blob: 9bd6378a16c729462e74998eb89d53b38f97d2b0 [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>
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Tim Peters5af4e6c2002-08-12 02:31:19 +000013/* For long multiplication, use the O(N**2) school algorithm unless
14 * both operands contain more than KARATSUBA_CUTOFF digits (this
Christian Heimes7f39c9f2008-01-25 12:18:43 +000015 * being an internal Python long digit, in base PyLong_BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000016 */
Tim Peters0973b992004-08-29 22:16:50 +000017#define KARATSUBA_CUTOFF 70
18#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000019
Tim Peters47e52ee2004-08-30 02:44:38 +000020/* For exponentiation, use the binary left-to-right algorithm
21 * unless the exponent contains more than FIVEARY_CUTOFF digits.
22 * In that case, do 5 bits at a time. The potential drawback is that
23 * a table of 2**5 intermediate results is computed.
24 */
25#define FIVEARY_CUTOFF 8
26
Guido van Rossume32e0141992-01-19 16:31:05 +000027#define ABS(x) ((x) < 0 ? -(x) : (x))
28
Tim Peters5af4e6c2002-08-12 02:31:19 +000029#undef MIN
30#undef MAX
31#define MAX(x, y) ((x) < (y) ? (y) : (x))
32#define MIN(x, y) ((x) > (y) ? (y) : (x))
33
Guido van Rossumc0b618a1997-05-02 03:12:38 +000034#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000035 if (--_Py_Ticker < 0) { \
36 _Py_Ticker = _Py_CheckInterval; \
Tim Petersd89fc222006-05-25 22:28:46 +000037 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +000038 }
39
Guido van Rossumedcc38a1991-05-05 20:09:44 +000040/* Normalize (remove leading zeros from) a long int object.
41 Doesn't attempt to free the storage--in most cases, due to the nature
42 of the algorithms used, this could save at most be one word anyway. */
43
Guido van Rossumc0b618a1997-05-02 03:12:38 +000044static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000045long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000046{
Christian Heimese93237d2007-12-19 02:37:44 +000047 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +000048 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +000049
Guido van Rossumedcc38a1991-05-05 20:09:44 +000050 while (i > 0 && v->ob_digit[i-1] == 0)
51 --i;
52 if (i != j)
Christian Heimese93237d2007-12-19 02:37:44 +000053 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +000054 return v;
55}
56
57/* Allocate a new long int object with size digits.
58 Return NULL and set exception if we run out of memory. */
59
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000060#define MAX_LONG_DIGITS \
61 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
62
Guido van Rossumc0b618a1997-05-02 03:12:38 +000063PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000064_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +000065{
Mark Dickinsonbcf6b182009-02-15 15:48:39 +000066 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000067 PyErr_SetString(PyExc_OverflowError,
68 "too many digits in integer");
Martin v. Löwis18e16552006-02-15 17:27:45 +000069 return NULL;
70 }
Christian Heimes4956d2b2008-01-18 19:12:56 +000071 /* coverity[ampersand_in_size] */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +000072 /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
73 overflow */
Guido van Rossumc0b618a1997-05-02 03:12:38 +000074 return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +000075}
76
Tim Peters64b5ce32001-09-10 20:52:51 +000077PyObject *
78_PyLong_Copy(PyLongObject *src)
79{
80 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +000081 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +000082
83 assert(src != NULL);
84 i = src->ob_size;
85 if (i < 0)
86 i = -(i);
87 result = _PyLong_New(i);
88 if (result != NULL) {
Tim Peters5329cdb2002-03-02 04:18:04 +000089 result->ob_size = src->ob_size;
Tim Peters64b5ce32001-09-10 20:52:51 +000090 while (--i >= 0)
91 result->ob_digit[i] = src->ob_digit[i];
92 }
93 return (PyObject *)result;
94}
95
Guido van Rossumedcc38a1991-05-05 20:09:44 +000096/* Create a new long int object from a C long int */
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +000099PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000100{
Tim Petersce9de2f2001-06-14 04:56:19 +0000101 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000102 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000103 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
104 int ndigits = 0;
105 int negative = 0;
106
107 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000108 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
109 ANSI C says that the result of -ival is undefined when ival
110 == LONG_MIN. Hence the following workaround. */
111 abs_ival = (unsigned long)(-1-ival) + 1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000112 negative = 1;
113 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000114 else {
115 abs_ival = (unsigned long)ival;
116 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000117
118 /* Count the number of Python digits.
119 We used to pick 5 ("big enough for anything"), but that's a
120 waste of time and space given that 5*15 = 75 bits are rarely
121 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000122 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000123 while (t) {
124 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000125 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000126 }
127 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000129 digit *p = v->ob_digit;
130 v->ob_size = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000131 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000132 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000133 *p++ = (digit)(t & PyLong_MASK);
134 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000135 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000137 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000138}
139
Guido van Rossum53756b11997-01-03 17:14:46 +0000140/* Create a new long int object from a C unsigned long int */
141
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000143PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000144{
Tim Petersce9de2f2001-06-14 04:56:19 +0000145 PyLongObject *v;
146 unsigned long t;
147 int ndigits = 0;
148
149 /* Count the number of Python digits. */
150 t = (unsigned long)ival;
151 while (t) {
152 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000153 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000154 }
155 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000156 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000157 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000158 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000159 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000160 *p++ = (digit)(ival & PyLong_MASK);
161 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000162 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000163 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000164 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000165}
166
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000167/* Create a new long int object from a C double */
168
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000171{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000173 double frac;
174 int i, ndig, expo, neg;
175 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000176 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000177 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsonb6467572008-08-04 21:30:09 +0000178 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000179 return NULL;
180 }
Christian Heimes8267d1d2008-01-04 00:37:34 +0000181 if (Py_IS_NAN(dval)) {
Mark Dickinsonb6467572008-08-04 21:30:09 +0000182 PyErr_SetString(PyExc_ValueError,
183 "cannot convert float NaN to integer");
184 return NULL;
Christian Heimes8267d1d2008-01-04 00:37:34 +0000185 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000186 if (dval < 0.0) {
187 neg = 1;
188 dval = -dval;
189 }
190 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
191 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 return PyLong_FromLong(0L);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000193 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000195 if (v == NULL)
196 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000197 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000198 for (i = ndig; --i >= 0; ) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000199 digit bits = (digit)frac;
200 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000201 frac = frac - (double)bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000202 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000203 }
204 if (neg)
Christian Heimese93237d2007-12-19 02:37:44 +0000205 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000206 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000207}
208
Armin Rigo7ccbca92006-10-04 12:17:45 +0000209/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
210 * anything about what happens when a signed integer operation overflows,
211 * and some compilers think they're doing you a favor by being "clever"
212 * then. The bit pattern for the largest postive signed long is
213 * (unsigned long)LONG_MAX, and for the smallest negative signed long
214 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
215 * However, some other compilers warn about applying unary minus to an
216 * unsigned operand. Hence the weird "0-".
217 */
218#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
219#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
220
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000221/* Get a C long int from a long int object.
222 Returns -1 and sets an error condition if overflow occurs. */
223
224long
Tim Peters9f688bf2000-07-07 15:53:28 +0000225PyLong_AsLong(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000226{
Guido van Rossumf7531811998-05-26 14:33:37 +0000227 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000229 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000230 Py_ssize_t i;
231 int sign;
Guido van Rossumf7531811998-05-26 14:33:37 +0000232
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000233 if (vv == NULL || !PyLong_Check(vv)) {
Guido van Rossum7e35d572001-09-15 03:14:32 +0000234 if (vv != NULL && PyInt_Check(vv))
235 return PyInt_AsLong(vv);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000236 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000237 return -1;
238 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000239 v = (PyLongObject *)vv;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240 i = v->ob_size;
241 sign = 1;
242 x = 0;
243 if (i < 0) {
244 sign = -1;
Guido van Rossum4c260ff1992-01-14 18:36:43 +0000245 i = -(i);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000246 }
247 while (--i >= 0) {
248 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000249 x = (x << PyLong_SHIFT) + v->ob_digit[i];
250 if ((x >> PyLong_SHIFT) != prev)
Guido van Rossumf7531811998-05-26 14:33:37 +0000251 goto overflow;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000252 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000253 /* Haven't lost any bits, but casting to long requires extra care
254 * (see comment above).
255 */
256 if (x <= (unsigned long)LONG_MAX) {
257 return (long)x * sign;
258 }
259 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
260 return LONG_MIN;
261 }
262 /* else overflow */
Guido van Rossumf7531811998-05-26 14:33:37 +0000263
264 overflow:
265 PyErr_SetString(PyExc_OverflowError,
Skip Montanarobafedec2001-09-13 19:05:30 +0000266 "long int too large to convert to int");
Guido van Rossumf7531811998-05-26 14:33:37 +0000267 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000268}
269
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000270/* Get a Py_ssize_t from a long int object.
271 Returns -1 and sets an error condition if overflow occurs. */
272
273Py_ssize_t
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000274PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000275 register PyLongObject *v;
276 size_t x, prev;
277 Py_ssize_t i;
278 int sign;
279
280 if (vv == NULL || !PyLong_Check(vv)) {
281 PyErr_BadInternalCall();
282 return -1;
283 }
284 v = (PyLongObject *)vv;
285 i = v->ob_size;
286 sign = 1;
287 x = 0;
288 if (i < 0) {
289 sign = -1;
290 i = -(i);
291 }
292 while (--i >= 0) {
293 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000294 x = (x << PyLong_SHIFT) + v->ob_digit[i];
295 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000296 goto overflow;
297 }
Armin Rigo7ccbca92006-10-04 12:17:45 +0000298 /* Haven't lost any bits, but casting to a signed type requires
299 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000300 */
Armin Rigo7ccbca92006-10-04 12:17:45 +0000301 if (x <= (size_t)PY_SSIZE_T_MAX) {
302 return (Py_ssize_t)x * sign;
303 }
304 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
305 return PY_SSIZE_T_MIN;
306 }
307 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000308
309 overflow:
310 PyErr_SetString(PyExc_OverflowError,
311 "long int too large to convert to int");
Neal Norwitz8a87f5d2006-08-12 17:03:09 +0000312 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000313}
314
Guido van Rossumd8c80482002-08-13 00:24:58 +0000315/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000316 Returns -1 and sets an error condition if overflow occurs. */
317
318unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000319PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000320{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000322 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000323 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000324
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000325 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000326 if (vv != NULL && PyInt_Check(vv)) {
327 long val = PyInt_AsLong(vv);
328 if (val < 0) {
329 PyErr_SetString(PyExc_OverflowError,
330 "can't convert negative value to unsigned long");
331 return (unsigned long) -1;
332 }
333 return val;
334 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000336 return (unsigned long) -1;
337 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000339 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000340 x = 0;
341 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum53756b11997-01-03 17:14:46 +0000343 "can't convert negative value to unsigned long");
344 return (unsigned long) -1;
345 }
346 while (--i >= 0) {
347 prev = x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000348 x = (x << PyLong_SHIFT) + v->ob_digit[i];
349 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +0000351 "long int too large to convert");
Guido van Rossum53756b11997-01-03 17:14:46 +0000352 return (unsigned long) -1;
353 }
354 }
355 return x;
356}
357
Thomas Hellera4ea6032003-04-17 18:55:45 +0000358/* Get a C unsigned long int from a long int object, ignoring the high bits.
359 Returns -1 and sets an error condition if an error occurs. */
360
361unsigned long
362PyLong_AsUnsignedLongMask(PyObject *vv)
363{
364 register PyLongObject *v;
365 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000366 Py_ssize_t i;
367 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000368
369 if (vv == NULL || !PyLong_Check(vv)) {
Martin v. Löwis729d47d2004-09-20 06:17:46 +0000370 if (vv != NULL && PyInt_Check(vv))
371 return PyInt_AsUnsignedLongMask(vv);
Thomas Hellera4ea6032003-04-17 18:55:45 +0000372 PyErr_BadInternalCall();
373 return (unsigned long) -1;
374 }
375 v = (PyLongObject *)vv;
376 i = v->ob_size;
377 sign = 1;
378 x = 0;
379 if (i < 0) {
380 sign = -1;
381 i = -i;
382 }
383 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000384 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000385 }
386 return x * sign;
387}
388
Tim Peters5b8132f2003-01-31 15:52:05 +0000389int
390_PyLong_Sign(PyObject *vv)
391{
392 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000393
394 assert(v != NULL);
395 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000396
Christian Heimese93237d2007-12-19 02:37:44 +0000397 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000398}
399
Tim Petersbaefd9e2003-01-28 20:37:45 +0000400size_t
401_PyLong_NumBits(PyObject *vv)
402{
403 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000404 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000405 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000406
407 assert(v != NULL);
408 assert(PyLong_Check(v));
Christian Heimese93237d2007-12-19 02:37:44 +0000409 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000410 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
411 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000412 digit msd = v->ob_digit[ndigits - 1];
413
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000414 result = (ndigits - 1) * PyLong_SHIFT;
415 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000416 goto Overflow;
417 do {
418 ++result;
419 if (result == 0)
420 goto Overflow;
421 msd >>= 1;
422 } while (msd);
423 }
424 return result;
425
426Overflow:
427 PyErr_SetString(PyExc_OverflowError, "long has too many bits "
428 "to express in a platform size_t");
429 return (size_t)-1;
430}
431
Tim Peters2a9b3672001-06-11 21:23:58 +0000432PyObject *
433_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
434 int little_endian, int is_signed)
435{
436 const unsigned char* pstartbyte;/* LSB of bytes */
437 int incr; /* direction to move pstartbyte */
438 const unsigned char* pendbyte; /* MSB of bytes */
439 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000440 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000441 PyLongObject* v; /* result */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000442 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000443
444 if (n == 0)
445 return PyLong_FromLong(0L);
446
447 if (little_endian) {
448 pstartbyte = bytes;
449 pendbyte = bytes + n - 1;
450 incr = 1;
451 }
452 else {
453 pstartbyte = bytes + n - 1;
454 pendbyte = bytes;
455 incr = -1;
456 }
457
458 if (is_signed)
459 is_signed = *pendbyte >= 0x80;
460
461 /* Compute numsignificantbytes. This consists of finding the most
462 significant byte. Leading 0 bytes are insignficant if the number
463 is positive, and leading 0xff bytes if negative. */
464 {
465 size_t i;
466 const unsigned char* p = pendbyte;
467 const int pincr = -incr; /* search MSB to LSB */
468 const unsigned char insignficant = is_signed ? 0xff : 0x00;
469
470 for (i = 0; i < n; ++i, p += pincr) {
471 if (*p != insignficant)
472 break;
473 }
474 numsignificantbytes = n - i;
475 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
476 actually has 2 significant bytes. OTOH, 0xff0001 ==
477 -0x00ffff, so we wouldn't *need* to bump it there; but we
478 do for 0xffff = -0x0001. To be safe without bothering to
479 check every case, bump it regardless. */
480 if (is_signed && numsignificantbytes < n)
481 ++numsignificantbytes;
482 }
483
484 /* How many Python long digits do we need? We have
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000485 8*numsignificantbytes bits, and each Python long digit has
486 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
487 /* catch overflow before it happens */
488 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
489 PyErr_SetString(PyExc_OverflowError,
490 "byte array too long to convert to int");
491 return NULL;
492 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000493 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000494 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000495 if (v == NULL)
496 return NULL;
497
498 /* Copy the bits over. The tricky parts are computing 2's-comp on
499 the fly for signed numbers, and dealing with the mismatch between
500 8-bit bytes and (probably) 15-bit Python digits.*/
501 {
502 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000503 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000504 twodigits accum = 0; /* sliding register */
505 unsigned int accumbits = 0; /* number of bits in accum */
506 const unsigned char* p = pstartbyte;
507
508 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000509 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000510 /* Compute correction for 2's comp, if needed. */
511 if (is_signed) {
512 thisbyte = (0xff ^ thisbyte) + carry;
513 carry = thisbyte >> 8;
514 thisbyte &= 0xff;
515 }
516 /* Because we're going LSB to MSB, thisbyte is
517 more significant than what's already in accum,
518 so needs to be prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000519 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000520 accumbits += 8;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000521 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000522 /* There's enough to fill a Python digit. */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000523 assert(idigit < ndigits);
524 v->ob_digit[idigit] = (digit)(accum &
525 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000526 ++idigit;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000527 accum >>= PyLong_SHIFT;
528 accumbits -= PyLong_SHIFT;
529 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000530 }
531 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000532 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000533 if (accumbits) {
Mark Dickinson2ffb26f2009-02-15 10:13:41 +0000534 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000535 v->ob_digit[idigit] = (digit)accum;
536 ++idigit;
537 }
538 }
539
Christian Heimese93237d2007-12-19 02:37:44 +0000540 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000541 return (PyObject *)long_normalize(v);
542}
543
544int
545_PyLong_AsByteArray(PyLongObject* v,
546 unsigned char* bytes, size_t n,
547 int little_endian, int is_signed)
548{
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000549 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000550 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000551 twodigits accum; /* sliding register */
552 unsigned int accumbits; /* # bits in accum */
553 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1afe6dd2009-01-25 22:12:31 +0000554 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000555 size_t j; /* # bytes filled */
556 unsigned char* p; /* pointer to next byte in bytes */
557 int pincr; /* direction to move p */
558
559 assert(v != NULL && PyLong_Check(v));
560
Christian Heimese93237d2007-12-19 02:37:44 +0000561 if (Py_SIZE(v) < 0) {
562 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000563 if (!is_signed) {
Mark Dickinson4015f622009-02-10 15:46:50 +0000564 PyErr_SetString(PyExc_OverflowError,
Tim Peters2a9b3672001-06-11 21:23:58 +0000565 "can't convert negative long to unsigned");
566 return -1;
567 }
568 do_twos_comp = 1;
569 }
570 else {
Christian Heimese93237d2007-12-19 02:37:44 +0000571 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000572 do_twos_comp = 0;
573 }
574
575 if (little_endian) {
576 p = bytes;
577 pincr = 1;
578 }
579 else {
580 p = bytes + n - 1;
581 pincr = -1;
582 }
583
Tim Peters898cf852001-06-13 20:50:08 +0000584 /* Copy over all the Python digits.
585 It's crucial that every Python digit except for the MSD contribute
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000586 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000587 normalized. */
588 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000589 j = 0;
590 accum = 0;
591 accumbits = 0;
592 carry = do_twos_comp ? 1 : 0;
593 for (i = 0; i < ndigits; ++i) {
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000594 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000595 if (do_twos_comp) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000596 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
597 carry = thisdigit >> PyLong_SHIFT;
598 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000599 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000600 /* Because we're going LSB to MSB, thisdigit is more
601 significant than what's already in accum, so needs to be
602 prepended to accum. */
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000603 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000604
Tim Petersede05092001-06-14 08:53:38 +0000605 /* The most-significant digit may be (probably is) at least
606 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000607 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000608 /* Count # of sign bits -- they needn't be stored,
609 * although for signed conversion we need later to
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000610 * make sure at least one sign bit gets stored. */
611 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
612 thisdigit;
613 while (s != 0) {
614 s >>= 1;
615 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000616 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000617 }
Mark Dickinsonff84aa82009-01-24 15:27:44 +0000618 else
619 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000620
Tim Peters2a9b3672001-06-11 21:23:58 +0000621 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000622 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000623 if (j >= n)
624 goto Overflow;
625 ++j;
626 *p = (unsigned char)(accum & 0xff);
627 p += pincr;
628 accumbits -= 8;
629 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000630 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000631 }
632
633 /* Store the straggler (if any). */
634 assert(accumbits < 8);
635 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000636 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000637 if (j >= n)
638 goto Overflow;
639 ++j;
640 if (do_twos_comp) {
641 /* Fill leading bits of the byte with sign bits
642 (appropriately pretending that the long had an
643 infinite supply of sign bits). */
644 accum |= (~(twodigits)0) << accumbits;
645 }
646 *p = (unsigned char)(accum & 0xff);
647 p += pincr;
648 }
Tim Peters05607ad2001-06-13 21:01:27 +0000649 else if (j == n && n > 0 && is_signed) {
650 /* The main loop filled the byte array exactly, so the code
651 just above didn't get to ensure there's a sign bit, and the
652 loop below wouldn't add one either. Make sure a sign bit
653 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000654 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000655 int sign_bit_set = msb >= 0x80;
656 assert(accumbits == 0);
657 if (sign_bit_set == do_twos_comp)
658 return 0;
659 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000660 goto Overflow;
661 }
Tim Peters05607ad2001-06-13 21:01:27 +0000662
663 /* Fill remaining bytes with copies of the sign bit. */
664 {
665 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
666 for ( ; j < n; ++j, p += pincr)
667 *p = signbyte;
668 }
669
Tim Peters2a9b3672001-06-11 21:23:58 +0000670 return 0;
671
672Overflow:
673 PyErr_SetString(PyExc_OverflowError, "long too big to convert");
674 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000675
Tim Peters2a9b3672001-06-11 21:23:58 +0000676}
677
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000678double
679_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
680{
681/* NBITS_WANTED should be > the number of bits in a double's precision,
682 but small enough so that 2**NBITS_WANTED is within the normal double
683 range. nbitsneeded is set to 1 less than that because the most-significant
684 Python digit contains at least 1 significant bit, but we don't want to
685 bother counting them (catering to the worst case cheaply).
686
687 57 is one more than VAX-D double precision; I (Tim) don't know of a double
688 format with more precision than that; it's 1 larger so that we add in at
689 least one round bit to stand in for the ignored least-significant bits.
690*/
691#define NBITS_WANTED 57
692 PyLongObject *v;
693 double x;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000694 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000695 Py_ssize_t i;
696 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000697 int nbitsneeded;
698
699 if (vv == NULL || !PyLong_Check(vv)) {
700 PyErr_BadInternalCall();
701 return -1;
702 }
703 v = (PyLongObject *)vv;
Christian Heimese93237d2007-12-19 02:37:44 +0000704 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000705 sign = 1;
706 if (i < 0) {
707 sign = -1;
708 i = -(i);
709 }
710 else if (i == 0) {
711 *exponent = 0;
712 return 0.0;
713 }
714 --i;
715 x = (double)v->ob_digit[i];
716 nbitsneeded = NBITS_WANTED - 1;
717 /* Invariant: i Python digits remain unaccounted for. */
718 while (i > 0 && nbitsneeded > 0) {
719 --i;
720 x = x * multiplier + (double)v->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000721 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000722 }
723 /* There are i digits we didn't shift in. Pretending they're all
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000724 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000725 *exponent = i;
726 assert(x > 0.0);
727 return x * sign;
728#undef NBITS_WANTED
729}
730
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000731/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000732
733double
Tim Peters9f688bf2000-07-07 15:53:28 +0000734PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000735{
Thomas Wouters553489a2006-02-01 21:32:04 +0000736 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000737 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000738
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000739 if (vv == NULL || !PyLong_Check(vv)) {
740 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000741 return -1;
742 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000743 x = _PyLong_AsScaledDouble(vv, &e);
744 if (x == -1.0 && PyErr_Occurred())
745 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000746 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
747 set correctly after a successful _PyLong_AsScaledDouble() call */
748 assert(e >= 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000749 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000750 goto overflow;
751 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000752 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000753 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000754 goto overflow;
755 return x;
756
757overflow:
758 PyErr_SetString(PyExc_OverflowError,
759 "long int too large to convert to float");
760 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000761}
762
Guido van Rossum78694d91998-09-18 14:14:13 +0000763/* Create a new long (or int) object from a C pointer */
764
765PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000766PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000767{
Tim Peters70128a12001-06-16 08:48:40 +0000768#if SIZEOF_VOID_P <= SIZEOF_LONG
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000769 if ((long)p < 0)
770 return PyLong_FromUnsignedLong((unsigned long)p);
Guido van Rossum78694d91998-09-18 14:14:13 +0000771 return PyInt_FromLong((long)p);
772#else
Guido van Rossum78694d91998-09-18 14:14:13 +0000773
Tim Peters70128a12001-06-16 08:48:40 +0000774#ifndef HAVE_LONG_LONG
775# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
776#endif
777#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000778# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000779#endif
780 /* optimize null pointers */
781 if (p == NULL)
782 return PyInt_FromLong(0);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000783 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
Tim Peters70128a12001-06-16 08:48:40 +0000784
785#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000786}
787
788/* Get a C pointer from a long object (or an int object in some cases) */
789
790void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000791PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000792{
793 /* This function will allow int or long objects. If vv is neither,
794 then the PyLong_AsLong*() functions will raise the exception:
795 PyExc_SystemError, "bad argument to internal function"
796 */
Tim Peters70128a12001-06-16 08:48:40 +0000797#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000798 long x;
799
Tim Peters70128a12001-06-16 08:48:40 +0000800 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000801 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000802 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000803 x = PyLong_AsLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000804 else
805 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000806#else
Tim Peters70128a12001-06-16 08:48:40 +0000807
808#ifndef HAVE_LONG_LONG
809# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
810#endif
811#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000812# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000813#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000814 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000815
Tim Peters70128a12001-06-16 08:48:40 +0000816 if (PyInt_Check(vv))
Guido van Rossum78694d91998-09-18 14:14:13 +0000817 x = PyInt_AS_LONG(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000818 else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000819 x = PyLong_AsLongLong(vv);
Martin v. Löwis0bc2ab92006-04-10 20:28:17 +0000820 else
821 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000822
823#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000824
825 if (x == -1 && PyErr_Occurred())
826 return NULL;
827 return (void *)x;
828}
829
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000830#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000831
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000832/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000833 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000834 */
835
Tim Peterscf37dfc2001-06-14 18:42:50 +0000836#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +0000837
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000838/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000839
840PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000841PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000842{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000843 PyLongObject *v;
Mark Dickinson27a63252008-04-15 20:51:18 +0000844 unsigned PY_LONG_LONG abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000845 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
846 int ndigits = 0;
847 int negative = 0;
848
849 if (ival < 0) {
Mark Dickinson27a63252008-04-15 20:51:18 +0000850 /* avoid signed overflow on negation; see comments
851 in PyLong_FromLong above. */
852 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000853 negative = 1;
854 }
Mark Dickinson27a63252008-04-15 20:51:18 +0000855 else {
856 abs_ival = (unsigned PY_LONG_LONG)ival;
857 }
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000858
859 /* Count the number of Python digits.
860 We used to pick 5 ("big enough for anything"), but that's a
861 waste of time and space given that 5*15 = 75 bits are rarely
862 needed. */
Mark Dickinson27a63252008-04-15 20:51:18 +0000863 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000864 while (t) {
865 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000866 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000867 }
868 v = _PyLong_New(ndigits);
869 if (v != NULL) {
870 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000871 Py_SIZE(v) = negative ? -ndigits : ndigits;
Mark Dickinson27a63252008-04-15 20:51:18 +0000872 t = abs_ival;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000873 while (t) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000874 *p++ = (digit)(t & PyLong_MASK);
875 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000876 }
877 }
878 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000879}
880
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000881/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +0000882
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000883PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000884PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000885{
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000886 PyLongObject *v;
887 unsigned PY_LONG_LONG t;
888 int ndigits = 0;
889
890 /* Count the number of Python digits. */
891 t = (unsigned PY_LONG_LONG)ival;
892 while (t) {
893 ++ndigits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000894 t >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000895 }
896 v = _PyLong_New(ndigits);
897 if (v != NULL) {
898 digit *p = v->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +0000899 Py_SIZE(v) = ndigits;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000900 while (ival) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000901 *p++ = (digit)(ival & PyLong_MASK);
902 ival >>= PyLong_SHIFT;
Bob Ippolitoa85bf202006-05-25 18:20:23 +0000903 }
904 }
905 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000906}
907
Martin v. Löwis18e16552006-02-15 17:27:45 +0000908/* Create a new long int object from a C Py_ssize_t. */
909
910PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000911PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912{
913 Py_ssize_t bytes = ival;
914 int one = 1;
915 return _PyLong_FromByteArray(
916 (unsigned char *)&bytes,
Kristján Valur Jónssonf0303942007-05-03 20:27:03 +0000917 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000918}
919
920/* Create a new long int object from a C size_t. */
921
922PyObject *
Christian Heimes7f39c9f2008-01-25 12:18:43 +0000923PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000924{
925 size_t bytes = ival;
926 int one = 1;
927 return _PyLong_FromByteArray(
928 (unsigned char *)&bytes,
929 SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
930}
931
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000932/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000933 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000934
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000935PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000936PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000937{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000938 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000939 int one = 1;
940 int res;
941
Tim Petersd38b1c72001-09-30 05:09:37 +0000942 if (vv == NULL) {
943 PyErr_BadInternalCall();
944 return -1;
945 }
946 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000947 PyNumberMethods *nb;
948 PyObject *io;
Tim Petersd38b1c72001-09-30 05:09:37 +0000949 if (PyInt_Check(vv))
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000950 return (PY_LONG_LONG)PyInt_AsLong(vv);
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +0000951 if ((nb = vv->ob_type->tp_as_number) == NULL ||
952 nb->nb_int == NULL) {
953 PyErr_SetString(PyExc_TypeError, "an integer is required");
954 return -1;
955 }
956 io = (*nb->nb_int) (vv);
957 if (io == NULL)
958 return -1;
959 if (PyInt_Check(io)) {
960 bytes = PyInt_AsLong(io);
961 Py_DECREF(io);
962 return bytes;
963 }
964 if (PyLong_Check(io)) {
965 bytes = PyLong_AsLongLong(io);
966 Py_DECREF(io);
967 return bytes;
968 }
969 Py_DECREF(io);
970 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000971 return -1;
972 }
973
Tim Petersd1a7da62001-06-13 00:35:57 +0000974 res = _PyLong_AsByteArray(
975 (PyLongObject *)vv, (unsigned char *)&bytes,
976 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000977
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000978 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000979 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000980 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +0000981 else
982 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000983}
984
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000985/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +0000986 Return -1 and set an error if overflow occurs. */
987
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000988unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +0000989PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000990{
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000991 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +0000992 int one = 1;
993 int res;
994
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000995 if (vv == NULL || !PyLong_Check(vv)) {
996 PyErr_BadInternalCall();
Skip Montanaro429433b2006-04-18 00:35:43 +0000997 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000998 }
999
Tim Petersd1a7da62001-06-13 00:35:57 +00001000 res = _PyLong_AsByteArray(
1001 (PyLongObject *)vv, (unsigned char *)&bytes,
1002 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001003
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001004 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001005 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001006 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001007 else
1008 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001009}
Tim Petersd1a7da62001-06-13 00:35:57 +00001010
Thomas Hellera4ea6032003-04-17 18:55:45 +00001011/* Get a C unsigned long int from a long int object, ignoring the high bits.
1012 Returns -1 and sets an error condition if an error occurs. */
1013
1014unsigned PY_LONG_LONG
1015PyLong_AsUnsignedLongLongMask(PyObject *vv)
1016{
1017 register PyLongObject *v;
1018 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001019 Py_ssize_t i;
1020 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001021
1022 if (vv == NULL || !PyLong_Check(vv)) {
1023 PyErr_BadInternalCall();
1024 return (unsigned long) -1;
1025 }
1026 v = (PyLongObject *)vv;
1027 i = v->ob_size;
1028 sign = 1;
1029 x = 0;
1030 if (i < 0) {
1031 sign = -1;
1032 i = -i;
1033 }
1034 while (--i >= 0) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001035 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001036 }
1037 return x * sign;
1038}
Tim Petersd1a7da62001-06-13 00:35:57 +00001039#undef IS_LITTLE_ENDIAN
1040
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041#endif /* HAVE_LONG_LONG */
1042
Neil Schemenauerba872e22001-01-04 01:46:03 +00001043
1044static int
1045convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00001046 if (PyLong_Check(v)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001047 *a = (PyLongObject *) v;
1048 Py_INCREF(v);
1049 }
1050 else if (PyInt_Check(v)) {
1051 *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
1052 }
1053 else {
1054 return 0;
1055 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001056 if (PyLong_Check(w)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00001057 *b = (PyLongObject *) w;
1058 Py_INCREF(w);
1059 }
1060 else if (PyInt_Check(w)) {
1061 *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
1062 }
1063 else {
1064 Py_DECREF(*a);
1065 return 0;
1066 }
1067 return 1;
1068}
1069
1070#define CONVERT_BINOP(v, w, a, b) \
1071 if (!convert_binop(v, w, a, b)) { \
1072 Py_INCREF(Py_NotImplemented); \
1073 return Py_NotImplemented; \
1074 }
1075
Tim Peters877a2122002-08-12 05:09:36 +00001076/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1077 * is modified in place, by adding y to it. Carries are propagated as far as
1078 * x[m-1], and the remaining carry (0 or 1) is returned.
1079 */
1080static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001082{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001083 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001084 digit carry = 0;
1085
1086 assert(m >= n);
1087 for (i = 0; i < n; ++i) {
1088 carry += x[i] + y[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001089 x[i] = carry & PyLong_MASK;
1090 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001091 assert((carry & 1) == carry);
1092 }
1093 for (; carry && i < m; ++i) {
1094 carry += x[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001095 x[i] = carry & PyLong_MASK;
1096 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001097 assert((carry & 1) == carry);
1098 }
1099 return carry;
1100}
1101
1102/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1103 * is modified in place, by subtracting y from it. Borrows are propagated as
1104 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1105 */
1106static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001107v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001108{
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001109 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001110 digit borrow = 0;
1111
1112 assert(m >= n);
1113 for (i = 0; i < n; ++i) {
1114 borrow = x[i] - y[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001115 x[i] = borrow & PyLong_MASK;
1116 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001117 borrow &= 1; /* keep only 1 sign bit */
1118 }
1119 for (; borrow && i < m; ++i) {
1120 borrow = x[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001121 x[i] = borrow & PyLong_MASK;
1122 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001123 borrow &= 1;
1124 }
1125 return borrow;
1126}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001127
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001128/* Multiply by a single digit, ignoring the sign. */
1129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001130static PyLongObject *
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001131mul1(PyLongObject *a, digit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001132{
Christian Heimese93237d2007-12-19 02:37:44 +00001133 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001134 PyLongObject *z = _PyLong_New(size_a+1);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001135 twodigits carry = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001136 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001137
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001138 if (z == NULL)
1139 return NULL;
1140 for (i = 0; i < size_a; ++i) {
1141 carry += (twodigits)a->ob_digit[i] * n;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001142 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1143 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001144 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001145 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001146 return long_normalize(z);
1147}
1148
Tim Peters212e6142001-07-14 12:23:19 +00001149/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1150 in pout, and returning the remainder. pin and pout point at the LSD.
1151 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Eric Smith5e527eb2008-02-10 01:36:53 +00001152 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001153 immutable. */
1154
1155static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001156inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001157{
1158 twodigits rem = 0;
1159
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001160 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001161 pin += size;
1162 pout += size;
1163 while (--size >= 0) {
1164 digit hi;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001165 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001166 *--pout = hi = (digit)(rem / n);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001167 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001168 }
1169 return (digit)rem;
1170}
1171
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001172/* Divide a long integer by a digit, returning both the quotient
1173 (as function result) and the remainder (through *prem).
1174 The sign of a is ignored; n should not be zero. */
1175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001176static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001177divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001178{
Christian Heimese93237d2007-12-19 02:37:44 +00001179 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001180 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001181
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001182 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001183 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001184 if (z == NULL)
1185 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001186 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001187 return long_normalize(z);
1188}
1189
Eric Smith5e527eb2008-02-10 01:36:53 +00001190/* Convert the long to a string object with given base,
1191 appending a base prefix of 0[box] if base is 2, 8 or 16.
1192 Add a trailing "L" if addL is non-zero.
1193 If newstyle is zero, then use the pre-2.6 behavior of octal having
1194 a leading "0", instead of the prefix "0o" */
1195PyAPI_FUNC(PyObject *)
1196_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001197{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001198 register PyLongObject *a = (PyLongObject *)aa;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001199 PyStringObject *str;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001200 Py_ssize_t i, j, sz;
Neal Norwitzc09efa82006-07-23 07:53:14 +00001201 Py_ssize_t size_a;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001202 char *p;
1203 int bits;
1204 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001205
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001206 if (a == NULL || !PyLong_Check(a)) {
1207 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001208 return NULL;
1209 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001210 assert(base >= 2 && base <= 36);
Christian Heimese93237d2007-12-19 02:37:44 +00001211 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001212
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001213 /* Compute a rough upper bound for the length of the string */
1214 i = base;
1215 bits = 0;
1216 while (i > 1) {
1217 ++bits;
1218 i >>= 1;
1219 }
Armin Rigo7ccbca92006-10-04 12:17:45 +00001220 i = 5 + (addL ? 1 : 0);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001221 j = size_a*PyLong_SHIFT + bits-1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001222 sz = i + j / bits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001223 if (j / PyLong_SHIFT < size_a || sz < i) {
Armin Rigo7ccbca92006-10-04 12:17:45 +00001224 PyErr_SetString(PyExc_OverflowError,
1225 "long is too large to format");
1226 return NULL;
1227 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001228 str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001229 if (str == NULL)
1230 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001231 p = PyString_AS_STRING(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001232 *p = '\0';
Fred Drake121ee271999-12-23 15:41:28 +00001233 if (addL)
1234 *--p = 'L';
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001235 if (a->ob_size < 0)
1236 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001237
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001238 if (a->ob_size == 0) {
1239 *--p = '0';
1240 }
1241 else if ((base & (base - 1)) == 0) {
1242 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001243 twodigits accum = 0;
1244 int accumbits = 0; /* # of bits in accum */
1245 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001246 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001247 while ((i >>= 1) > 1)
1248 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001249
1250 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001251 accum |= (twodigits)a->ob_digit[i] << accumbits;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001252 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001253 assert(accumbits >= basebits);
1254 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001255 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001256 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001257 assert(p > PyString_AS_STRING(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001258 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001259 accumbits -= basebits;
1260 accum >>= basebits;
1261 } while (i < size_a-1 ? accumbits >= basebits :
1262 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001263 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001264 }
1265 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001266 /* Not 0, and base not a power of 2. Divide repeatedly by
1267 base, but for speed use the highest power of base that
1268 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001269 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001270 digit *pin = a->ob_digit;
1271 PyLongObject *scratch;
1272 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001273 digit powbase = base; /* powbase == base ** power */
1274 int power = 1;
1275 for (;;) {
Mark Dickinsonb6464872009-02-25 20:29:50 +00001276 twodigits newpow = powbase * (twodigits)base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001277 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001278 break;
1279 powbase = (digit)newpow;
1280 ++power;
1281 }
Tim Peters212e6142001-07-14 12:23:19 +00001282
1283 /* Get a scratch area for repeated division. */
1284 scratch = _PyLong_New(size);
1285 if (scratch == NULL) {
1286 Py_DECREF(str);
1287 return NULL;
1288 }
1289
1290 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001291 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001292 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001293 digit rem = inplace_divrem1(scratch->ob_digit,
1294 pin, size, powbase);
1295 pin = scratch->ob_digit; /* no need to use a again */
1296 if (pin[size - 1] == 0)
1297 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001298 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001299 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001300 Py_DECREF(str);
1301 return NULL;
1302 })
Tim Peters212e6142001-07-14 12:23:19 +00001303
1304 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001305 assert(ntostore > 0);
1306 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001307 digit nextrem = (digit)(rem / base);
1308 char c = (char)(rem - nextrem * base);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001309 assert(p > PyString_AS_STRING(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001310 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001311 *--p = c;
1312 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001313 --ntostore;
1314 /* Termination is a bit delicate: must not
1315 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001316 remaining quotient and rem are both 0. */
1317 } while (ntostore && (size || rem));
1318 } while (size != 0);
1319 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001320 }
1321
Eric Smith5e527eb2008-02-10 01:36:53 +00001322 if (base == 2) {
1323 *--p = 'b';
1324 *--p = '0';
1325 }
1326 else if (base == 8) {
1327 if (newstyle) {
1328 *--p = 'o';
Guido van Rossum2c475421992-08-14 15:13:07 +00001329 *--p = '0';
Eric Smith5e527eb2008-02-10 01:36:53 +00001330 }
1331 else
1332 if (size_a != 0)
1333 *--p = '0';
Guido van Rossum2c475421992-08-14 15:13:07 +00001334 }
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001335 else if (base == 16) {
1336 *--p = 'x';
1337 *--p = '0';
1338 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001339 else if (base != 10) {
1340 *--p = '#';
1341 *--p = '0' + base%10;
1342 if (base > 10)
1343 *--p = '0' + base/10;
1344 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001345 if (sign)
1346 *--p = sign;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001347 if (p != PyString_AS_STRING(str)) {
1348 char *q = PyString_AS_STRING(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001349 assert(p > q);
1350 do {
1351 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001352 q--;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001353 _PyString_Resize((PyObject **)&str,
1354 (Py_ssize_t) (q - PyString_AS_STRING(str)));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001355 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001356 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001357}
1358
Tim Petersda53afa2006-05-25 17:34:03 +00001359/* Table of digit values for 8-bit string -> integer conversion.
1360 * '0' maps to 0, ..., '9' maps to 9.
1361 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1362 * All other indices map to 37.
1363 * Note that when converting a base B string, a char c is a legitimate
1364 * base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
1365 */
1366int _PyLong_DigitValue[256] = {
Tim Peters696cf432006-05-24 21:10:40 +00001367 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1368 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1369 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1370 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1371 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1372 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1373 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1374 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1375 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1376 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1377 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1378 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1379 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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,
Tim Peters696cf432006-05-24 21:10:40 +00001383};
1384
1385/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001386 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1387 * non-digit (which may be *str!). A normalized long is returned.
1388 * The point to this routine is that it takes time linear in the number of
1389 * string characters.
1390 */
1391static PyLongObject *
1392long_from_binary_base(char **str, int base)
1393{
1394 char *p = *str;
1395 char *start = p;
1396 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001397 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001398 PyLongObject *z;
1399 twodigits accum;
1400 int bits_in_accum;
1401 digit *pdigit;
1402
1403 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1404 n = base;
1405 for (bits_per_char = -1; n; ++bits_per_char)
1406 n >>= 1;
1407 /* n <- total # of bits needed, while setting p to end-of-string */
1408 n = 0;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001409 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001410 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001411 *str = p;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001412 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1413 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Armin Rigo7ccbca92006-10-04 12:17:45 +00001414 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001415 PyErr_SetString(PyExc_ValueError,
1416 "long string too large to convert");
1417 return NULL;
1418 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001419 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001420 z = _PyLong_New(n);
1421 if (z == NULL)
1422 return NULL;
1423 /* Read string from right, and fill in long from left; i.e.,
1424 * from least to most significant in both.
1425 */
1426 accum = 0;
1427 bits_in_accum = 0;
1428 pdigit = z->ob_digit;
1429 while (--p >= start) {
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001430 int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001431 assert(k >= 0 && k < base);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001432 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001433 bits_in_accum += bits_per_char;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001434 if (bits_in_accum >= PyLong_SHIFT) {
1435 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001436 assert(pdigit - z->ob_digit <= n);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001437 accum >>= PyLong_SHIFT;
1438 bits_in_accum -= PyLong_SHIFT;
1439 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001440 }
1441 }
1442 if (bits_in_accum) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001443 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001444 *pdigit++ = (digit)accum;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001445 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001446 }
1447 while (pdigit - z->ob_digit < n)
1448 *pdigit++ = 0;
1449 return long_normalize(z);
1450}
1451
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001452PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001453PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001454{
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001455 int sign = 1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001456 char *start, *orig_str = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001457 PyLongObject *z;
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001458 PyObject *strobj, *strrepr;
1459 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001460
Guido van Rossum472c04f1996-12-05 21:57:21 +00001461 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001462 PyErr_SetString(PyExc_ValueError,
Fred Drake661ea262000-10-24 19:57:45 +00001463 "long() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001464 return NULL;
1465 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001466 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001467 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001468 if (*str == '+')
1469 ++str;
1470 else if (*str == '-') {
1471 ++str;
1472 sign = -1;
1473 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001474 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001475 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001476 if (base == 0) {
Eric Smith9ff19b52008-03-17 17:32:20 +00001477 /* No base given. Deduce the base from the contents
1478 of the string */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001479 if (str[0] != '0')
1480 base = 10;
1481 else if (str[1] == 'x' || str[1] == 'X')
1482 base = 16;
Eric Smith9ff19b52008-03-17 17:32:20 +00001483 else if (str[1] == 'o' || str[1] == 'O')
1484 base = 8;
1485 else if (str[1] == 'b' || str[1] == 'B')
1486 base = 2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001487 else
Eric Smith9ff19b52008-03-17 17:32:20 +00001488 /* "old" (C-style) octal literal, still valid in
1489 2.x, although illegal in 3.x */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001490 base = 8;
1491 }
Eric Smith9ff19b52008-03-17 17:32:20 +00001492 /* Whether or not we were deducing the base, skip leading chars
1493 as needed */
1494 if (str[0] == '0' &&
1495 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1496 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1497 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001498 str += 2;
Tim Peters696cf432006-05-24 21:10:40 +00001499
Guido van Rossume6762971998-06-22 03:54:46 +00001500 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001501 if ((base & (base - 1)) == 0)
1502 z = long_from_binary_base(&str, base);
1503 else {
Tim Peters696cf432006-05-24 21:10:40 +00001504/***
1505Binary bases can be converted in time linear in the number of digits, because
1506Python's representation base is binary. Other bases (including decimal!) use
1507the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001508
Tim Peters696cf432006-05-24 21:10:40 +00001509First some math: the largest integer that can be expressed in N base-B digits
1510is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1511case number of Python digits needed to hold it is the smallest integer n s.t.
1512
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001513 PyLong_BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1514 PyLong_BASE**n >= B**N [taking logs to base PyLong_BASE]
1515 n >= log(B**N)/log(PyLong_BASE) = N * log(B)/log(PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001516
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001517The static array log_base_PyLong_BASE[base] == log(base)/log(PyLong_BASE) so we can compute
Tim Peters696cf432006-05-24 21:10:40 +00001518this quickly. A Python long with that much space is reserved near the start,
1519and the result is computed into it.
1520
1521The input string is actually treated as being in base base**i (i.e., i digits
1522are processed at a time), where two more static arrays hold:
1523
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001524 convwidth_base[base] = the largest integer i such that base**i <= PyLong_BASE
Tim Peters696cf432006-05-24 21:10:40 +00001525 convmultmax_base[base] = base ** convwidth_base[base]
1526
1527The first of these is the largest i such that i consecutive input digits
1528must fit in a single Python digit. The second is effectively the input
1529base we're really using.
1530
1531Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1532convmultmax_base[base], the result is "simply"
1533
1534 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1535
1536where B = convmultmax_base[base].
Tim Peters9faa3ed2006-05-30 15:53:34 +00001537
1538Error analysis: as above, the number of Python digits `n` needed is worst-
1539case
1540
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001541 n >= N * log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001542
1543where `N` is the number of input digits in base `B`. This is computed via
1544
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001545 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001546
1547below. Two numeric concerns are how much space this can waste, and whether
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001548the computed result can be too small. To be concrete, assume PyLong_BASE = 2**15,
Tim Peters9faa3ed2006-05-30 15:53:34 +00001549which is the default (and it's unlikely anyone changes that).
1550
1551Waste isn't a problem: provided the first input digit isn't 0, the difference
1552between the worst-case input with N digits and the smallest input with N
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001553digits is about a factor of B, but B is small compared to PyLong_BASE so at most
Tim Peters9faa3ed2006-05-30 15:53:34 +00001554one allocated Python digit can remain unused on that count. If
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001555N*log(B)/log(PyLong_BASE) is mathematically an exact integer, then truncating that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001556and adding 1 returns a result 1 larger than necessary. However, that can't
1557happen: whenever B is a power of 2, long_from_binary_base() is called
1558instead, and it's impossible for B**i to be an integer power of 2**15 when
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001559B 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 +00001560an exact integer when B is not a power of 2, since B**i has a prime factor
1561other than 2 in that case, but (2**15)**j's only prime factor is 2).
1562
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001563The computed result can be too small if the true value of N*log(B)/log(PyLong_BASE)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001564is a little bit larger than an exact integer, but due to roundoff errors (in
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001565computing log(B), log(PyLong_BASE), their quotient, and/or multiplying that by N)
Tim Peters9faa3ed2006-05-30 15:53:34 +00001566yields a numeric result a little less than that integer. Unfortunately, "how
1567close can a transcendental function get to an integer over some range?"
1568questions are generally theoretically intractable. Computer analysis via
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001569continued fractions is practical: expand log(B)/log(PyLong_BASE) via continued
Tim Peters9faa3ed2006-05-30 15:53:34 +00001570fractions, giving a sequence i/j of "the best" rational approximations. Then
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001571j*log(B)/log(PyLong_BASE) is approximately equal to (the integer) i. This shows that
Tim Peters9faa3ed2006-05-30 15:53:34 +00001572we can get very close to being in trouble, but very rarely. For example,
157376573 is a denominator in one of the continued-fraction approximations to
1574log(10)/log(2**15), and indeed:
1575
1576 >>> log(10)/log(2**15)*76573
1577 16958.000000654003
1578
1579is very close to an integer. If we were working with IEEE single-precision,
1580rounding errors could kill us. Finding worst cases in IEEE double-precision
1581requires better-than-double-precision log() functions, and Tim didn't bother.
1582Instead the code checks to see whether the allocated space is enough as each
1583new Python digit is added, and copies the whole thing to a larger long if not.
1584This should happen extremely rarely, and in fact I don't have a test case
1585that triggers it(!). Instead the code was tested by artificially allocating
1586just 1 digit at the start, so that the copying code was exercised for every
1587digit beyond the first.
Tim Peters696cf432006-05-24 21:10:40 +00001588***/
1589 register twodigits c; /* current input character */
1590 Py_ssize_t size_z;
1591 int i;
1592 int convwidth;
1593 twodigits convmultmax, convmult;
1594 digit *pz, *pzstop;
1595 char* scan;
1596
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001597 static double log_base_PyLong_BASE[37] = {0.0e0,};
Tim Peters696cf432006-05-24 21:10:40 +00001598 static int convwidth_base[37] = {0,};
1599 static twodigits convmultmax_base[37] = {0,};
1600
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001601 if (log_base_PyLong_BASE[base] == 0.0) {
Tim Peters696cf432006-05-24 21:10:40 +00001602 twodigits convmax = base;
1603 int i = 1;
1604
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001605 log_base_PyLong_BASE[base] = log((double)base) /
1606 log((double)PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001607 for (;;) {
1608 twodigits next = convmax * base;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001609 if (next > PyLong_BASE)
Tim Peters696cf432006-05-24 21:10:40 +00001610 break;
1611 convmax = next;
1612 ++i;
1613 }
1614 convmultmax_base[base] = convmax;
1615 assert(i > 0);
1616 convwidth_base[base] = i;
1617 }
1618
1619 /* Find length of the string of numeric characters. */
1620 scan = str;
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001621 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Tim Peters696cf432006-05-24 21:10:40 +00001622 ++scan;
1623
1624 /* Create a long object that can contain the largest possible
1625 * integer with this base and length. Note that there's no
1626 * need to initialize z->ob_digit -- no slot is read up before
1627 * being stored into.
1628 */
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001629 size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
Tim Peters9faa3ed2006-05-30 15:53:34 +00001630 /* Uncomment next line to test exceedingly rare copy code */
1631 /* size_z = 1; */
Tim Peters696cf432006-05-24 21:10:40 +00001632 assert(size_z > 0);
1633 z = _PyLong_New(size_z);
1634 if (z == NULL)
1635 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00001636 Py_SIZE(z) = 0;
Tim Peters696cf432006-05-24 21:10:40 +00001637
1638 /* `convwidth` consecutive input digits are treated as a single
1639 * digit in base `convmultmax`.
1640 */
1641 convwidth = convwidth_base[base];
1642 convmultmax = convmultmax_base[base];
1643
1644 /* Work ;-) */
1645 while (str < scan) {
1646 /* grab up to convwidth digits from the input string */
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001647 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Tim Peters696cf432006-05-24 21:10:40 +00001648 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1649 c = (twodigits)(c * base +
Neal Norwitzd183bdd2008-03-28 04:58:51 +00001650 _PyLong_DigitValue[Py_CHARMASK(*str)]);
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001651 assert(c < PyLong_BASE);
Tim Peters696cf432006-05-24 21:10:40 +00001652 }
1653
1654 convmult = convmultmax;
1655 /* Calculate the shift only if we couldn't get
1656 * convwidth digits.
1657 */
1658 if (i != convwidth) {
1659 convmult = base;
1660 for ( ; i > 1; --i)
1661 convmult *= base;
1662 }
1663
1664 /* Multiply z by convmult, and add c. */
1665 pz = z->ob_digit;
Christian Heimese93237d2007-12-19 02:37:44 +00001666 pzstop = pz + Py_SIZE(z);
Tim Peters696cf432006-05-24 21:10:40 +00001667 for (; pz < pzstop; ++pz) {
1668 c += (twodigits)*pz * convmult;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001669 *pz = (digit)(c & PyLong_MASK);
1670 c >>= PyLong_SHIFT;
Tim Peters696cf432006-05-24 21:10:40 +00001671 }
1672 /* carry off the current end? */
1673 if (c) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001674 assert(c < PyLong_BASE);
Christian Heimese93237d2007-12-19 02:37:44 +00001675 if (Py_SIZE(z) < size_z) {
Tim Peters9faa3ed2006-05-30 15:53:34 +00001676 *pz = (digit)c;
Christian Heimese93237d2007-12-19 02:37:44 +00001677 ++Py_SIZE(z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001678 }
1679 else {
1680 PyLongObject *tmp;
1681 /* Extremely rare. Get more space. */
Christian Heimese93237d2007-12-19 02:37:44 +00001682 assert(Py_SIZE(z) == size_z);
Tim Peters9faa3ed2006-05-30 15:53:34 +00001683 tmp = _PyLong_New(size_z + 1);
1684 if (tmp == NULL) {
1685 Py_DECREF(z);
1686 return NULL;
1687 }
1688 memcpy(tmp->ob_digit,
1689 z->ob_digit,
1690 sizeof(digit) * size_z);
1691 Py_DECREF(z);
1692 z = tmp;
1693 z->ob_digit[size_z] = (digit)c;
1694 ++size_z;
1695 }
Tim Peters696cf432006-05-24 21:10:40 +00001696 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001697 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001698 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001699 if (z == NULL)
1700 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001701 if (str == start)
1702 goto onError;
Tim Peters696cf432006-05-24 21:10:40 +00001703 if (sign < 0)
Christian Heimese93237d2007-12-19 02:37:44 +00001704 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001705 if (*str == 'L' || *str == 'l')
1706 str++;
1707 while (*str && isspace(Py_CHARMASK(*str)))
1708 str++;
1709 if (*str != '\0')
1710 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001711 if (pend)
1712 *pend = str;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001713 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001714
1715 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00001716 Py_XDECREF(z);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001717 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001718 strobj = PyString_FromStringAndSize(orig_str, slen);
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001719 if (strobj == NULL)
1720 return NULL;
1721 strrepr = PyObject_Repr(strobj);
1722 Py_DECREF(strobj);
1723 if (strrepr == NULL)
1724 return NULL;
1725 PyErr_Format(PyExc_ValueError,
1726 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001727 base, PyString_AS_STRING(strrepr));
Thomas Wouters9cb28bea2006-04-11 23:50:33 +00001728 Py_DECREF(strrepr);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001729 return NULL;
1730}
1731
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001732#ifdef Py_USING_UNICODE
Guido van Rossum9e896b32000-04-05 20:11:21 +00001733PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001734PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001735{
Walter Dörwald07e14762002-11-06 16:15:14 +00001736 PyObject *result;
Anthony Baxter377be112006-04-11 06:54:30 +00001737 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001738
Walter Dörwald07e14762002-11-06 16:15:14 +00001739 if (buffer == NULL)
1740 return NULL;
1741
1742 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
1743 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001744 return NULL;
1745 }
Walter Dörwald07e14762002-11-06 16:15:14 +00001746 result = PyLong_FromString(buffer, NULL, base);
1747 PyMem_FREE(buffer);
1748 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749}
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001750#endif
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751
Tim Peters9f688bf2000-07-07 15:53:28 +00001752/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001753static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00001754 (PyLongObject *, PyLongObject *, PyLongObject **);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00001755static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001756
1757/* Long division with remainder, top-level routine */
1758
Guido van Rossume32e0141992-01-19 16:31:05 +00001759static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001760long_divrem(PyLongObject *a, PyLongObject *b,
1761 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001762{
Christian Heimese93237d2007-12-19 02:37:44 +00001763 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001764 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001765
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001766 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001767 PyErr_SetString(PyExc_ZeroDivisionError,
Fred Drake661ea262000-10-24 19:57:45 +00001768 "long division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00001769 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770 }
1771 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00001772 (size_a == size_b &&
1773 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001774 /* |a| < |b|. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001775 *pdiv = _PyLong_New(0);
Georg Brandlc02e1312007-04-11 17:16:24 +00001776 if (*pdiv == NULL)
1777 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001778 Py_INCREF(a);
1779 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00001780 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001781 }
1782 if (size_b == 1) {
1783 digit rem = 0;
1784 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001785 if (z == NULL)
1786 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001787 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Georg Brandlc02e1312007-04-11 17:16:24 +00001788 if (*prem == NULL) {
1789 Py_DECREF(z);
1790 return -1;
1791 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001792 }
Guido van Rossume32e0141992-01-19 16:31:05 +00001793 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001794 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00001795 if (z == NULL)
1796 return -1;
1797 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001798 /* Set the signs.
1799 The quotient z has the sign of a*b;
1800 the remainder r has the sign of a,
1801 so a = b*z + r. */
Guido van Rossume32e0141992-01-19 16:31:05 +00001802 if ((a->ob_size < 0) != (b->ob_size < 0))
1803 z->ob_size = -(z->ob_size);
1804 if (a->ob_size < 0 && (*prem)->ob_size != 0)
1805 (*prem)->ob_size = -((*prem)->ob_size);
1806 *pdiv = z;
1807 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001808}
1809
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001810/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001811
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001812static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001813x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001814{
Christian Heimese93237d2007-12-19 02:37:44 +00001815 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001816 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001817 PyLongObject *v = mul1(v1, d);
1818 PyLongObject *w = mul1(w1, d);
1819 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001820 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001821
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001822 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001823 Py_XDECREF(v);
1824 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001825 return NULL;
1826 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001827
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001828 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimese93237d2007-12-19 02:37:44 +00001829 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
1830 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001831
Christian Heimese93237d2007-12-19 02:37:44 +00001832 size_v = ABS(Py_SIZE(v));
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001833 k = size_v - size_w;
1834 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00001835
Neal Norwitzc6a989a2006-05-10 06:57:58 +00001836 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001837 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
1838 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001839 stwodigits carry = 0;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00001840 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001841
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001842 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001843 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001844 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001845 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00001846 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001847 if (vj == w->ob_digit[size_w-1])
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001848 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001849 else
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001850 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001851 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00001852
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001853 while (w->ob_digit[size_w-2]*q >
1854 ((
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001855 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001856 + v->ob_digit[j-1]
1857 - q*w->ob_digit[size_w-1]
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001858 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001859 + v->ob_digit[j-2])
1860 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001861
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001862 for (i = 0; i < size_w && i+k < size_v; ++i) {
1863 twodigits z = w->ob_digit[i] * q;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001864 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001865 carry += v->ob_digit[i+k] - z
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001866 + ((twodigits)zz << PyLong_SHIFT);
1867 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
1868 carry = Py_ARITHMETIC_RIGHT_SHIFT(PyLong_BASE_TWODIGITS_TYPE,
1869 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00001870 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001871 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001872
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001873 if (i+k < size_v) {
1874 carry += v->ob_digit[i+k];
1875 v->ob_digit[i+k] = 0;
1876 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001877
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001878 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00001879 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001880 else {
1881 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00001882 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001883 carry = 0;
1884 for (i = 0; i < size_w && i+k < size_v; ++i) {
1885 carry += v->ob_digit[i+k] + w->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001886 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00001887 carry = Py_ARITHMETIC_RIGHT_SHIFT(
Christian Heimes7f39c9f2008-01-25 12:18:43 +00001888 PyLong_BASE_TWODIGITS_TYPE,
1889 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001890 }
1891 }
1892 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00001893
Guido van Rossumc206c761995-01-10 15:23:19 +00001894 if (a == NULL)
1895 *prem = NULL;
1896 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00001897 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001898 *prem = divrem1(v, d, &d);
1899 /* d receives the (unused) remainder */
1900 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001901 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00001902 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00001903 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001904 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001905 Py_DECREF(v);
1906 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001907 return a;
1908}
1909
1910/* Methods */
1911
1912static void
Tim Peters9f688bf2000-07-07 15:53:28 +00001913long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001914{
Christian Heimese93237d2007-12-19 02:37:44 +00001915 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001916}
1917
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001918static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001919long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001920{
Eric Smith5e527eb2008-02-10 01:36:53 +00001921 return _PyLong_Format(v, 10, 1, 0);
Fred Drake121ee271999-12-23 15:41:28 +00001922}
1923
1924static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001925long_str(PyObject *v)
Fred Drake121ee271999-12-23 15:41:28 +00001926{
Eric Smith5e527eb2008-02-10 01:36:53 +00001927 return _PyLong_Format(v, 10, 0, 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001928}
1929
1930static int
Tim Peters9f688bf2000-07-07 15:53:28 +00001931long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001932{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001933 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001934
Christian Heimese93237d2007-12-19 02:37:44 +00001935 if (Py_SIZE(a) != Py_SIZE(b)) {
1936 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00001937 sign = 0;
1938 else
Christian Heimese93237d2007-12-19 02:37:44 +00001939 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00001940 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001941 else {
Christian Heimese93237d2007-12-19 02:37:44 +00001942 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001943 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
1944 ;
1945 if (i < 0)
1946 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001947 else {
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00001948 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimese93237d2007-12-19 02:37:44 +00001949 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00001950 sign = -sign;
1951 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001952 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001953 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001954}
1955
Guido van Rossum9bfef441993-03-29 10:43:31 +00001956static long
Tim Peters9f688bf2000-07-07 15:53:28 +00001957long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001958{
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00001959 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001960 Py_ssize_t i;
1961 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001962
1963 /* This is designed so that Python ints and longs with the
1964 same value hash to the same value, otherwise comparisons
1965 of mapping keys will turn out weird */
1966 i = v->ob_size;
1967 sign = 1;
1968 x = 0;
1969 if (i < 0) {
1970 sign = -1;
1971 i = -(i);
1972 }
Mark Dickinsona0eae032009-01-26 21:40:08 +00001973 /* The following loop produces a C unsigned long x such that x is
1974 congruent to the absolute value of v modulo ULONG_MAX. The
1975 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00001976 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00001977 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001978 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00001979 x += v->ob_digit[i];
Mark Dickinson6ffa4a22009-01-26 21:36:30 +00001980 /* If the addition above overflowed we compensate by
1981 incrementing. This preserves the value modulo
1982 ULONG_MAX. */
1983 if (x < v->ob_digit[i])
Facundo Batistad544df72007-09-19 15:10:06 +00001984 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001985 }
1986 x = x * sign;
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00001987 if (x == (unsigned long)-1)
1988 x = (unsigned long)-2;
1989 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001990}
1991
1992
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001993/* Add the absolute values of two long integers. */
1994
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001995static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001996x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001997{
Christian Heimese93237d2007-12-19 02:37:44 +00001998 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001999 PyLongObject *z;
Mark Dickinsonff84aa82009-01-24 15:27:44 +00002000 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002001 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002002
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002003 /* Ensure a is the larger of the two: */
2004 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002005 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002006 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002007 size_a = size_b;
2008 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002009 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002010 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002011 if (z == NULL)
2012 return NULL;
2013 for (i = 0; i < size_b; ++i) {
2014 carry += a->ob_digit[i] + b->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002015 z->ob_digit[i] = carry & PyLong_MASK;
2016 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002017 }
2018 for (; i < size_a; ++i) {
2019 carry += a->ob_digit[i];
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002020 z->ob_digit[i] = carry & PyLong_MASK;
2021 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002022 }
2023 z->ob_digit[i] = carry;
2024 return long_normalize(z);
2025}
2026
2027/* Subtract the absolute values of two integers. */
2028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002030x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031{
Christian Heimese93237d2007-12-19 02:37:44 +00002032 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002033 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002034 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002035 int sign = 1;
2036 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002037
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002038 /* Ensure a is the larger of the two: */
2039 if (size_a < size_b) {
2040 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002041 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002042 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043 size_a = size_b;
2044 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045 }
2046 else if (size_a == size_b) {
2047 /* Find highest digit where a and b differ: */
2048 i = size_a;
2049 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2050 ;
2051 if (i < 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052 return _PyLong_New(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 if (a->ob_digit[i] < b->ob_digit[i]) {
2054 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002055 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002056 }
2057 size_a = size_b = i+1;
2058 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002059 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002060 if (z == NULL)
2061 return NULL;
2062 for (i = 0; i < size_b; ++i) {
2063 /* The following assumes unsigned arithmetic
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002064 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002065 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002066 z->ob_digit[i] = borrow & PyLong_MASK;
2067 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068 borrow &= 1; /* Keep only one sign bit */
2069 }
2070 for (; i < size_a; ++i) {
2071 borrow = a->ob_digit[i] - borrow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002072 z->ob_digit[i] = borrow & PyLong_MASK;
2073 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002074 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002075 }
2076 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002077 if (sign < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002078 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 return long_normalize(z);
2080}
2081
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002083long_add(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002084{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002085 PyLongObject *a, *b, *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002086
Neil Schemenauerba872e22001-01-04 01:46:03 +00002087 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2088
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002089 if (a->ob_size < 0) {
2090 if (b->ob_size < 0) {
2091 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002092 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002093 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002094 }
2095 else
2096 z = x_sub(b, a);
2097 }
2098 else {
2099 if (b->ob_size < 0)
2100 z = x_sub(a, b);
2101 else
2102 z = x_add(a, b);
2103 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002104 Py_DECREF(a);
2105 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107}
2108
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002109static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002110long_sub(PyLongObject *v, PyLongObject *w)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002111{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002112 PyLongObject *a, *b, *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002113
Neil Schemenauerba872e22001-01-04 01:46:03 +00002114 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2115
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116 if (a->ob_size < 0) {
2117 if (b->ob_size < 0)
2118 z = x_sub(a, b);
2119 else
2120 z = x_add(a, b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002121 if (z != NULL && z->ob_size != 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002122 z->ob_size = -(z->ob_size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002123 }
2124 else {
2125 if (b->ob_size < 0)
2126 z = x_add(a, b);
2127 else
2128 z = x_sub(a, b);
2129 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002130 Py_DECREF(a);
2131 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002132 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133}
2134
Tim Peters5af4e6c2002-08-12 02:31:19 +00002135/* Grade school multiplication, ignoring the signs.
2136 * Returns the absolute value of the product, or NULL if error.
2137 */
2138static PyLongObject *
2139x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002140{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002141 PyLongObject *z;
Christian Heimese93237d2007-12-19 02:37:44 +00002142 Py_ssize_t size_a = ABS(Py_SIZE(a));
2143 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002144 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002145
Tim Peters5af4e6c2002-08-12 02:31:19 +00002146 z = _PyLong_New(size_a + size_b);
2147 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002148 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002149
Christian Heimese93237d2007-12-19 02:37:44 +00002150 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002151 if (a == b) {
2152 /* Efficient squaring per HAC, Algorithm 14.16:
2153 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2154 * Gives slightly less than a 2x speedup when a == b,
2155 * via exploiting that each entry in the multiplication
2156 * pyramid appears twice (except for the size_a squares).
2157 */
2158 for (i = 0; i < size_a; ++i) {
2159 twodigits carry;
2160 twodigits f = a->ob_digit[i];
2161 digit *pz = z->ob_digit + (i << 1);
2162 digit *pa = a->ob_digit + i + 1;
2163 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002164
Tim Peters0973b992004-08-29 22:16:50 +00002165 SIGCHECK({
2166 Py_DECREF(z);
2167 return NULL;
2168 })
2169
2170 carry = *pz + f * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002171 *pz++ = (digit)(carry & PyLong_MASK);
2172 carry >>= PyLong_SHIFT;
2173 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002174
2175 /* Now f is added in twice in each column of the
2176 * pyramid it appears. Same as adding f<<1 once.
2177 */
2178 f <<= 1;
2179 while (pa < paend) {
2180 carry += *pz + *pa++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002181 *pz++ = (digit)(carry & PyLong_MASK);
2182 carry >>= PyLong_SHIFT;
2183 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002184 }
2185 if (carry) {
2186 carry += *pz;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002187 *pz++ = (digit)(carry & PyLong_MASK);
2188 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002189 }
2190 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002191 *pz += (digit)(carry & PyLong_MASK);
2192 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002193 }
Tim Peters0973b992004-08-29 22:16:50 +00002194 }
2195 else { /* a is not the same as b -- gradeschool long mult */
2196 for (i = 0; i < size_a; ++i) {
2197 twodigits carry = 0;
2198 twodigits f = a->ob_digit[i];
2199 digit *pz = z->ob_digit + i;
2200 digit *pb = b->ob_digit;
2201 digit *pbend = b->ob_digit + size_b;
2202
2203 SIGCHECK({
2204 Py_DECREF(z);
2205 return NULL;
2206 })
2207
2208 while (pb < pbend) {
2209 carry += *pz + *pb++ * f;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002210 *pz++ = (digit)(carry & PyLong_MASK);
2211 carry >>= PyLong_SHIFT;
2212 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002213 }
2214 if (carry)
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002215 *pz += (digit)(carry & PyLong_MASK);
2216 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002217 }
2218 }
Tim Peters44121a62002-08-12 06:17:58 +00002219 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002220}
2221
2222/* A helper for Karatsuba multiplication (k_mul).
2223 Takes a long "n" and an integer "size" representing the place to
2224 split, and sets low and high such that abs(n) == (high << size) + low,
2225 viewing the shift as being by digits. The sign bit is ignored, and
2226 the return values are >= 0.
2227 Returns 0 on success, -1 on failure.
2228*/
2229static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002230kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002231{
2232 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002233 Py_ssize_t size_lo, size_hi;
Christian Heimese93237d2007-12-19 02:37:44 +00002234 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002235
2236 size_lo = MIN(size_n, size);
2237 size_hi = size_n - size_lo;
2238
2239 if ((hi = _PyLong_New(size_hi)) == NULL)
2240 return -1;
2241 if ((lo = _PyLong_New(size_lo)) == NULL) {
2242 Py_DECREF(hi);
2243 return -1;
2244 }
2245
2246 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2247 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2248
2249 *high = long_normalize(hi);
2250 *low = long_normalize(lo);
2251 return 0;
2252}
2253
Tim Peters60004642002-08-12 22:01:34 +00002254static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2255
Tim Peters5af4e6c2002-08-12 02:31:19 +00002256/* Karatsuba multiplication. Ignores the input signs, and returns the
2257 * absolute value of the product (or NULL if error).
2258 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2259 */
2260static PyLongObject *
2261k_mul(PyLongObject *a, PyLongObject *b)
2262{
Christian Heimese93237d2007-12-19 02:37:44 +00002263 Py_ssize_t asize = ABS(Py_SIZE(a));
2264 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002265 PyLongObject *ah = NULL;
2266 PyLongObject *al = NULL;
2267 PyLongObject *bh = NULL;
2268 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002269 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002270 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002271 Py_ssize_t shift; /* the number of digits we split off */
2272 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002273
Tim Peters5af4e6c2002-08-12 02:31:19 +00002274 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2275 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2276 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002277 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002278 * By picking X to be a power of 2, "*X" is just shifting, and it's
2279 * been reduced to 3 multiplies on numbers half the size.
2280 */
2281
Tim Petersfc07e562002-08-12 02:54:10 +00002282 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002283 * is largest.
2284 */
Tim Peters738eda72002-08-12 15:08:20 +00002285 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002286 t1 = a;
2287 a = b;
2288 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002289
2290 i = asize;
2291 asize = bsize;
2292 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002293 }
2294
2295 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002296 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2297 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002298 if (asize == 0)
Tim Peters44121a62002-08-12 06:17:58 +00002299 return _PyLong_New(0);
2300 else
2301 return x_mul(a, b);
2302 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002303
Tim Peters60004642002-08-12 22:01:34 +00002304 /* If a is small compared to b, splitting on b gives a degenerate
2305 * case with ah==0, and Karatsuba may be (even much) less efficient
2306 * than "grade school" then. However, we can still win, by viewing
2307 * b as a string of "big digits", each of width a->ob_size. That
2308 * leads to a sequence of balanced calls to k_mul.
2309 */
2310 if (2 * asize <= bsize)
2311 return k_lopsided_mul(a, b);
2312
Tim Petersd6974a52002-08-13 20:37:51 +00002313 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002314 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002315 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002316 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002317
Tim Peters0973b992004-08-29 22:16:50 +00002318 if (a == b) {
2319 bh = ah;
2320 bl = al;
2321 Py_INCREF(bh);
2322 Py_INCREF(bl);
2323 }
2324 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002325
Tim Petersd64c1de2002-08-12 17:36:03 +00002326 /* The plan:
2327 * 1. Allocate result space (asize + bsize digits: that's always
2328 * enough).
2329 * 2. Compute ah*bh, and copy into result at 2*shift.
2330 * 3. Compute al*bl, and copy into result at 0. Note that this
2331 * can't overlap with #2.
2332 * 4. Subtract al*bl from the result, starting at shift. This may
2333 * underflow (borrow out of the high digit), but we don't care:
2334 * we're effectively doing unsigned arithmetic mod
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002335 * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
Tim Petersd64c1de2002-08-12 17:36:03 +00002336 * borrows and carries out of the high digit can be ignored.
2337 * 5. Subtract ah*bh from the result, starting at shift.
2338 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2339 * at shift.
2340 */
2341
2342 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002343 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002344 if (ret == NULL) goto fail;
2345#ifdef Py_DEBUG
2346 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002347 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002348#endif
Tim Peters44121a62002-08-12 06:17:58 +00002349
Tim Petersd64c1de2002-08-12 17:36:03 +00002350 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002351 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002352 assert(Py_SIZE(t1) >= 0);
2353 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002354 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimese93237d2007-12-19 02:37:44 +00002355 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002356
2357 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimese93237d2007-12-19 02:37:44 +00002358 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002359 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002360 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002361 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002362
Tim Petersd64c1de2002-08-12 17:36:03 +00002363 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002364 if ((t2 = k_mul(al, bl)) == NULL) {
2365 Py_DECREF(t1);
2366 goto fail;
2367 }
Christian Heimese93237d2007-12-19 02:37:44 +00002368 assert(Py_SIZE(t2) >= 0);
2369 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2370 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002371
2372 /* Zero out remaining digits. */
Christian Heimese93237d2007-12-19 02:37:44 +00002373 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002374 if (i)
Christian Heimese93237d2007-12-19 02:37:44 +00002375 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002376
Tim Petersd64c1de2002-08-12 17:36:03 +00002377 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2378 * because it's fresher in cache.
2379 */
Christian Heimese93237d2007-12-19 02:37:44 +00002380 i = Py_SIZE(ret) - shift; /* # digits after shift */
2381 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002382 Py_DECREF(t2);
2383
Christian Heimese93237d2007-12-19 02:37:44 +00002384 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002385 Py_DECREF(t1);
2386
Tim Petersd64c1de2002-08-12 17:36:03 +00002387 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002388 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2389 Py_DECREF(ah);
2390 Py_DECREF(al);
2391 ah = al = NULL;
2392
Tim Peters0973b992004-08-29 22:16:50 +00002393 if (a == b) {
2394 t2 = t1;
2395 Py_INCREF(t2);
2396 }
2397 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002398 Py_DECREF(t1);
2399 goto fail;
2400 }
2401 Py_DECREF(bh);
2402 Py_DECREF(bl);
2403 bh = bl = NULL;
2404
Tim Peters738eda72002-08-12 15:08:20 +00002405 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002406 Py_DECREF(t1);
2407 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002408 if (t3 == NULL) goto fail;
Christian Heimese93237d2007-12-19 02:37:44 +00002409 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002410
Tim Petersd6974a52002-08-13 20:37:51 +00002411 /* Add t3. It's not obvious why we can't run out of room here.
2412 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002413 */
Christian Heimese93237d2007-12-19 02:37:44 +00002414 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002415 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002416
Tim Peters5af4e6c2002-08-12 02:31:19 +00002417 return long_normalize(ret);
2418
2419 fail:
2420 Py_XDECREF(ret);
2421 Py_XDECREF(ah);
2422 Py_XDECREF(al);
2423 Py_XDECREF(bh);
2424 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002425 return NULL;
2426}
2427
Tim Petersd6974a52002-08-13 20:37:51 +00002428/* (*) Why adding t3 can't "run out of room" above.
2429
Tim Petersab86c2b2002-08-15 20:06:00 +00002430Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2431to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002432
Tim Petersab86c2b2002-08-15 20:06:00 +000024331. For any integer i, i = c(i/2) + f(i/2). In particular,
2434 bsize = c(bsize/2) + f(bsize/2).
24352. shift = f(bsize/2)
24363. asize <= bsize
24374. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2438 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002439
Tim Petersab86c2b2002-08-15 20:06:00 +00002440We allocated asize + bsize result digits, and add t3 into them at an offset
2441of shift. This leaves asize+bsize-shift allocated digit positions for t3
2442to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2443asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002444
Tim Petersab86c2b2002-08-15 20:06:00 +00002445bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2446at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002447
Tim Petersab86c2b2002-08-15 20:06:00 +00002448If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2449digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2450most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002451
Tim Petersab86c2b2002-08-15 20:06:00 +00002452The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002453
Tim Petersab86c2b2002-08-15 20:06:00 +00002454 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002455
Tim Petersab86c2b2002-08-15 20:06:00 +00002456and we have asize + c(bsize/2) available digit positions. We need to show
2457this is always enough. An instance of c(bsize/2) cancels out in both, so
2458the question reduces to whether asize digits is enough to hold
2459(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2460then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2461asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002462digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002463asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002464c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2465is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2466bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002467
Tim Peters48d52c02002-08-14 17:07:32 +00002468Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2469clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2470ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002471*/
2472
Tim Peters60004642002-08-12 22:01:34 +00002473/* b has at least twice the digits of a, and a is big enough that Karatsuba
2474 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2475 * of slices, each with a->ob_size digits, and multiply the slices by a,
2476 * one at a time. This gives k_mul balanced inputs to work with, and is
2477 * also cache-friendly (we compute one double-width slice of the result
2478 * at a time, then move on, never bactracking except for the helpful
2479 * single-width slice overlap between successive partial sums).
2480 */
2481static PyLongObject *
2482k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2483{
Christian Heimese93237d2007-12-19 02:37:44 +00002484 const Py_ssize_t asize = ABS(Py_SIZE(a));
2485 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002486 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002487 PyLongObject *ret;
2488 PyLongObject *bslice = NULL;
2489
2490 assert(asize > KARATSUBA_CUTOFF);
2491 assert(2 * asize <= bsize);
2492
2493 /* Allocate result space, and zero it out. */
2494 ret = _PyLong_New(asize + bsize);
2495 if (ret == NULL)
2496 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002497 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002498
2499 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002500 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002501 if (bslice == NULL)
2502 goto fail;
2503
2504 nbdone = 0;
2505 while (bsize > 0) {
2506 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002507 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002508
2509 /* Multiply the next slice of b by a. */
2510 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2511 nbtouse * sizeof(digit));
Christian Heimese93237d2007-12-19 02:37:44 +00002512 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002513 product = k_mul(a, bslice);
2514 if (product == NULL)
2515 goto fail;
2516
2517 /* Add into result. */
Christian Heimese93237d2007-12-19 02:37:44 +00002518 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2519 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002520 Py_DECREF(product);
2521
2522 bsize -= nbtouse;
2523 nbdone += nbtouse;
2524 }
2525
2526 Py_DECREF(bslice);
2527 return long_normalize(ret);
2528
2529 fail:
2530 Py_DECREF(ret);
2531 Py_XDECREF(bslice);
2532 return NULL;
2533}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002534
2535static PyObject *
2536long_mul(PyLongObject *v, PyLongObject *w)
2537{
2538 PyLongObject *a, *b, *z;
2539
2540 if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002541 Py_INCREF(Py_NotImplemented);
2542 return Py_NotImplemented;
2543 }
2544
Tim Petersd64c1de2002-08-12 17:36:03 +00002545 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002546 /* Negate if exactly one of the inputs is negative. */
2547 if (((a->ob_size ^ b->ob_size) < 0) && z)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002548 z->ob_size = -(z->ob_size);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002549 Py_DECREF(a);
2550 Py_DECREF(b);
Tim Peters9973d742002-08-15 19:41:06 +00002551 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002552}
2553
Guido van Rossume32e0141992-01-19 16:31:05 +00002554/* The / and % operators are now defined in terms of divmod().
2555 The expression a mod b has the value a - b*floor(a/b).
2556 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002557 |a| by |b|, with the sign of a. This is also expressed
2558 as a - b*trunc(a/b), if trunc truncates towards zero.
2559 Some examples:
2560 a b a rem b a mod b
2561 13 10 3 3
2562 -13 10 -3 7
2563 13 -10 3 -7
2564 -13 -10 -3 -3
2565 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002566 have different signs. We then subtract one from the 'div'
2567 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002568
Tim Peters47e52ee2004-08-30 02:44:38 +00002569/* Compute
2570 * *pdiv, *pmod = divmod(v, w)
2571 * NULL can be passed for pdiv or pmod, in which case that part of
2572 * the result is simply thrown away. The caller owns a reference to
2573 * each of these it requests (does not pass NULL for).
2574 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002575static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002576l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002577 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002578{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002579 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002580
Guido van Rossume32e0141992-01-19 16:31:05 +00002581 if (long_divrem(v, w, &div, &mod) < 0)
2582 return -1;
Christian Heimese93237d2007-12-19 02:37:44 +00002583 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2584 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002585 PyLongObject *temp;
2586 PyLongObject *one;
2587 temp = (PyLongObject *) long_add(mod, w);
2588 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002589 mod = temp;
2590 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002591 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002592 return -1;
2593 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002594 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002595 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002596 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2597 Py_DECREF(mod);
2598 Py_DECREF(div);
2599 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002600 return -1;
2601 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002602 Py_DECREF(one);
2603 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002604 div = temp;
2605 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002606 if (pdiv != NULL)
2607 *pdiv = div;
2608 else
2609 Py_DECREF(div);
2610
2611 if (pmod != NULL)
2612 *pmod = mod;
2613 else
2614 Py_DECREF(mod);
2615
Guido van Rossume32e0141992-01-19 16:31:05 +00002616 return 0;
2617}
2618
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002619static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002620long_div(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002621{
Tim Peters47e52ee2004-08-30 02:44:38 +00002622 PyLongObject *a, *b, *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002623
2624 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002625 if (l_divmod(a, b, &div, NULL) < 0)
2626 div = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002627 Py_DECREF(a);
2628 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002629 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002630}
2631
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002632static PyObject *
Guido van Rossum393661d2001-08-31 17:40:15 +00002633long_classic_div(PyObject *v, PyObject *w)
2634{
Tim Peters47e52ee2004-08-30 02:44:38 +00002635 PyLongObject *a, *b, *div;
Guido van Rossum393661d2001-08-31 17:40:15 +00002636
2637 CONVERT_BINOP(v, w, &a, &b);
Guido van Rossum393661d2001-08-31 17:40:15 +00002638 if (Py_DivisionWarningFlag &&
2639 PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
2640 div = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00002641 else if (l_divmod(a, b, &div, NULL) < 0)
Guido van Rossum393661d2001-08-31 17:40:15 +00002642 div = NULL;
Guido van Rossum393661d2001-08-31 17:40:15 +00002643 Py_DECREF(a);
2644 Py_DECREF(b);
2645 return (PyObject *)div;
2646}
2647
2648static PyObject *
Tim Peters20dab9f2001-09-04 05:31:47 +00002649long_true_divide(PyObject *v, PyObject *w)
2650{
Tim Peterse2a60002001-09-04 06:17:36 +00002651 PyLongObject *a, *b;
2652 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002653 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002654
2655 CONVERT_BINOP(v, w, &a, &b);
2656 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2657 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002658 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
2659 Py_DECREF(a);
2660 Py_DECREF(b);
2661 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002662 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002663 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2664 but should really be set correctly after sucessful calls to
2665 _PyLong_AsScaledDouble() */
2666 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002667
2668 if (bd == 0.0) {
2669 PyErr_SetString(PyExc_ZeroDivisionError,
2670 "long division or modulo by zero");
2671 return NULL;
2672 }
2673
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002674 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002675 ad /= bd; /* overflow/underflow impossible here */
2676 aexp -= bexp;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002677 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002678 goto overflow;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002679 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002680 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002681 errno = 0;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002682 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002683 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002684 goto overflow;
2685 return PyFloat_FromDouble(ad);
2686
2687overflow:
2688 PyErr_SetString(PyExc_OverflowError,
2689 "long/long too large for a float");
2690 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002691
Tim Peters20dab9f2001-09-04 05:31:47 +00002692}
2693
2694static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002695long_mod(PyObject *v, PyObject *w)
Guido van Rossume32e0141992-01-19 16:31:05 +00002696{
Tim Peters47e52ee2004-08-30 02:44:38 +00002697 PyLongObject *a, *b, *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002698
2699 CONVERT_BINOP(v, w, &a, &b);
2700
Tim Peters47e52ee2004-08-30 02:44:38 +00002701 if (l_divmod(a, b, NULL, &mod) < 0)
2702 mod = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002703 Py_DECREF(a);
2704 Py_DECREF(b);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002705 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00002706}
2707
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002708static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002709long_divmod(PyObject *v, PyObject *w)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002710{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002711 PyLongObject *a, *b, *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002712 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002713
2714 CONVERT_BINOP(v, w, &a, &b);
2715
2716 if (l_divmod(a, b, &div, &mod) < 0) {
2717 Py_DECREF(a);
2718 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002719 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002720 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002721 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002722 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002723 PyTuple_SetItem(z, 0, (PyObject *) div);
2724 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002725 }
2726 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002727 Py_DECREF(div);
2728 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002729 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002730 Py_DECREF(a);
2731 Py_DECREF(b);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002732 return z;
2733}
2734
Tim Peters47e52ee2004-08-30 02:44:38 +00002735/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002736static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002737long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002738{
Tim Peters47e52ee2004-08-30 02:44:38 +00002739 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
2740 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002741
Tim Peters47e52ee2004-08-30 02:44:38 +00002742 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002743 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00002744 PyLongObject *temp = NULL;
2745
2746 /* 5-ary values. If the exponent is large enough, table is
2747 * precomputed so that table[i] == a**i % c for i in range(32).
2748 */
2749 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
2750 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2751
2752 /* a, b, c = v, w, x */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002753 CONVERT_BINOP(v, w, &a, &b);
Tim Peters47e52ee2004-08-30 02:44:38 +00002754 if (PyLong_Check(x)) {
2755 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002756 Py_INCREF(x);
2757 }
Tim Petersde7990b2005-07-17 23:45:23 +00002758 else if (PyInt_Check(x)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002759 c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
Tim Petersde7990b2005-07-17 23:45:23 +00002760 if (c == NULL)
2761 goto Error;
2762 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002763 else if (x == Py_None)
2764 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002765 else {
2766 Py_DECREF(a);
2767 Py_DECREF(b);
2768 Py_INCREF(Py_NotImplemented);
2769 return Py_NotImplemented;
2770 }
Tim Peters4c483c42001-09-05 06:24:58 +00002771
Christian Heimese93237d2007-12-19 02:37:44 +00002772 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00002773 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00002774 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00002775 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00002776 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00002777 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002778 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00002779 /* else return a float. This works because we know
2780 that this calls float_pow() which converts its
2781 arguments to double. */
2782 Py_DECREF(a);
2783 Py_DECREF(b);
2784 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00002785 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002786 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002787
2788 if (c) {
2789 /* if modulus == 0:
2790 raise ValueError() */
Christian Heimese93237d2007-12-19 02:37:44 +00002791 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002792 PyErr_SetString(PyExc_ValueError,
2793 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00002794 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002795 }
2796
2797 /* if modulus < 0:
2798 negativeOutput = True
2799 modulus = -modulus */
Christian Heimese93237d2007-12-19 02:37:44 +00002800 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002801 negativeOutput = 1;
2802 temp = (PyLongObject *)_PyLong_Copy(c);
2803 if (temp == NULL)
2804 goto Error;
2805 Py_DECREF(c);
2806 c = temp;
2807 temp = NULL;
2808 c->ob_size = - c->ob_size;
2809 }
2810
2811 /* if modulus == 1:
2812 return 0 */
Christian Heimese93237d2007-12-19 02:37:44 +00002813 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002814 z = (PyLongObject *)PyLong_FromLong(0L);
2815 goto Done;
2816 }
2817
2818 /* if base < 0:
2819 base = base % modulus
2820 Having the base positive just makes things easier. */
Christian Heimese93237d2007-12-19 02:37:44 +00002821 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002822 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00002823 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00002824 Py_DECREF(a);
2825 a = temp;
2826 temp = NULL;
2827 }
2828 }
2829
2830 /* At this point a, b, and c are guaranteed non-negative UNLESS
2831 c is NULL, in which case a may be negative. */
2832
2833 z = (PyLongObject *)PyLong_FromLong(1L);
2834 if (z == NULL)
2835 goto Error;
2836
2837 /* Perform a modular reduction, X = X % c, but leave X alone if c
2838 * is NULL.
2839 */
2840#define REDUCE(X) \
2841 if (c != NULL) { \
2842 if (l_divmod(X, c, NULL, &temp) < 0) \
2843 goto Error; \
2844 Py_XDECREF(X); \
2845 X = temp; \
2846 temp = NULL; \
2847 }
2848
2849 /* Multiply two values, then reduce the result:
2850 result = X*Y % c. If c is NULL, skip the mod. */
2851#define MULT(X, Y, result) \
2852{ \
2853 temp = (PyLongObject *)long_mul(X, Y); \
2854 if (temp == NULL) \
2855 goto Error; \
2856 Py_XDECREF(result); \
2857 result = temp; \
2858 temp = NULL; \
2859 REDUCE(result) \
2860}
2861
Christian Heimese93237d2007-12-19 02:37:44 +00002862 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002863 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
2864 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimese93237d2007-12-19 02:37:44 +00002865 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002866 digit bi = b->ob_digit[i];
2867
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00002868 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002869 MULT(z, z, z)
2870 if (bi & j)
2871 MULT(z, a, z)
2872 }
2873 }
2874 }
2875 else {
2876 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
2877 Py_INCREF(z); /* still holds 1L */
2878 table[0] = z;
2879 for (i = 1; i < 32; ++i)
2880 MULT(table[i-1], a, table[i])
2881
Christian Heimese93237d2007-12-19 02:37:44 +00002882 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002883 const digit bi = b->ob_digit[i];
2884
Christian Heimes7f39c9f2008-01-25 12:18:43 +00002885 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002886 const int index = (bi >> j) & 0x1f;
2887 for (k = 0; k < 5; ++k)
2888 MULT(z, z, z)
2889 if (index)
2890 MULT(z, table[index], z)
2891 }
2892 }
2893 }
2894
Christian Heimese93237d2007-12-19 02:37:44 +00002895 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002896 temp = (PyLongObject *)long_sub(z, c);
2897 if (temp == NULL)
2898 goto Error;
2899 Py_DECREF(z);
2900 z = temp;
2901 temp = NULL;
2902 }
2903 goto Done;
2904
2905 Error:
2906 if (z != NULL) {
2907 Py_DECREF(z);
2908 z = NULL;
2909 }
2910 /* fall through */
2911 Done:
Christian Heimese93237d2007-12-19 02:37:44 +00002912 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00002913 for (i = 0; i < 32; ++i)
2914 Py_XDECREF(table[i]);
2915 }
Tim Petersde7990b2005-07-17 23:45:23 +00002916 Py_DECREF(a);
2917 Py_DECREF(b);
2918 Py_XDECREF(c);
2919 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002920 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002921}
2922
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002923static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002924long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002925{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002926 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002927 PyLongObject *x;
2928 PyLongObject *w;
2929 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002930 if (w == NULL)
2931 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002932 x = (PyLongObject *) long_add(v, w);
2933 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002934 if (x == NULL)
2935 return NULL;
Christian Heimese93237d2007-12-19 02:37:44 +00002936 Py_SIZE(x) = -(Py_SIZE(x));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002937 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002938}
2939
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002940static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002941long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002942{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002943 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002944 if (v->ob_size == 0 && PyLong_CheckExact(v)) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002945 /* -0 == 0 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002946 Py_INCREF(v);
2947 return (PyObject *) v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002948 }
Tim Peters69c2de32001-09-11 22:31:33 +00002949 z = (PyLongObject *)_PyLong_Copy(v);
2950 if (z != NULL)
2951 z->ob_size = -(v->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002952 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002953}
2954
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002955static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002956long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002957{
2958 if (v->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002959 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00002960 else
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00002961 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002962}
2963
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002964static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002965long_nonzero(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002966{
Christian Heimese93237d2007-12-19 02:37:44 +00002967 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002968}
2969
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002970static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00002971long_rshift(PyLongObject *v, PyLongObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002972{
Neil Schemenauerba872e22001-01-04 01:46:03 +00002973 PyLongObject *a, *b;
2974 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002975 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002976 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002977 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002978
Neil Schemenauerba872e22001-01-04 01:46:03 +00002979 CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
2980
Christian Heimese93237d2007-12-19 02:37:44 +00002981 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002982 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00002983 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002984 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002985 if (a1 == NULL)
2986 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002987 a2 = (PyLongObject *) long_rshift(a1, b);
2988 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002989 if (a2 == NULL)
2990 goto rshift_error;
2991 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002992 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002993 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00002994 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002995
Neil Schemenauerba872e22001-01-04 01:46:03 +00002996 shiftby = PyLong_AsLong((PyObject *)b);
2997 if (shiftby == -1L && PyErr_Occurred())
2998 goto rshift_error;
2999 if (shiftby < 0) {
3000 PyErr_SetString(PyExc_ValueError,
3001 "negative shift count");
3002 goto rshift_error;
3003 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003004 wordshift = shiftby / PyLong_SHIFT;
Christian Heimese93237d2007-12-19 02:37:44 +00003005 newsize = ABS(Py_SIZE(a)) - wordshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003006 if (newsize <= 0) {
3007 z = _PyLong_New(0);
3008 Py_DECREF(a);
3009 Py_DECREF(b);
3010 return (PyObject *)z;
3011 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003012 loshift = shiftby % PyLong_SHIFT;
3013 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003014 lomask = ((digit)1 << hishift) - 1;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003015 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003016 z = _PyLong_New(newsize);
3017 if (z == NULL)
3018 goto rshift_error;
Christian Heimese93237d2007-12-19 02:37:44 +00003019 if (Py_SIZE(a) < 0)
3020 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003021 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3022 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3023 if (i+1 < newsize)
3024 z->ob_digit[i] |=
3025 (a->ob_digit[j+1] << hishift) & himask;
3026 }
3027 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003028 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003029rshift_error:
3030 Py_DECREF(a);
3031 Py_DECREF(b);
3032 return (PyObject *) z;
3033
Guido van Rossumc6913e71991-11-19 20:26:46 +00003034}
3035
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003036static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003037long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003038{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003039 /* This version due to Tim Peters */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003040 PyLongObject *a, *b;
3041 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003042 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003043 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003044 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003045
Neil Schemenauerba872e22001-01-04 01:46:03 +00003046 CONVERT_BINOP(v, w, &a, &b);
3047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003048 shiftby = PyLong_AsLong((PyObject *)b);
3049 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003050 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003051 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003052 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003053 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003054 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003055 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003056 PyErr_SetString(PyExc_ValueError,
3057 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003058 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003059 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003060 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3061 wordshift = (int)shiftby / PyLong_SHIFT;
3062 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003063
3064 oldsize = ABS(a->ob_size);
3065 newsize = oldsize + wordshift;
3066 if (remshift)
3067 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003068 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003069 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003070 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003071 if (a->ob_size < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003072 z->ob_size = -(z->ob_size);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003073 for (i = 0; i < wordshift; i++)
3074 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003075 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003076 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003077 accum |= (twodigits)a->ob_digit[j] << remshift;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003078 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3079 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003080 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003081 if (remshift)
3082 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003083 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003084 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003085 z = long_normalize(z);
3086lshift_error:
3087 Py_DECREF(a);
3088 Py_DECREF(b);
3089 return (PyObject *) z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003090}
3091
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003092
3093/* Bitwise and/xor/or operations */
3094
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003095static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003096long_bitwise(PyLongObject *a,
3097 int op, /* '&', '|', '^' */
3098 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003099{
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003100 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003101 int negz;
Mark Dickinsonbcf6b182009-02-15 15:48:39 +00003102 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003103 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003104 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003105 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003106
Christian Heimese93237d2007-12-19 02:37:44 +00003107 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003108 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003109 if (a == NULL)
3110 return NULL;
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003111 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003112 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003113 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003114 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003115 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003116 }
Christian Heimese93237d2007-12-19 02:37:44 +00003117 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003118 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003119 if (b == NULL) {
3120 Py_DECREF(a);
3121 return NULL;
3122 }
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003123 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003124 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003125 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003126 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003127 maskb = 0;
3128 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003129
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003130 negz = 0;
3131 switch (op) {
3132 case '^':
3133 if (maska != maskb) {
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003134 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003135 negz = -1;
3136 }
3137 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003138 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003139 if (maska && maskb) {
3140 op = '|';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003141 maska ^= PyLong_MASK;
3142 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003143 negz = -1;
3144 }
3145 break;
3146 case '|':
3147 if (maska || maskb) {
3148 op = '&';
Christian Heimes7f39c9f2008-01-25 12:18:43 +00003149 maska ^= PyLong_MASK;
3150 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003151 negz = -1;
3152 }
3153 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003154 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003155
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003156 /* JRH: The original logic here was to allocate the result value (z)
3157 as the longer of the two operands. However, there are some cases
3158 where the result is guaranteed to be shorter than that: AND of two
3159 positives, OR of two negatives: use the shorter number. AND with
3160 mixed signs: use the positive number. OR with mixed signs: use the
3161 negative number. After the transformations above, op will be '&'
3162 iff one of these cases applies, and mask will be non-0 for operands
3163 whose length should be ignored.
3164 */
3165
Christian Heimese93237d2007-12-19 02:37:44 +00003166 size_a = Py_SIZE(a);
3167 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003168 size_z = op == '&'
3169 ? (maska
3170 ? size_b
3171 : (maskb ? size_a : MIN(size_a, size_b)))
3172 : MAX(size_a, size_b);
3173 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003174 if (z == NULL) {
Neal Norwitzef02b9e2006-07-16 02:00:32 +00003175 Py_DECREF(a);
3176 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003177 return NULL;
3178 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003179
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003180 for (i = 0; i < size_z; ++i) {
3181 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3182 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3183 switch (op) {
3184 case '&': z->ob_digit[i] = diga & digb; break;
3185 case '|': z->ob_digit[i] = diga | digb; break;
3186 case '^': z->ob_digit[i] = diga ^ digb; break;
3187 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003188 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003189
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003190 Py_DECREF(a);
3191 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003192 z = long_normalize(z);
3193 if (negz == 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003194 return (PyObject *) z;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003195 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003196 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003197 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003198}
3199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003200static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003201long_and(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003202{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003203 PyLongObject *a, *b;
3204 PyObject *c;
3205 CONVERT_BINOP(v, w, &a, &b);
3206 c = long_bitwise(a, '&', b);
3207 Py_DECREF(a);
3208 Py_DECREF(b);
3209 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003210}
3211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003212static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003213long_xor(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003214{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003215 PyLongObject *a, *b;
3216 PyObject *c;
3217 CONVERT_BINOP(v, w, &a, &b);
3218 c = long_bitwise(a, '^', b);
3219 Py_DECREF(a);
3220 Py_DECREF(b);
3221 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003222}
3223
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003224static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003225long_or(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003226{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003227 PyLongObject *a, *b;
3228 PyObject *c;
3229 CONVERT_BINOP(v, w, &a, &b);
3230 c = long_bitwise(a, '|', b);
3231 Py_DECREF(a);
3232 Py_DECREF(b);
3233 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003234}
3235
Guido van Rossum234f9421993-06-17 12:35:49 +00003236static int
Tim Peters9f688bf2000-07-07 15:53:28 +00003237long_coerce(PyObject **pv, PyObject **pw)
Guido van Rossume6eefc21992-08-14 12:06:52 +00003238{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003239 if (PyInt_Check(*pw)) {
Neil Schemenauerba872e22001-01-04 01:46:03 +00003240 *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
Georg Brandlc02e1312007-04-11 17:16:24 +00003241 if (*pw == NULL)
3242 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003243 Py_INCREF(*pv);
Guido van Rossume6eefc21992-08-14 12:06:52 +00003244 return 0;
3245 }
Guido van Rossum1952e382001-09-19 01:25:16 +00003246 else if (PyLong_Check(*pw)) {
3247 Py_INCREF(*pv);
3248 Py_INCREF(*pw);
3249 return 0;
3250 }
Guido van Rossume6eefc21992-08-14 12:06:52 +00003251 return 1; /* Can't do it */
3252}
3253
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003254static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003255long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003256{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003257 if (PyLong_CheckExact(v))
3258 Py_INCREF(v);
3259 else
3260 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003261 return v;
3262}
3263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003264static PyObject *
Walter Dörwaldf1715402002-11-19 20:49:15 +00003265long_int(PyObject *v)
3266{
3267 long x;
3268 x = PyLong_AsLong(v);
3269 if (PyErr_Occurred()) {
3270 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
3271 PyErr_Clear();
3272 if (PyLong_CheckExact(v)) {
3273 Py_INCREF(v);
3274 return v;
3275 }
3276 else
3277 return _PyLong_Copy((PyLongObject *)v);
3278 }
3279 else
3280 return NULL;
3281 }
3282 return PyInt_FromLong(x);
3283}
3284
3285static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003286long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003287{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003288 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003289 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003290 if (result == -1.0 && PyErr_Occurred())
3291 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003292 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003293}
3294
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003295static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003296long_oct(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003297{
Eric Smith5e527eb2008-02-10 01:36:53 +00003298 return _PyLong_Format(v, 8, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003299}
3300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003301static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003302long_hex(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003303{
Eric Smith5e527eb2008-02-10 01:36:53 +00003304 return _PyLong_Format(v, 16, 1, 0);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003305}
Jeremy Hylton938ace62002-07-17 16:30:39 +00003306
3307static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003308long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003309
Tim Peters6d6c1a32001-08-02 04:15:00 +00003310static PyObject *
3311long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3312{
3313 PyObject *x = NULL;
3314 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003315 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003316
Guido van Rossumbef14172001-08-29 15:47:46 +00003317 if (type != &PyLong_Type)
3318 return long_subtype_new(type, args, kwds); /* Wimp out */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003319 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
3320 &x, &base))
3321 return NULL;
3322 if (x == NULL)
3323 return PyLong_FromLong(0L);
3324 if (base == -909)
3325 return PyNumber_Long(x);
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003326 else if (PyString_Check(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003327 /* Since PyLong_FromString doesn't have a length parameter,
3328 * check here for possible NULs in the string. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003329 char *string = PyString_AS_STRING(x);
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003330 if (strlen(string) != (size_t)PyString_Size(x)) {
Georg Brandl00cd8182007-03-06 18:41:12 +00003331 /* create a repr() of the input string,
3332 * just like PyLong_FromString does. */
3333 PyObject *srepr;
3334 srepr = PyObject_Repr(x);
3335 if (srepr == NULL)
3336 return NULL;
3337 PyErr_Format(PyExc_ValueError,
3338 "invalid literal for long() with base %d: %s",
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003339 base, PyString_AS_STRING(srepr));
Georg Brandl00cd8182007-03-06 18:41:12 +00003340 Py_DECREF(srepr);
3341 return NULL;
3342 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00003343 return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
Georg Brandl00cd8182007-03-06 18:41:12 +00003344 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003345#ifdef Py_USING_UNICODE
Tim Peters6d6c1a32001-08-02 04:15:00 +00003346 else if (PyUnicode_Check(x))
3347 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3348 PyUnicode_GET_SIZE(x),
3349 base);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003350#endif
Tim Peters6d6c1a32001-08-02 04:15:00 +00003351 else {
3352 PyErr_SetString(PyExc_TypeError,
3353 "long() can't convert non-string with explicit base");
3354 return NULL;
3355 }
3356}
3357
Guido van Rossumbef14172001-08-29 15:47:46 +00003358/* Wimpy, slow approach to tp_new calls for subtypes of long:
3359 first create a regular long from whatever arguments we got,
3360 then allocate a subtype instance and initialize it from
3361 the regular long. The regular long is then thrown away.
3362*/
3363static PyObject *
3364long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3365{
Anthony Baxter377be112006-04-11 06:54:30 +00003366 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003367 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003368
3369 assert(PyType_IsSubtype(type, &PyLong_Type));
3370 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3371 if (tmp == NULL)
3372 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003373 assert(PyLong_CheckExact(tmp));
Christian Heimese93237d2007-12-19 02:37:44 +00003374 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003375 if (n < 0)
3376 n = -n;
Anthony Baxter377be112006-04-11 06:54:30 +00003377 newobj = (PyLongObject *)type->tp_alloc(type, n);
3378 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003379 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003380 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003381 }
Anthony Baxter377be112006-04-11 06:54:30 +00003382 assert(PyLong_Check(newobj));
Christian Heimese93237d2007-12-19 02:37:44 +00003383 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003384 for (i = 0; i < n; i++)
Anthony Baxter377be112006-04-11 06:54:30 +00003385 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003386 Py_DECREF(tmp);
Anthony Baxter377be112006-04-11 06:54:30 +00003387 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003388}
3389
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003390static PyObject *
3391long_getnewargs(PyLongObject *v)
3392{
3393 return Py_BuildValue("(N)", _PyLong_Copy(v));
3394}
3395
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003396static PyObject *
3397long_getN(PyLongObject *v, void *context) {
Jeffrey Yasskin5de250e2008-03-18 01:09:59 +00003398 return PyLong_FromLong((Py_intptr_t)context);
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003399}
3400
Eric Smitha9f7d622008-02-17 19:46:49 +00003401static PyObject *
3402long__format__(PyObject *self, PyObject *args)
3403{
3404 PyObject *format_spec;
3405
3406 if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
3407 return NULL;
Christian Heimes593daf52008-05-26 12:51:38 +00003408 if (PyBytes_Check(format_spec))
Eric Smithdc13b792008-05-30 18:10:04 +00003409 return _PyLong_FormatAdvanced(self,
3410 PyBytes_AS_STRING(format_spec),
3411 PyBytes_GET_SIZE(format_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003412 if (PyUnicode_Check(format_spec)) {
3413 /* Convert format_spec to a str */
Eric Smithdc13b792008-05-30 18:10:04 +00003414 PyObject *result;
3415 PyObject *str_spec = PyObject_Str(format_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003416
Eric Smithdc13b792008-05-30 18:10:04 +00003417 if (str_spec == NULL)
3418 return NULL;
Eric Smitha9f7d622008-02-17 19:46:49 +00003419
Eric Smithdc13b792008-05-30 18:10:04 +00003420 result = _PyLong_FormatAdvanced(self,
3421 PyBytes_AS_STRING(str_spec),
3422 PyBytes_GET_SIZE(str_spec));
Eric Smitha9f7d622008-02-17 19:46:49 +00003423
Eric Smithdc13b792008-05-30 18:10:04 +00003424 Py_DECREF(str_spec);
Eric Smitha9f7d622008-02-17 19:46:49 +00003425 return result;
3426 }
3427 PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
3428 return NULL;
3429}
3430
Robert Schuppenies51df0642008-06-01 16:16:17 +00003431static PyObject *
3432long_sizeof(PyLongObject *v)
3433{
3434 Py_ssize_t res;
3435
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003436 res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
Robert Schuppenies51df0642008-06-01 16:16:17 +00003437 return PyInt_FromSsize_t(res);
3438}
3439
Mark Dickinson1a707982008-12-17 16:14:37 +00003440static const unsigned char BitLengthTable[32] = {
3441 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3442 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3443};
3444
3445static PyObject *
3446long_bit_length(PyLongObject *v)
3447{
3448 PyLongObject *result, *x, *y;
3449 Py_ssize_t ndigits, msd_bits = 0;
3450 digit msd;
3451
3452 assert(v != NULL);
3453 assert(PyLong_Check(v));
3454
3455 ndigits = ABS(Py_SIZE(v));
3456 if (ndigits == 0)
3457 return PyInt_FromLong(0);
3458
3459 msd = v->ob_digit[ndigits-1];
3460 while (msd >= 32) {
3461 msd_bits += 6;
3462 msd >>= 6;
3463 }
3464 msd_bits += (long)(BitLengthTable[msd]);
3465
3466 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3467 return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3468
3469 /* expression above may overflow; use Python integers instead */
3470 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3471 if (result == NULL)
3472 return NULL;
3473 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3474 if (x == NULL)
3475 goto error;
3476 y = (PyLongObject *)long_mul(result, x);
3477 Py_DECREF(x);
3478 if (y == NULL)
3479 goto error;
3480 Py_DECREF(result);
3481 result = y;
3482
3483 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3484 if (x == NULL)
3485 goto error;
3486 y = (PyLongObject *)long_add(result, x);
3487 Py_DECREF(x);
3488 if (y == NULL)
3489 goto error;
3490 Py_DECREF(result);
3491 result = y;
3492
3493 return (PyObject *)result;
3494
3495error:
3496 Py_DECREF(result);
3497 return NULL;
3498}
3499
3500PyDoc_STRVAR(long_bit_length_doc,
3501"long.bit_length() -> int or long\n\
3502\n\
3503Number of bits necessary to represent self in binary.\n\
3504>>> bin(37L)\n\
3505'0b100101'\n\
3506>>> (37L).bit_length()\n\
35076");
3508
Christian Heimes6f341092008-04-18 23:13:07 +00003509#if 0
3510static PyObject *
3511long_is_finite(PyObject *v)
3512{
3513 Py_RETURN_TRUE;
3514}
3515#endif
3516
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003517static PyMethodDef long_methods[] = {
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003518 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3519 "Returns self, the complex conjugate of any long."},
Mark Dickinson1a707982008-12-17 16:14:37 +00003520 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3521 long_bit_length_doc},
Christian Heimes6f341092008-04-18 23:13:07 +00003522#if 0
3523 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3524 "Returns always True."},
3525#endif
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003526 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3527 "Truncating an Integral returns itself."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003528 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smitha9f7d622008-02-17 19:46:49 +00003529 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Robert Schuppenies51df0642008-06-01 16:16:17 +00003530 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00003531 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003532 {NULL, NULL} /* sentinel */
3533};
3534
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003535static PyGetSetDef long_getset[] = {
3536 {"real",
3537 (getter)long_long, (setter)NULL,
3538 "the real part of a complex number",
3539 NULL},
3540 {"imag",
3541 (getter)long_getN, (setter)NULL,
3542 "the imaginary part of a complex number",
3543 (void*)0},
3544 {"numerator",
3545 (getter)long_long, (setter)NULL,
3546 "the numerator of a rational number in lowest terms",
3547 NULL},
3548 {"denominator",
3549 (getter)long_getN, (setter)NULL,
3550 "the denominator of a rational number in lowest terms",
3551 (void*)1},
3552 {NULL} /* Sentinel */
3553};
3554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003555PyDoc_STRVAR(long_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556"long(x[, base]) -> integer\n\
3557\n\
3558Convert a string or number to a long integer, if possible. A floating\n\
3559point argument will be truncated towards zero (this does not include a\n\
3560string representation of a floating point number!) When converting a\n\
3561string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003562converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003564static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003565 (binaryfunc) long_add, /*nb_add*/
3566 (binaryfunc) long_sub, /*nb_subtract*/
3567 (binaryfunc) long_mul, /*nb_multiply*/
Georg Brandl347b3002006-03-30 11:57:00 +00003568 long_classic_div, /*nb_divide*/
3569 long_mod, /*nb_remainder*/
3570 long_divmod, /*nb_divmod*/
3571 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003572 (unaryfunc) long_neg, /*nb_negative*/
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003573 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003574 (unaryfunc) long_abs, /*tp_absolute*/
3575 (inquiry) long_nonzero, /*tp_nonzero*/
3576 (unaryfunc) long_invert, /*nb_invert*/
Georg Brandl347b3002006-03-30 11:57:00 +00003577 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003578 (binaryfunc) long_rshift, /*nb_rshift*/
Georg Brandl347b3002006-03-30 11:57:00 +00003579 long_and, /*nb_and*/
3580 long_xor, /*nb_xor*/
3581 long_or, /*nb_or*/
3582 long_coerce, /*nb_coerce*/
3583 long_int, /*nb_int*/
3584 long_long, /*nb_long*/
3585 long_float, /*nb_float*/
3586 long_oct, /*nb_oct*/
3587 long_hex, /*nb_hex*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003588 0, /* nb_inplace_add */
3589 0, /* nb_inplace_subtract */
3590 0, /* nb_inplace_multiply */
3591 0, /* nb_inplace_divide */
3592 0, /* nb_inplace_remainder */
3593 0, /* nb_inplace_power */
3594 0, /* nb_inplace_lshift */
3595 0, /* nb_inplace_rshift */
3596 0, /* nb_inplace_and */
3597 0, /* nb_inplace_xor */
3598 0, /* nb_inplace_or */
Georg Brandl347b3002006-03-30 11:57:00 +00003599 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003600 long_true_divide, /* nb_true_divide */
3601 0, /* nb_inplace_floor_divide */
3602 0, /* nb_inplace_true_divide */
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00003603 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003604};
3605
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003606PyTypeObject PyLong_Type = {
3607 PyObject_HEAD_INIT(&PyType_Type)
Tim Peters6d6c1a32001-08-02 04:15:00 +00003608 0, /* ob_size */
3609 "long", /* tp_name */
Mark Dickinson2ffb26f2009-02-15 10:13:41 +00003610 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003611 sizeof(digit), /* tp_itemsize */
Georg Brandl347b3002006-03-30 11:57:00 +00003612 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003613 0, /* tp_print */
3614 0, /* tp_getattr */
3615 0, /* tp_setattr */
3616 (cmpfunc)long_compare, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003617 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003618 &long_as_number, /* tp_as_number */
3619 0, /* tp_as_sequence */
3620 0, /* tp_as_mapping */
3621 (hashfunc)long_hash, /* tp_hash */
3622 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003623 long_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003624 PyObject_GenericGetAttr, /* tp_getattro */
3625 0, /* tp_setattro */
3626 0, /* tp_as_buffer */
Guido van Rossumbef14172001-08-29 15:47:46 +00003627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00003628 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003629 long_doc, /* tp_doc */
3630 0, /* tp_traverse */
3631 0, /* tp_clear */
3632 0, /* tp_richcompare */
3633 0, /* tp_weaklistoffset */
3634 0, /* tp_iter */
3635 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003636 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003637 0, /* tp_members */
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +00003638 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003639 0, /* tp_base */
3640 0, /* tp_dict */
3641 0, /* tp_descr_get */
3642 0, /* tp_descr_set */
3643 0, /* tp_dictoffset */
3644 0, /* tp_init */
3645 0, /* tp_alloc */
3646 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003647 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003648};