blob: 9993d103ea24644bc2e5f858d7305e3af27ab28d [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00008#include <ctype.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +00009
Guido van Rossumddefaf32007-01-14 03:31:43 +000010#ifndef NSMALLPOSINTS
11#define NSMALLPOSINTS 257
12#endif
13#ifndef NSMALLNEGINTS
14#define NSMALLNEGINTS 5
15#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000016
17#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(x)->ob_digit[0] : \
18 (Py_SIZE(x) == 0 ? 0 : (x)->ob_digit[0]))
19#define ABS(x) ((x) < 0 ? -(x) : (x))
20
Guido van Rossumddefaf32007-01-14 03:31:43 +000021#if NSMALLNEGINTS + NSMALLPOSINTS > 0
22/* Small integers are preallocated in this array so that they
23 can be shared.
24 The integers that are preallocated are those in the range
25 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
26*/
27static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
28#ifdef COUNT_ALLOCS
29int quick_int_allocs, quick_neg_int_allocs;
30#endif
31
Guido van Rossum7eaf8222007-06-18 17:58:50 +000032static PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +000033get_small_int(int ival)
34{
35 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
36 Py_INCREF(v);
37#ifdef COUNT_ALLOCS
38 if (ival >= 0)
39 quick_int_allocs++;
40 else
41 quick_neg_int_allocs++;
42#endif
43 return v;
44}
45#define CHECK_SMALL_INT(ival) \
46 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
Mark Dickinson50b2b6e2008-12-05 17:14:29 +000047 return get_small_int((int)ival); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000048 } while(0)
49
Facundo Batista6e6f59b2008-07-24 18:57:11 +000050static PyLongObject *
51maybe_small_long(PyLongObject *v)
52{
53 if (v && ABS(Py_SIZE(v)) <= 1) {
54 int ival = MEDIUM_VALUE(v);
55 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
56 Py_DECREF(v);
57 return (PyLongObject *)get_small_int(ival);
58 }
59 }
60 return v;
61}
Guido van Rossumddefaf32007-01-14 03:31:43 +000062#else
63#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000064#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000065#endif
66
Guido van Rossumddefaf32007-01-14 03:31:43 +000067/* If a freshly-allocated long is already shared, it must
68 be a small integer, so negating it must go to PyLong_FromLong */
69#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000070 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000071 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000072 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
73 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000074/* For long multiplication, use the O(N**2) school algorithm unless
75 * both operands contain more than KARATSUBA_CUTOFF digits (this
76 * being an internal Python long digit, in base BASE).
77 */
Tim Peters0973b992004-08-29 22:16:50 +000078#define KARATSUBA_CUTOFF 70
79#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000080
Tim Peters47e52ee2004-08-30 02:44:38 +000081/* For exponentiation, use the binary left-to-right algorithm
82 * unless the exponent contains more than FIVEARY_CUTOFF digits.
83 * In that case, do 5 bits at a time. The potential drawback is that
84 * a table of 2**5 intermediate results is computed.
85 */
86#define FIVEARY_CUTOFF 8
87
Tim Peters5af4e6c2002-08-12 02:31:19 +000088#undef MIN
89#undef MAX
90#define MAX(x, y) ((x) < (y) ? (y) : (x))
91#define MIN(x, y) ((x) > (y) ? (y) : (x))
92
Guido van Rossume32e0141992-01-19 16:31:05 +000093/* Forward */
Tim Peters9f688bf2000-07-07 15:53:28 +000094static PyLongObject *long_normalize(PyLongObject *);
95static PyLongObject *mul1(PyLongObject *, wdigit);
96static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit);
Tim Peters212e6142001-07-14 12:23:19 +000097static PyLongObject *divrem1(PyLongObject *, digit, digit *);
Guido van Rossume32e0141992-01-19 16:31:05 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +0000100 if (--_Py_Ticker < 0) { \
101 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000103 }
104
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000105/* Normalize (remove leading zeros from) a long int object.
106 Doesn't attempt to free the storage--in most cases, due to the nature
107 of the algorithms used, this could save at most be one word anyway. */
108
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000110long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000111{
Christian Heimes90aa7642007-12-19 02:45:37 +0000112 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000114
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115 while (i > 0 && v->ob_digit[i-1] == 0)
116 --i;
117 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000118 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000119 return v;
120}
121
122/* Allocate a new long int object with size digits.
123 Return NULL and set exception if we run out of memory. */
124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000128 PyLongObject *result;
129 /* Can't use sizeof(PyLongObject) here, since the
130 compiler takes padding at the end into account.
131 As the consequence, this would waste 2 bytes on
132 a 32-bit system, and 6 bytes on a 64-bit system.
133 This computation would be incorrect on systems
134 which have padding before the digits; with 16-bit
135 digits this should not happen. */
136 result = PyObject_MALLOC(sizeof(PyVarObject) +
137 size*sizeof(digit));
138 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000139 PyErr_NoMemory();
140 return NULL;
141 }
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000142 /* XXX(nnorwitz): This can overflow --
143 PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect overflow */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000144 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000145}
146
Tim Peters64b5ce32001-09-10 20:52:51 +0000147PyObject *
148_PyLong_Copy(PyLongObject *src)
149{
150 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000151 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000152
153 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000154 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000155 if (i < 0)
156 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000157 if (i < 2) {
158 int ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000159 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000160 ival = -ival;
161 CHECK_SMALL_INT(ival);
162 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000163 result = _PyLong_New(i);
164 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000165 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000166 while (--i >= 0)
167 result->ob_digit[i] = src->ob_digit[i];
168 }
169 return (PyObject *)result;
170}
171
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000172/* Create a new long int object from a C long int */
173
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000175PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000176{
Tim Petersce9de2f2001-06-14 04:56:19 +0000177 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +0000178 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000179 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
180 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181 int sign = 1;
182
183 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000184
185 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +0000186 /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
187 ANSI C says that the result of -ival is undefined when ival
188 == LONG_MIN. Hence the following workaround. */
189 abs_ival = (unsigned long)(-1-ival) + 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000190 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000191 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Guido van Rossumddefaf32007-01-14 03:31:43 +0000196 /* Fast path for single-digits ints */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000197 if (!(ival>>PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000198 v = _PyLong_New(1);
199 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000200 Py_SIZE(v) = sign;
Mark Dickinson50b2b6e2008-12-05 17:14:29 +0000201 v->ob_digit[0] = (digit)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000202 }
203 return (PyObject*)v;
204 }
205
206 /* 2 digits */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000207 if (!(ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000208 v = _PyLong_New(2);
209 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000210 Py_SIZE(v) = 2*sign;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000211 v->ob_digit[0] = (digit)ival & PyLong_MASK;
Mark Dickinson50b2b6e2008-12-05 17:14:29 +0000212 v->ob_digit[1] = (digit)(ival >> PyLong_SHIFT);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000213 }
214 return (PyObject*)v;
215 }
216
217 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000218 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000219 while (t) {
220 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000221 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000222 }
223 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000224 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000226 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000227 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000228 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000229 *p++ = (digit)(t & PyLong_MASK);
230 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000231 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000232 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000233 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000234}
235
Guido van Rossum53756b11997-01-03 17:14:46 +0000236/* Create a new long int object from a C unsigned long int */
237
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000239PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000240{
Tim Petersce9de2f2001-06-14 04:56:19 +0000241 PyLongObject *v;
242 unsigned long t;
243 int ndigits = 0;
244
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000245 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000246 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000247 /* Count the number of Python digits. */
248 t = (unsigned long)ival;
249 while (t) {
250 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000251 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000252 }
253 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000254 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000255 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000256 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000257 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000258 *p++ = (digit)(ival & PyLong_MASK);
259 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000260 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000261 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000263}
264
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000265/* Create a new long int object from a C double */
266
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000267PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000268PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271 double frac;
272 int i, ndig, expo, neg;
273 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000274 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000275 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000276 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000277 return NULL;
278 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000279 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000280 PyErr_SetString(PyExc_ValueError,
281 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000282 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000283 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000284 if (dval < 0.0) {
285 neg = 1;
286 dval = -dval;
287 }
288 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
289 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000290 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000291 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000292 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000293 if (v == NULL)
294 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000295 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000296 for (i = ndig; --i >= 0; ) {
297 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000298 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000299 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000300 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000301 }
302 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000303 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000304 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000305}
306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
308 * anything about what happens when a signed integer operation overflows,
309 * and some compilers think they're doing you a favor by being "clever"
310 * then. The bit pattern for the largest postive signed long is
311 * (unsigned long)LONG_MAX, and for the smallest negative signed long
312 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
313 * However, some other compilers warn about applying unary minus to an
314 * unsigned operand. Hence the weird "0-".
315 */
316#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
317#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
318
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000319/* Get a C long int from a long int object.
320 Returns -1 and sets an error condition if overflow occurs. */
321
322long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000323PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000324{
Guido van Rossumf7531811998-05-26 14:33:37 +0000325 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000326 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000327 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000328 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000329 Py_ssize_t i;
330 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000331 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000332
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000333 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000334 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000336 return -1;
337 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000338
339 if (!PyLong_Check(vv)) {
340 PyNumberMethods *nb;
341 if ((nb = vv->ob_type->tp_as_number) == NULL ||
342 nb->nb_int == NULL) {
343 PyErr_SetString(PyExc_TypeError, "an integer is required");
344 return -1;
345 }
346 vv = (*nb->nb_int) (vv);
347 if (vv == NULL)
348 return -1;
349 do_decref = 1;
350 if (!PyLong_Check(vv)) {
351 Py_DECREF(vv);
352 PyErr_SetString(PyExc_TypeError,
353 "nb_int should return int object");
354 return -1;
355 }
356 }
357
Georg Brandl61c31b02007-02-26 14:46:30 +0000358 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000359 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000360 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000361
Georg Brandl61c31b02007-02-26 14:46:30 +0000362 switch (i) {
363 case -1:
364 res = -v->ob_digit[0];
365 break;
366 case 0:
367 res = 0;
368 break;
369 case 1:
370 res = v->ob_digit[0];
371 break;
372 default:
373 sign = 1;
374 x = 0;
375 if (i < 0) {
376 sign = -1;
377 i = -(i);
378 }
379 while (--i >= 0) {
380 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000381 x = (x << PyLong_SHIFT) + v->ob_digit[i];
382 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000383 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000384 goto exit;
385 }
386 }
387 /* Haven't lost any bits, but casting to long requires extra care
388 * (see comment above).
389 */
390 if (x <= (unsigned long)LONG_MAX) {
391 res = (long)x * sign;
392 }
393 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
394 res = LONG_MIN;
395 }
396 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000397 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000398 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000399 }
400 }
401 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000402 if (do_decref) {
403 Py_DECREF(vv);
404 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000405 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000406}
407
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000408long
409PyLong_AsLong(PyObject *obj)
410{
411 int overflow;
412 long result = PyLong_AsLongAndOverflow(obj, &overflow);
413 if (overflow) {
414 /* XXX: could be cute and give a different
415 message for overflow == -1 */
416 PyErr_SetString(PyExc_OverflowError,
417 "Python int too large to convert to C long");
418 }
419 return result;
420}
421
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000422/* Get a Py_ssize_t from a long int object.
423 Returns -1 and sets an error condition if overflow occurs. */
424
425Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000426PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000427 register PyLongObject *v;
428 size_t x, prev;
429 Py_ssize_t i;
430 int sign;
431
432 if (vv == NULL || !PyLong_Check(vv)) {
433 PyErr_BadInternalCall();
434 return -1;
435 }
436 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000437 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000438 switch (i) {
439 case -1: return -v->ob_digit[0];
440 case 0: return 0;
441 case 1: return v->ob_digit[0];
442 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443 sign = 1;
444 x = 0;
445 if (i < 0) {
446 sign = -1;
447 i = -(i);
448 }
449 while (--i >= 0) {
450 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000451 x = (x << PyLong_SHIFT) + v->ob_digit[i];
452 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000453 goto overflow;
454 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455 /* Haven't lost any bits, but casting to a signed type requires
456 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 if (x <= (size_t)PY_SSIZE_T_MAX) {
459 return (Py_ssize_t)x * sign;
460 }
461 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
462 return PY_SSIZE_T_MIN;
463 }
464 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000465
466 overflow:
467 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000468 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000469 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000470}
471
Guido van Rossumd8c80482002-08-13 00:24:58 +0000472/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000473 Returns -1 and sets an error condition if overflow occurs. */
474
475unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000476PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000477{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000479 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000480 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000481
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482 if (vv == NULL || !PyLong_Check(vv)) {
483 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000484 return (unsigned long) -1;
485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000487 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000488 x = 0;
489 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000491 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000492 return (unsigned long) -1;
493 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000494 switch (i) {
495 case 0: return 0;
496 case 1: return v->ob_digit[0];
497 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000498 while (--i >= 0) {
499 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000500 x = (x << PyLong_SHIFT) + v->ob_digit[i];
501 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000503 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000504 return (unsigned long) -1;
505 }
506 }
507 return x;
508}
509
510/* Get a C unsigned long int from a long int object.
511 Returns -1 and sets an error condition if overflow occurs. */
512
513size_t
514PyLong_AsSize_t(PyObject *vv)
515{
516 register PyLongObject *v;
517 size_t x, prev;
518 Py_ssize_t i;
519
520 if (vv == NULL || !PyLong_Check(vv)) {
521 PyErr_BadInternalCall();
522 return (unsigned long) -1;
523 }
524 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000525 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000526 x = 0;
527 if (i < 0) {
528 PyErr_SetString(PyExc_OverflowError,
529 "can't convert negative value to size_t");
530 return (size_t) -1;
531 }
532 switch (i) {
533 case 0: return 0;
534 case 1: return v->ob_digit[0];
535 }
536 while (--i >= 0) {
537 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000538 x = (x << PyLong_SHIFT) + v->ob_digit[i];
539 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000540 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000541 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000542 return (unsigned long) -1;
543 }
544 }
545 return x;
546}
547
Thomas Hellera4ea6032003-04-17 18:55:45 +0000548/* Get a C unsigned long int from a long int object, ignoring the high bits.
549 Returns -1 and sets an error condition if an error occurs. */
550
Guido van Rossumddefaf32007-01-14 03:31:43 +0000551static unsigned long
552_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000553{
554 register PyLongObject *v;
555 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000556 Py_ssize_t i;
557 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000558
559 if (vv == NULL || !PyLong_Check(vv)) {
560 PyErr_BadInternalCall();
561 return (unsigned long) -1;
562 }
563 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000564 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000565 switch (i) {
566 case 0: return 0;
567 case 1: return v->ob_digit[0];
568 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000569 sign = 1;
570 x = 0;
571 if (i < 0) {
572 sign = -1;
573 i = -i;
574 }
575 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000576 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000577 }
578 return x * sign;
579}
580
Guido van Rossumddefaf32007-01-14 03:31:43 +0000581unsigned long
582PyLong_AsUnsignedLongMask(register PyObject *op)
583{
584 PyNumberMethods *nb;
585 PyLongObject *lo;
586 unsigned long val;
587
588 if (op && PyLong_Check(op))
589 return _PyLong_AsUnsignedLongMask(op);
590
591 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
592 nb->nb_int == NULL) {
593 PyErr_SetString(PyExc_TypeError, "an integer is required");
594 return (unsigned long)-1;
595 }
596
597 lo = (PyLongObject*) (*nb->nb_int) (op);
598 if (lo == NULL)
599 return (unsigned long)-1;
600 if (PyLong_Check(lo)) {
601 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
602 Py_DECREF(lo);
603 if (PyErr_Occurred())
604 return (unsigned long)-1;
605 return val;
606 }
607 else
608 {
609 Py_DECREF(lo);
610 PyErr_SetString(PyExc_TypeError,
611 "nb_int should return int object");
612 return (unsigned long)-1;
613 }
614}
615
Tim Peters5b8132f2003-01-31 15:52:05 +0000616int
617_PyLong_Sign(PyObject *vv)
618{
619 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000620
621 assert(v != NULL);
622 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000623
Christian Heimes90aa7642007-12-19 02:45:37 +0000624 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000625}
626
Tim Petersbaefd9e2003-01-28 20:37:45 +0000627size_t
628_PyLong_NumBits(PyObject *vv)
629{
630 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000631 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000632 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000633
634 assert(v != NULL);
635 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000636 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000637 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
638 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000639 digit msd = v->ob_digit[ndigits - 1];
640
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000641 result = (ndigits - 1) * PyLong_SHIFT;
642 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000643 goto Overflow;
644 do {
645 ++result;
646 if (result == 0)
647 goto Overflow;
648 msd >>= 1;
649 } while (msd);
650 }
651 return result;
652
653Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000654 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000655 "to express in a platform size_t");
656 return (size_t)-1;
657}
658
Tim Peters2a9b3672001-06-11 21:23:58 +0000659PyObject *
660_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
661 int little_endian, int is_signed)
662{
663 const unsigned char* pstartbyte;/* LSB of bytes */
664 int incr; /* direction to move pstartbyte */
665 const unsigned char* pendbyte; /* MSB of bytes */
666 size_t numsignificantbytes; /* number of bytes that matter */
667 size_t ndigits; /* number of Python long digits */
668 PyLongObject* v; /* result */
669 int idigit = 0; /* next free index in v->ob_digit */
670
671 if (n == 0)
672 return PyLong_FromLong(0L);
673
674 if (little_endian) {
675 pstartbyte = bytes;
676 pendbyte = bytes + n - 1;
677 incr = 1;
678 }
679 else {
680 pstartbyte = bytes + n - 1;
681 pendbyte = bytes;
682 incr = -1;
683 }
684
685 if (is_signed)
686 is_signed = *pendbyte >= 0x80;
687
688 /* Compute numsignificantbytes. This consists of finding the most
689 significant byte. Leading 0 bytes are insignficant if the number
690 is positive, and leading 0xff bytes if negative. */
691 {
692 size_t i;
693 const unsigned char* p = pendbyte;
694 const int pincr = -incr; /* search MSB to LSB */
695 const unsigned char insignficant = is_signed ? 0xff : 0x00;
696
697 for (i = 0; i < n; ++i, p += pincr) {
698 if (*p != insignficant)
699 break;
700 }
701 numsignificantbytes = n - i;
702 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
703 actually has 2 significant bytes. OTOH, 0xff0001 ==
704 -0x00ffff, so we wouldn't *need* to bump it there; but we
705 do for 0xffff = -0x0001. To be safe without bothering to
706 check every case, bump it regardless. */
707 if (is_signed && numsignificantbytes < n)
708 ++numsignificantbytes;
709 }
710
711 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000712 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000713 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000714 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000715 if (ndigits > (size_t)INT_MAX)
716 return PyErr_NoMemory();
717 v = _PyLong_New((int)ndigits);
718 if (v == NULL)
719 return NULL;
720
721 /* Copy the bits over. The tricky parts are computing 2's-comp on
722 the fly for signed numbers, and dealing with the mismatch between
723 8-bit bytes and (probably) 15-bit Python digits.*/
724 {
725 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000726 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000727 twodigits accum = 0; /* sliding register */
728 unsigned int accumbits = 0; /* number of bits in accum */
729 const unsigned char* p = pstartbyte;
730
731 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000732 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000733 /* Compute correction for 2's comp, if needed. */
734 if (is_signed) {
735 thisbyte = (0xff ^ thisbyte) + carry;
736 carry = thisbyte >> 8;
737 thisbyte &= 0xff;
738 }
739 /* Because we're going LSB to MSB, thisbyte is
740 more significant than what's already in accum,
741 so needs to be prepended to accum. */
742 accum |= thisbyte << accumbits;
743 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000744 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000745 /* There's enough to fill a Python digit. */
746 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000747 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000748 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000749 accum >>= PyLong_SHIFT;
750 accumbits -= PyLong_SHIFT;
751 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000752 }
753 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000754 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 if (accumbits) {
756 assert(idigit < (int)ndigits);
757 v->ob_digit[idigit] = (digit)accum;
758 ++idigit;
759 }
760 }
761
Christian Heimes90aa7642007-12-19 02:45:37 +0000762 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000763 return (PyObject *)long_normalize(v);
764}
765
766int
767_PyLong_AsByteArray(PyLongObject* v,
768 unsigned char* bytes, size_t n,
769 int little_endian, int is_signed)
770{
771 int i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000772 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000773 twodigits accum; /* sliding register */
774 unsigned int accumbits; /* # bits in accum */
775 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
776 twodigits carry; /* for computing 2's-comp */
777 size_t j; /* # bytes filled */
778 unsigned char* p; /* pointer to next byte in bytes */
779 int pincr; /* direction to move p */
780
781 assert(v != NULL && PyLong_Check(v));
782
Christian Heimes90aa7642007-12-19 02:45:37 +0000783 if (Py_SIZE(v) < 0) {
784 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000785 if (!is_signed) {
786 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000787 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000788 return -1;
789 }
790 do_twos_comp = 1;
791 }
792 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000793 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000794 do_twos_comp = 0;
795 }
796
797 if (little_endian) {
798 p = bytes;
799 pincr = 1;
800 }
801 else {
802 p = bytes + n - 1;
803 pincr = -1;
804 }
805
Tim Peters898cf852001-06-13 20:50:08 +0000806 /* Copy over all the Python digits.
807 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000808 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000809 normalized. */
810 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000811 j = 0;
812 accum = 0;
813 accumbits = 0;
814 carry = do_twos_comp ? 1 : 0;
815 for (i = 0; i < ndigits; ++i) {
816 twodigits thisdigit = v->ob_digit[i];
817 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000818 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
819 carry = thisdigit >> PyLong_SHIFT;
820 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000821 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000822 /* Because we're going LSB to MSB, thisdigit is more
823 significant than what's already in accum, so needs to be
824 prepended to accum. */
825 accum |= thisdigit << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000826 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000827
Tim Petersede05092001-06-14 08:53:38 +0000828 /* The most-significant digit may be (probably is) at least
829 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000830 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000831 /* Count # of sign bits -- they needn't be stored,
832 * although for signed conversion we need later to
833 * make sure at least one sign bit gets stored.
834 * First shift conceptual sign bit to real sign bit.
835 */
836 stwodigits s = (stwodigits)(thisdigit <<
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000837 (8*sizeof(stwodigits) - PyLong_SHIFT));
Tim Peters7a3bfc32001-06-12 01:22:22 +0000838 unsigned int nsignbits = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000839 while ((s < 0) == do_twos_comp && nsignbits < PyLong_SHIFT) {
Tim Peters7a3bfc32001-06-12 01:22:22 +0000840 ++nsignbits;
Tim Petersede05092001-06-14 08:53:38 +0000841 s <<= 1;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000842 }
Tim Petersede05092001-06-14 08:53:38 +0000843 accumbits -= nsignbits;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000844 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000845
Tim Peters2a9b3672001-06-11 21:23:58 +0000846 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000847 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000848 if (j >= n)
849 goto Overflow;
850 ++j;
851 *p = (unsigned char)(accum & 0xff);
852 p += pincr;
853 accumbits -= 8;
854 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000855 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000856 }
857
858 /* Store the straggler (if any). */
859 assert(accumbits < 8);
860 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000861 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000862 if (j >= n)
863 goto Overflow;
864 ++j;
865 if (do_twos_comp) {
866 /* Fill leading bits of the byte with sign bits
867 (appropriately pretending that the long had an
868 infinite supply of sign bits). */
869 accum |= (~(twodigits)0) << accumbits;
870 }
871 *p = (unsigned char)(accum & 0xff);
872 p += pincr;
873 }
Tim Peters05607ad2001-06-13 21:01:27 +0000874 else if (j == n && n > 0 && is_signed) {
875 /* The main loop filled the byte array exactly, so the code
876 just above didn't get to ensure there's a sign bit, and the
877 loop below wouldn't add one either. Make sure a sign bit
878 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000879 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000880 int sign_bit_set = msb >= 0x80;
881 assert(accumbits == 0);
882 if (sign_bit_set == do_twos_comp)
883 return 0;
884 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000885 goto Overflow;
886 }
Tim Peters05607ad2001-06-13 21:01:27 +0000887
888 /* Fill remaining bytes with copies of the sign bit. */
889 {
890 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
891 for ( ; j < n; ++j, p += pincr)
892 *p = signbyte;
893 }
894
Tim Peters2a9b3672001-06-11 21:23:58 +0000895 return 0;
896
897Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000898 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000899 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000900
Tim Peters2a9b3672001-06-11 21:23:58 +0000901}
902
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000903double
904_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
905{
906/* NBITS_WANTED should be > the number of bits in a double's precision,
907 but small enough so that 2**NBITS_WANTED is within the normal double
908 range. nbitsneeded is set to 1 less than that because the most-significant
909 Python digit contains at least 1 significant bit, but we don't want to
910 bother counting them (catering to the worst case cheaply).
911
912 57 is one more than VAX-D double precision; I (Tim) don't know of a double
913 format with more precision than that; it's 1 larger so that we add in at
914 least one round bit to stand in for the ignored least-significant bits.
915*/
916#define NBITS_WANTED 57
917 PyLongObject *v;
918 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000919 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000920 Py_ssize_t i;
921 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000922 int nbitsneeded;
923
924 if (vv == NULL || !PyLong_Check(vv)) {
925 PyErr_BadInternalCall();
926 return -1;
927 }
928 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000929 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000930 sign = 1;
931 if (i < 0) {
932 sign = -1;
933 i = -(i);
934 }
935 else if (i == 0) {
936 *exponent = 0;
937 return 0.0;
938 }
939 --i;
940 x = (double)v->ob_digit[i];
941 nbitsneeded = NBITS_WANTED - 1;
942 /* Invariant: i Python digits remain unaccounted for. */
943 while (i > 0 && nbitsneeded > 0) {
944 --i;
945 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000946 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000947 }
948 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000949 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000950 *exponent = i;
951 assert(x > 0.0);
952 return x * sign;
953#undef NBITS_WANTED
954}
955
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000956/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000957
958double
Tim Peters9f688bf2000-07-07 15:53:28 +0000959PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000960{
Thomas Wouters553489a2006-02-01 21:32:04 +0000961 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000962 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000963
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964 if (vv == NULL || !PyLong_Check(vv)) {
965 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000966 return -1;
967 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000968 x = _PyLong_AsScaledDouble(vv, &e);
969 if (x == -1.0 && PyErr_Occurred())
970 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000971 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
972 set correctly after a successful _PyLong_AsScaledDouble() call */
973 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000974 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000975 goto overflow;
976 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000977 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000978 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000979 goto overflow;
980 return x;
981
982overflow:
983 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000984 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000985 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000986}
987
Guido van Rossum78694d91998-09-18 14:14:13 +0000988/* Create a new long (or int) object from a C pointer */
989
990PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000991PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000992{
Tim Peters70128a12001-06-16 08:48:40 +0000993#ifndef HAVE_LONG_LONG
994# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
995#endif
996#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000997# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000998#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000999 /* special-case null pointer */
1000 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001001 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001002 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001003
Guido van Rossum78694d91998-09-18 14:14:13 +00001004}
1005
1006/* Get a C pointer from a long object (or an int object in some cases) */
1007
1008void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001009PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001010{
1011 /* This function will allow int or long objects. If vv is neither,
1012 then the PyLong_AsLong*() functions will raise the exception:
1013 PyExc_SystemError, "bad argument to internal function"
1014 */
Tim Peters70128a12001-06-16 08:48:40 +00001015#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001016 long x;
1017
Guido van Rossumddefaf32007-01-14 03:31:43 +00001018 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001019 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001020 else
1021 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001022#else
Tim Peters70128a12001-06-16 08:48:40 +00001023
1024#ifndef HAVE_LONG_LONG
1025# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1026#endif
1027#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001028# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001029#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001030 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001031
Guido van Rossumddefaf32007-01-14 03:31:43 +00001032 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001033 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001034 else
1035 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001036
1037#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001038
1039 if (x == -1 && PyErr_Occurred())
1040 return NULL;
1041 return (void *)x;
1042}
1043
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001045
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001046/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001047 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001048 */
1049
Tim Peterscf37dfc2001-06-14 18:42:50 +00001050#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001051
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001052/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001053
1054PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001055PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001056{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001058 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1060 int ndigits = 0;
1061 int negative = 0;
1062
Guido van Rossumddefaf32007-01-14 03:31:43 +00001063 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001065 /* avoid signed overflow on negation; see comments
1066 in PyLong_FromLong above. */
1067 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068 negative = 1;
1069 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001070 else {
1071 abs_ival = (unsigned PY_LONG_LONG)ival;
1072 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073
1074 /* Count the number of Python digits.
1075 We used to pick 5 ("big enough for anything"), but that's a
1076 waste of time and space given that 5*15 = 75 bits are rarely
1077 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001078 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 while (t) {
1080 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001081 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082 }
1083 v = _PyLong_New(ndigits);
1084 if (v != NULL) {
1085 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001086 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001087 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001089 *p++ = (digit)(t & PyLong_MASK);
1090 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 }
1092 }
1093 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001094}
1095
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001096/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001097
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001098PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001099PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001100{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101 PyLongObject *v;
1102 unsigned PY_LONG_LONG t;
1103 int ndigits = 0;
1104
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001105 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001106 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001107 /* Count the number of Python digits. */
1108 t = (unsigned PY_LONG_LONG)ival;
1109 while (t) {
1110 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001111 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 }
1113 v = _PyLong_New(ndigits);
1114 if (v != NULL) {
1115 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001116 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001118 *p++ = (digit)(ival & PyLong_MASK);
1119 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 }
1121 }
1122 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001123}
1124
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125/* Create a new long int object from a C Py_ssize_t. */
1126
1127PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001128PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001129{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001130 PyLongObject *v;
1131 size_t abs_ival;
1132 size_t t; /* unsigned so >> doesn't propagate sign bit */
1133 int ndigits = 0;
1134 int negative = 0;
1135
1136 CHECK_SMALL_INT(ival);
1137 if (ival < 0) {
1138 /* avoid signed overflow when ival = SIZE_T_MIN */
1139 abs_ival = (size_t)(-1-ival)+1;
1140 negative = 1;
1141 }
1142 else {
1143 abs_ival = (size_t)ival;
1144 }
1145
1146 /* Count the number of Python digits. */
1147 t = abs_ival;
1148 while (t) {
1149 ++ndigits;
1150 t >>= PyLong_SHIFT;
1151 }
1152 v = _PyLong_New(ndigits);
1153 if (v != NULL) {
1154 digit *p = v->ob_digit;
1155 Py_SIZE(v) = negative ? -ndigits : ndigits;
1156 t = abs_ival;
1157 while (t) {
1158 *p++ = (digit)(t & PyLong_MASK);
1159 t >>= PyLong_SHIFT;
1160 }
1161 }
1162 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163}
1164
1165/* Create a new long int object from a C size_t. */
1166
1167PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001168PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001169{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001170 PyLongObject *v;
1171 size_t t;
1172 int ndigits = 0;
1173
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001174 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001175 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001176 /* Count the number of Python digits. */
1177 t = ival;
1178 while (t) {
1179 ++ndigits;
1180 t >>= PyLong_SHIFT;
1181 }
1182 v = _PyLong_New(ndigits);
1183 if (v != NULL) {
1184 digit *p = v->ob_digit;
1185 Py_SIZE(v) = ndigits;
1186 while (ival) {
1187 *p++ = (digit)(ival & PyLong_MASK);
1188 ival >>= PyLong_SHIFT;
1189 }
1190 }
1191 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001192}
1193
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001194/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001195 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001197PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001198PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001200 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001201 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001202 int one = 1;
1203 int res;
1204
Tim Petersd38b1c72001-09-30 05:09:37 +00001205 if (vv == NULL) {
1206 PyErr_BadInternalCall();
1207 return -1;
1208 }
1209 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001210 PyNumberMethods *nb;
1211 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001212 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1213 nb->nb_int == NULL) {
1214 PyErr_SetString(PyExc_TypeError, "an integer is required");
1215 return -1;
1216 }
1217 io = (*nb->nb_int) (vv);
1218 if (io == NULL)
1219 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001220 if (PyLong_Check(io)) {
1221 bytes = PyLong_AsLongLong(io);
1222 Py_DECREF(io);
1223 return bytes;
1224 }
1225 Py_DECREF(io);
1226 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001227 return -1;
1228 }
1229
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001231 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001232 case -1: return -v->ob_digit[0];
1233 case 0: return 0;
1234 case 1: return v->ob_digit[0];
1235 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001236 res = _PyLong_AsByteArray(
1237 (PyLongObject *)vv, (unsigned char *)&bytes,
1238 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001240 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001241 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001242 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001243 else
1244 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001245}
1246
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001247/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001248 Return -1 and set an error if overflow occurs. */
1249
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001250unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001251PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001252{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001253 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001254 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001255 int one = 1;
1256 int res;
1257
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001258 if (vv == NULL || !PyLong_Check(vv)) {
1259 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001260 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261 }
1262
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001264 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265 case 0: return 0;
1266 case 1: return v->ob_digit[0];
1267 }
1268
Tim Petersd1a7da62001-06-13 00:35:57 +00001269 res = _PyLong_AsByteArray(
1270 (PyLongObject *)vv, (unsigned char *)&bytes,
1271 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001272
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001273 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001274 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001275 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001276 else
1277 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001278}
Tim Petersd1a7da62001-06-13 00:35:57 +00001279
Thomas Hellera4ea6032003-04-17 18:55:45 +00001280/* Get a C unsigned long int from a long int object, ignoring the high bits.
1281 Returns -1 and sets an error condition if an error occurs. */
1282
Guido van Rossumddefaf32007-01-14 03:31:43 +00001283static unsigned PY_LONG_LONG
1284_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001285{
1286 register PyLongObject *v;
1287 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001288 Py_ssize_t i;
1289 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001290
1291 if (vv == NULL || !PyLong_Check(vv)) {
1292 PyErr_BadInternalCall();
1293 return (unsigned long) -1;
1294 }
1295 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001296 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001297 case 0: return 0;
1298 case 1: return v->ob_digit[0];
1299 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001300 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001301 sign = 1;
1302 x = 0;
1303 if (i < 0) {
1304 sign = -1;
1305 i = -i;
1306 }
1307 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001308 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001309 }
1310 return x * sign;
1311}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312
1313unsigned PY_LONG_LONG
1314PyLong_AsUnsignedLongLongMask(register PyObject *op)
1315{
1316 PyNumberMethods *nb;
1317 PyLongObject *lo;
1318 unsigned PY_LONG_LONG val;
1319
1320 if (op && PyLong_Check(op))
1321 return _PyLong_AsUnsignedLongLongMask(op);
1322
1323 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1324 nb->nb_int == NULL) {
1325 PyErr_SetString(PyExc_TypeError, "an integer is required");
1326 return (unsigned PY_LONG_LONG)-1;
1327 }
1328
1329 lo = (PyLongObject*) (*nb->nb_int) (op);
1330 if (lo == NULL)
1331 return (unsigned PY_LONG_LONG)-1;
1332 if (PyLong_Check(lo)) {
1333 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1334 Py_DECREF(lo);
1335 if (PyErr_Occurred())
1336 return (unsigned PY_LONG_LONG)-1;
1337 return val;
1338 }
1339 else
1340 {
1341 Py_DECREF(lo);
1342 PyErr_SetString(PyExc_TypeError,
1343 "nb_int should return int object");
1344 return (unsigned PY_LONG_LONG)-1;
1345 }
1346}
Tim Petersd1a7da62001-06-13 00:35:57 +00001347#undef IS_LITTLE_ENDIAN
1348
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001349#endif /* HAVE_LONG_LONG */
1350
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001351#define CHECK_BINOP(v,w) \
1352 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001353 Py_INCREF(Py_NotImplemented); \
1354 return Py_NotImplemented; \
1355 }
1356
Tim Peters877a2122002-08-12 05:09:36 +00001357/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1358 * is modified in place, by adding y to it. Carries are propagated as far as
1359 * x[m-1], and the remaining carry (0 or 1) is returned.
1360 */
1361static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001362v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001363{
1364 int i;
1365 digit carry = 0;
1366
1367 assert(m >= n);
1368 for (i = 0; i < n; ++i) {
1369 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001370 x[i] = carry & PyLong_MASK;
1371 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001372 assert((carry & 1) == carry);
1373 }
1374 for (; carry && i < m; ++i) {
1375 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001376 x[i] = carry & PyLong_MASK;
1377 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001378 assert((carry & 1) == carry);
1379 }
1380 return carry;
1381}
1382
1383/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1384 * is modified in place, by subtracting y from it. Borrows are propagated as
1385 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1386 */
1387static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001388v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001389{
1390 int i;
1391 digit borrow = 0;
1392
1393 assert(m >= n);
1394 for (i = 0; i < n; ++i) {
1395 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001396 x[i] = borrow & PyLong_MASK;
1397 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001398 borrow &= 1; /* keep only 1 sign bit */
1399 }
1400 for (; borrow && i < m; ++i) {
1401 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001402 x[i] = borrow & PyLong_MASK;
1403 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001404 borrow &= 1;
1405 }
1406 return borrow;
1407}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001408
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001409/* Multiply by a single digit, ignoring the sign. */
1410
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001411static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001412mul1(PyLongObject *a, wdigit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001413{
1414 return muladd1(a, n, (digit)0);
1415}
1416
1417/* Multiply by a single digit and add a single digit, ignoring the sign. */
1418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001419static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001420muladd1(PyLongObject *a, wdigit n, wdigit extra)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001421{
Christian Heimes90aa7642007-12-19 02:45:37 +00001422 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001423 PyLongObject *z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424 twodigits carry = extra;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001425 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001426
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427 if (z == NULL)
1428 return NULL;
1429 for (i = 0; i < size_a; ++i) {
1430 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001431 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1432 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001433 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001434 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001435 return long_normalize(z);
1436}
1437
Tim Peters212e6142001-07-14 12:23:19 +00001438/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1439 in pout, and returning the remainder. pin and pout point at the LSD.
1440 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001441 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001442 immutable. */
1443
1444static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001445inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001446{
1447 twodigits rem = 0;
1448
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001449 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001450 pin += size;
1451 pout += size;
1452 while (--size >= 0) {
1453 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001454 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001455 *--pout = hi = (digit)(rem / n);
1456 rem -= hi * n;
1457 }
1458 return (digit)rem;
1459}
1460
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001461/* Divide a long integer by a digit, returning both the quotient
1462 (as function result) and the remainder (through *prem).
1463 The sign of a is ignored; n should not be zero. */
1464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001465static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001466divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001467{
Christian Heimes90aa7642007-12-19 02:45:37 +00001468 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001469 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001470
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001471 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001472 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001473 if (z == NULL)
1474 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001475 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001476 return long_normalize(z);
1477}
1478
1479/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001480 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001481 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001482
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001483PyObject *
1484_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001485{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001486 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001487 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001488 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001490 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001491 int bits;
1492 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001493
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001494 if (a == NULL || !PyLong_Check(a)) {
1495 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001496 return NULL;
1497 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001498 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001499 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001500
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001501 /* Compute a rough upper bound for the length of the string */
1502 i = base;
1503 bits = 0;
1504 while (i > 1) {
1505 ++bits;
1506 i >>= 1;
1507 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001508 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001509 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001510 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001511 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001512 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001513 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001514 return NULL;
1515 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001516 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001517 if (str == NULL)
1518 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001519 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001520 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001521 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001522 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001523
Christian Heimes90aa7642007-12-19 02:45:37 +00001524 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001525 *--p = '0';
1526 }
1527 else if ((base & (base - 1)) == 0) {
1528 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001529 twodigits accum = 0;
1530 int accumbits = 0; /* # of bits in accum */
1531 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001532 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001533 while ((i >>= 1) > 1)
1534 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001535
1536 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001537 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001538 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001539 assert(accumbits >= basebits);
1540 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001541 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001542 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001543 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001544 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001545 accumbits -= basebits;
1546 accum >>= basebits;
1547 } while (i < size_a-1 ? accumbits >= basebits :
1548 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001549 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001550 }
1551 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001552 /* Not 0, and base not a power of 2. Divide repeatedly by
1553 base, but for speed use the highest power of base that
1554 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001555 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001556 digit *pin = a->ob_digit;
1557 PyLongObject *scratch;
1558 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001559 digit powbase = base; /* powbase == base ** power */
1560 int power = 1;
1561 for (;;) {
1562 unsigned long newpow = powbase * (unsigned long)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001563 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001564 break;
1565 powbase = (digit)newpow;
1566 ++power;
1567 }
Tim Peters212e6142001-07-14 12:23:19 +00001568
1569 /* Get a scratch area for repeated division. */
1570 scratch = _PyLong_New(size);
1571 if (scratch == NULL) {
1572 Py_DECREF(str);
1573 return NULL;
1574 }
1575
1576 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001577 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001578 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001579 digit rem = inplace_divrem1(scratch->ob_digit,
1580 pin, size, powbase);
1581 pin = scratch->ob_digit; /* no need to use a again */
1582 if (pin[size - 1] == 0)
1583 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001584 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001585 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001586 Py_DECREF(str);
1587 return NULL;
1588 })
Tim Peters212e6142001-07-14 12:23:19 +00001589
1590 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001591 assert(ntostore > 0);
1592 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001593 digit nextrem = (digit)(rem / base);
1594 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001595 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001596 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001597 *--p = c;
1598 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001599 --ntostore;
1600 /* Termination is a bit delicate: must not
1601 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001602 remaining quotient and rem are both 0. */
1603 } while (ntostore && (size || rem));
1604 } while (size != 0);
1605 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001606 }
1607
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001608 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001609 *--p = 'x';
1610 *--p = '0';
1611 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001612 else if (base == 8) {
1613 *--p = 'o';
1614 *--p = '0';
1615 }
1616 else if (base == 2) {
1617 *--p = 'b';
1618 *--p = '0';
1619 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001620 else if (base != 10) {
1621 *--p = '#';
1622 *--p = '0' + base%10;
1623 if (base > 10)
1624 *--p = '0' + base/10;
1625 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001626 if (sign)
1627 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001628 if (p != PyUnicode_AS_UNICODE(str)) {
1629 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001630 assert(p > q);
1631 do {
1632 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001633 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001634 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1635 Py_DECREF(str);
1636 return NULL;
1637 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001639 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001640}
1641
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642/* Table of digit values for 8-bit string -> integer conversion.
1643 * '0' maps to 0, ..., '9' maps to 9.
1644 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1645 * All other indices map to 37.
1646 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001647 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001648 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001649unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001650 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1651 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1652 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1653 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1654 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1655 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1656 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1657 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1658 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1659 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1660 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1661 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1662 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1663 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1664 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1665 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1666};
1667
1668/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001669 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1670 * non-digit (which may be *str!). A normalized long is returned.
1671 * The point to this routine is that it takes time linear in the number of
1672 * string characters.
1673 */
1674static PyLongObject *
1675long_from_binary_base(char **str, int base)
1676{
1677 char *p = *str;
1678 char *start = p;
1679 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001680 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001681 PyLongObject *z;
1682 twodigits accum;
1683 int bits_in_accum;
1684 digit *pdigit;
1685
1686 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1687 n = base;
1688 for (bits_per_char = -1; n; ++bits_per_char)
1689 n >>= 1;
1690 /* n <- total # of bits needed, while setting p to end-of-string */
1691 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001692 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001693 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001694 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001695 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1696 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001697 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001698 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001699 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001700 return NULL;
1701 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001702 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001703 z = _PyLong_New(n);
1704 if (z == NULL)
1705 return NULL;
1706 /* Read string from right, and fill in long from left; i.e.,
1707 * from least to most significant in both.
1708 */
1709 accum = 0;
1710 bits_in_accum = 0;
1711 pdigit = z->ob_digit;
1712 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001713 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001714 assert(k >= 0 && k < base);
1715 accum |= (twodigits)(k << bits_in_accum);
Tim Petersbf2674b2003-02-02 07:51:32 +00001716 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001717 if (bits_in_accum >= PyLong_SHIFT) {
1718 *pdigit++ = (digit)(accum & PyLong_MASK);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001719 assert(pdigit - z->ob_digit <= (int)n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001720 accum >>= PyLong_SHIFT;
1721 bits_in_accum -= PyLong_SHIFT;
1722 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001723 }
1724 }
1725 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001726 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001727 *pdigit++ = (digit)accum;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001728 assert(pdigit - z->ob_digit <= (int)n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001729 }
1730 while (pdigit - z->ob_digit < n)
1731 *pdigit++ = 0;
1732 return long_normalize(z);
1733}
1734
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001735PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001736PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001737{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001738 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001739 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001740 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001741 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001742 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001743
Guido van Rossum472c04f1996-12-05 21:57:21 +00001744 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001745 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001746 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001747 return NULL;
1748 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001749 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001750 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751 if (*str == '+')
1752 ++str;
1753 else if (*str == '-') {
1754 ++str;
1755 sign = -1;
1756 }
1757 if (base == 0) {
1758 if (str[0] != '0')
1759 base = 10;
1760 else if (str[1] == 'x' || str[1] == 'X')
1761 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001762 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001763 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001764 else if (str[1] == 'b' || str[1] == 'B')
1765 base = 2;
1766 else {
1767 /* "old" (C-style) octal literal, now invalid.
1768 it might still be zero though */
1769 error_if_nonzero = 1;
1770 base = 10;
1771 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001772 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001773 if (str[0] == '0' &&
1774 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1775 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1776 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001777 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778
Guido van Rossume6762971998-06-22 03:54:46 +00001779 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001780 if ((base & (base - 1)) == 0)
1781 z = long_from_binary_base(&str, base);
1782 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001783/***
1784Binary bases can be converted in time linear in the number of digits, because
1785Python's representation base is binary. Other bases (including decimal!) use
1786the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001787
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788First some math: the largest integer that can be expressed in N base-B digits
1789is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1790case number of Python digits needed to hold it is the smallest integer n s.t.
1791
1792 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1793 BASE**n >= B**N [taking logs to base BASE]
1794 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1795
1796The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1797this quickly. A Python long with that much space is reserved near the start,
1798and the result is computed into it.
1799
1800The input string is actually treated as being in base base**i (i.e., i digits
1801are processed at a time), where two more static arrays hold:
1802
1803 convwidth_base[base] = the largest integer i such that base**i <= BASE
1804 convmultmax_base[base] = base ** convwidth_base[base]
1805
1806The first of these is the largest i such that i consecutive input digits
1807must fit in a single Python digit. The second is effectively the input
1808base we're really using.
1809
1810Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1811convmultmax_base[base], the result is "simply"
1812
1813 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1814
1815where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001816
1817Error analysis: as above, the number of Python digits `n` needed is worst-
1818case
1819
1820 n >= N * log(B)/log(BASE)
1821
1822where `N` is the number of input digits in base `B`. This is computed via
1823
1824 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1825
1826below. Two numeric concerns are how much space this can waste, and whether
1827the computed result can be too small. To be concrete, assume BASE = 2**15,
1828which is the default (and it's unlikely anyone changes that).
1829
1830Waste isn't a problem: provided the first input digit isn't 0, the difference
1831between the worst-case input with N digits and the smallest input with N
1832digits is about a factor of B, but B is small compared to BASE so at most
1833one allocated Python digit can remain unused on that count. If
1834N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1835and adding 1 returns a result 1 larger than necessary. However, that can't
1836happen: whenever B is a power of 2, long_from_binary_base() is called
1837instead, and it's impossible for B**i to be an integer power of 2**15 when
1838B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1839an exact integer when B is not a power of 2, since B**i has a prime factor
1840other than 2 in that case, but (2**15)**j's only prime factor is 2).
1841
1842The computed result can be too small if the true value of N*log(B)/log(BASE)
1843is a little bit larger than an exact integer, but due to roundoff errors (in
1844computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1845yields a numeric result a little less than that integer. Unfortunately, "how
1846close can a transcendental function get to an integer over some range?"
1847questions are generally theoretically intractable. Computer analysis via
1848continued fractions is practical: expand log(B)/log(BASE) via continued
1849fractions, giving a sequence i/j of "the best" rational approximations. Then
1850j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1851we can get very close to being in trouble, but very rarely. For example,
185276573 is a denominator in one of the continued-fraction approximations to
1853log(10)/log(2**15), and indeed:
1854
1855 >>> log(10)/log(2**15)*76573
1856 16958.000000654003
1857
1858is very close to an integer. If we were working with IEEE single-precision,
1859rounding errors could kill us. Finding worst cases in IEEE double-precision
1860requires better-than-double-precision log() functions, and Tim didn't bother.
1861Instead the code checks to see whether the allocated space is enough as each
1862new Python digit is added, and copies the whole thing to a larger long if not.
1863This should happen extremely rarely, and in fact I don't have a test case
1864that triggers it(!). Instead the code was tested by artificially allocating
1865just 1 digit at the start, so that the copying code was exercised for every
1866digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001867***/
1868 register twodigits c; /* current input character */
1869 Py_ssize_t size_z;
1870 int i;
1871 int convwidth;
1872 twodigits convmultmax, convmult;
1873 digit *pz, *pzstop;
1874 char* scan;
1875
1876 static double log_base_BASE[37] = {0.0e0,};
1877 static int convwidth_base[37] = {0,};
1878 static twodigits convmultmax_base[37] = {0,};
1879
1880 if (log_base_BASE[base] == 0.0) {
1881 twodigits convmax = base;
1882 int i = 1;
1883
1884 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001885 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001886 for (;;) {
1887 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001888 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001889 break;
1890 convmax = next;
1891 ++i;
1892 }
1893 convmultmax_base[base] = convmax;
1894 assert(i > 0);
1895 convwidth_base[base] = i;
1896 }
1897
1898 /* Find length of the string of numeric characters. */
1899 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001900 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901 ++scan;
1902
1903 /* Create a long object that can contain the largest possible
1904 * integer with this base and length. Note that there's no
1905 * need to initialize z->ob_digit -- no slot is read up before
1906 * being stored into.
1907 */
1908 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001909 /* Uncomment next line to test exceedingly rare copy code */
1910 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911 assert(size_z > 0);
1912 z = _PyLong_New(size_z);
1913 if (z == NULL)
1914 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001915 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916
1917 /* `convwidth` consecutive input digits are treated as a single
1918 * digit in base `convmultmax`.
1919 */
1920 convwidth = convwidth_base[base];
1921 convmultmax = convmultmax_base[base];
1922
1923 /* Work ;-) */
1924 while (str < scan) {
1925 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001926 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001927 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1928 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00001929 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001930 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001931 }
1932
1933 convmult = convmultmax;
1934 /* Calculate the shift only if we couldn't get
1935 * convwidth digits.
1936 */
1937 if (i != convwidth) {
1938 convmult = base;
1939 for ( ; i > 1; --i)
1940 convmult *= base;
1941 }
1942
1943 /* Multiply z by convmult, and add c. */
1944 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001945 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001946 for (; pz < pzstop; ++pz) {
1947 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001948 *pz = (digit)(c & PyLong_MASK);
1949 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001950 }
1951 /* carry off the current end? */
1952 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001953 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001954 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001955 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001956 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001957 }
1958 else {
1959 PyLongObject *tmp;
1960 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001961 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001962 tmp = _PyLong_New(size_z + 1);
1963 if (tmp == NULL) {
1964 Py_DECREF(z);
1965 return NULL;
1966 }
1967 memcpy(tmp->ob_digit,
1968 z->ob_digit,
1969 sizeof(digit) * size_z);
1970 Py_DECREF(z);
1971 z = tmp;
1972 z->ob_digit[size_z] = (digit)c;
1973 ++size_z;
1974 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001976 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001977 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001978 if (z == NULL)
1979 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001980 if (error_if_nonzero) {
1981 /* reset the base to 0, else the exception message
1982 doesn't make too much sense */
1983 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001984 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001985 goto onError;
1986 /* there might still be other problems, therefore base
1987 remains zero here for the same reason */
1988 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001989 if (str == start)
1990 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001992 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001993 if (*str == 'L' || *str == 'l')
1994 str++;
1995 while (*str && isspace(Py_CHARMASK(*str)))
1996 str++;
1997 if (*str != '\0')
1998 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001999 if (pend)
2000 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002001 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002002 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002003
2004 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002005 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002006 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002007 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002008 if (strobj == NULL)
2009 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002010 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002011 "invalid literal for int() with base %d: %R",
2012 base, strobj);
2013 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002014 return NULL;
2015}
2016
2017PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002018PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002019{
Walter Dörwald07e14762002-11-06 16:15:14 +00002020 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002021 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002022
Walter Dörwald07e14762002-11-06 16:15:14 +00002023 if (buffer == NULL)
2024 return NULL;
2025
2026 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2027 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002028 return NULL;
2029 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002030 result = PyLong_FromString(buffer, NULL, base);
2031 PyMem_FREE(buffer);
2032 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002033}
2034
Tim Peters9f688bf2000-07-07 15:53:28 +00002035/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002037 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002038static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00002039static int long_divrem(PyLongObject *, PyLongObject *,
2040 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002041
2042/* Long division with remainder, top-level routine */
2043
Guido van Rossume32e0141992-01-19 16:31:05 +00002044static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002045long_divrem(PyLongObject *a, PyLongObject *b,
2046 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002047{
Christian Heimes90aa7642007-12-19 02:45:37 +00002048 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002049 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002050
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002051 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002052 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002053 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002054 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002055 }
2056 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002057 (size_a == size_b &&
2058 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002059 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002060 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002061 if (*pdiv == NULL)
2062 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002063 Py_INCREF(a);
2064 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002065 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002066 }
2067 if (size_b == 1) {
2068 digit rem = 0;
2069 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002070 if (z == NULL)
2071 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002072 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002073 if (*prem == NULL) {
2074 Py_DECREF(z);
2075 return -1;
2076 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002078 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002080 if (z == NULL)
2081 return -1;
2082 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002083 /* Set the signs.
2084 The quotient z has the sign of a*b;
2085 the remainder r has the sign of a,
2086 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002087 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002088 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002089 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002090 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002091 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002092 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093}
2094
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002095/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002097static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002098x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002099{
Christian Heimes90aa7642007-12-19 02:45:37 +00002100 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002101 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 PyLongObject *v = mul1(v1, d);
2103 PyLongObject *w = mul1(w1, d);
2104 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002105 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002106
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108 Py_XDECREF(v);
2109 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002110 return NULL;
2111 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002112
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002113 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002114 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2115 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002116
Christian Heimes90aa7642007-12-19 02:45:37 +00002117 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118 k = size_v - size_w;
2119 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002120
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002122 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2123 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002124 stwodigits carry = 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002125 int i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002126
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002127 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002128 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002129 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002131 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002133 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002135 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002136 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002137
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 while (w->ob_digit[size_w-2]*q >
2139 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002140 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141 + v->ob_digit[j-1]
2142 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002143 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002144 + v->ob_digit[j-2])
2145 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002146
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002147 for (i = 0; i < size_w && i+k < size_v; ++i) {
2148 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002149 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002151 + ((twodigits)zz << PyLong_SHIFT);
2152 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002153 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002154 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002155 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002156 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002157
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002158 if (i+k < size_v) {
2159 carry += v->ob_digit[i+k];
2160 v->ob_digit[i+k] = 0;
2161 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002162
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002164 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002165 else {
2166 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002167 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002168 carry = 0;
2169 for (i = 0; i < size_w && i+k < size_v; ++i) {
2170 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002171 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002172 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2173 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002174 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002175 }
2176 }
2177 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002178
Guido van Rossumc206c761995-01-10 15:23:19 +00002179 if (a == NULL)
2180 *prem = NULL;
2181 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002182 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002183 *prem = divrem1(v, d, &d);
2184 /* d receives the (unused) remainder */
2185 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002187 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002188 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 Py_DECREF(v);
2191 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002192 return a;
2193}
2194
2195/* Methods */
2196
2197static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002198long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002199{
Christian Heimes90aa7642007-12-19 02:45:37 +00002200 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002201}
2202
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002203static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002204long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002205{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002206 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002207}
2208
2209static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002210long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002211{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002212 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002213
Christian Heimes90aa7642007-12-19 02:45:37 +00002214 if (Py_SIZE(a) != Py_SIZE(b)) {
2215 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002216 sign = 0;
2217 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002218 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002219 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002221 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002222 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2223 ;
2224 if (i < 0)
2225 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002226 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002227 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002228 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002229 sign = -sign;
2230 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002232 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233}
2234
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002235#define TEST_COND(cond) \
2236 ((cond) ? Py_True : Py_False)
2237
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002238static PyObject *
2239long_richcompare(PyObject *self, PyObject *other, int op)
2240{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002241 int result;
2242 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002243 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002244 if (self == other)
2245 result = 0;
2246 else
2247 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2248 /* Convert the return value to a Boolean */
2249 switch (op) {
2250 case Py_EQ:
2251 v = TEST_COND(result == 0);
2252 break;
2253 case Py_NE:
2254 v = TEST_COND(result != 0);
2255 break;
2256 case Py_LE:
2257 v = TEST_COND(result <= 0);
2258 break;
2259 case Py_GE:
2260 v = TEST_COND(result >= 0);
2261 break;
2262 case Py_LT:
2263 v = TEST_COND(result == -1);
2264 break;
2265 case Py_GT:
2266 v = TEST_COND(result == 1);
2267 break;
2268 default:
2269 PyErr_BadArgument();
2270 return NULL;
2271 }
2272 Py_INCREF(v);
2273 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002274}
2275
Guido van Rossum9bfef441993-03-29 10:43:31 +00002276static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002277long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002278{
2279 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002280 Py_ssize_t i;
2281 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002282
2283 /* This is designed so that Python ints and longs with the
2284 same value hash to the same value, otherwise comparisons
2285 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002286 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002287 switch(i) {
2288 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2289 case 0: return 0;
2290 case 1: return v->ob_digit[0];
2291 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002292 sign = 1;
2293 x = 0;
2294 if (i < 0) {
2295 sign = -1;
2296 i = -(i);
2297 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002298#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002299 /* The following loop produces a C long x such that (unsigned long)x
2300 is congruent to the absolute value of v modulo ULONG_MAX. The
2301 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002302 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002303 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002304 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002305 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002306 /* If the addition above overflowed (thinking of x as
2307 unsigned), we compensate by incrementing. This preserves
2308 the value modulo ULONG_MAX. */
2309 if ((unsigned long)x < v->ob_digit[i])
2310 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002311 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002312#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002313 x = x * sign;
2314 if (x == -1)
2315 x = -2;
2316 return x;
2317}
2318
2319
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002320/* Add the absolute values of two long integers. */
2321
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002323x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002324{
Christian Heimes90aa7642007-12-19 02:45:37 +00002325 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002326 PyLongObject *z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002327 int i;
2328 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002329
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330 /* Ensure a is the larger of the two: */
2331 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002333 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002334 size_a = size_b;
2335 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002338 if (z == NULL)
2339 return NULL;
2340 for (i = 0; i < size_b; ++i) {
2341 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002342 z->ob_digit[i] = carry & PyLong_MASK;
2343 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002344 }
2345 for (; i < size_a; ++i) {
2346 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002347 z->ob_digit[i] = carry & PyLong_MASK;
2348 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002349 }
2350 z->ob_digit[i] = carry;
2351 return long_normalize(z);
2352}
2353
2354/* Subtract the absolute values of two integers. */
2355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002356static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002357x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002358{
Christian Heimes90aa7642007-12-19 02:45:37 +00002359 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002361 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362 int sign = 1;
2363 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002364
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002365 /* Ensure a is the larger of the two: */
2366 if (size_a < size_b) {
2367 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002368 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002369 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002370 size_a = size_b;
2371 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002372 }
2373 else if (size_a == size_b) {
2374 /* Find highest digit where a and b differ: */
2375 i = size_a;
2376 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2377 ;
2378 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002379 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002380 if (a->ob_digit[i] < b->ob_digit[i]) {
2381 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002382 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002383 }
2384 size_a = size_b = i+1;
2385 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002386 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002387 if (z == NULL)
2388 return NULL;
2389 for (i = 0; i < size_b; ++i) {
2390 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002391 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002392 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002393 z->ob_digit[i] = borrow & PyLong_MASK;
2394 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002395 borrow &= 1; /* Keep only one sign bit */
2396 }
2397 for (; i < size_a; ++i) {
2398 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002399 z->ob_digit[i] = borrow & PyLong_MASK;
2400 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002401 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002402 }
2403 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002404 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002405 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002406 return long_normalize(z);
2407}
2408
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002409static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002410long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002411{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002412 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002413
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002414 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002415
Christian Heimes90aa7642007-12-19 02:45:37 +00002416 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002417 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002418 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002419 return result;
2420 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002421 if (Py_SIZE(a) < 0) {
2422 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002423 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002424 if (z != NULL && Py_SIZE(z) != 0)
2425 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002426 }
2427 else
2428 z = x_sub(b, a);
2429 }
2430 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002431 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002432 z = x_sub(a, b);
2433 else
2434 z = x_add(a, b);
2435 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002436 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002437}
2438
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002439static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002440long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002441{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002442 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002443
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002444 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002445
Christian Heimes90aa7642007-12-19 02:45:37 +00002446 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002447 PyObject* r;
2448 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002449 return r;
2450 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002451 if (Py_SIZE(a) < 0) {
2452 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453 z = x_sub(a, b);
2454 else
2455 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002456 if (z != NULL && Py_SIZE(z) != 0)
2457 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002458 }
2459 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002460 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002461 z = x_add(a, b);
2462 else
2463 z = x_sub(a, b);
2464 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002465 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002466}
2467
Tim Peters5af4e6c2002-08-12 02:31:19 +00002468/* Grade school multiplication, ignoring the signs.
2469 * Returns the absolute value of the product, or NULL if error.
2470 */
2471static PyLongObject *
2472x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002473{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002475 Py_ssize_t size_a = ABS(Py_SIZE(a));
2476 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002477 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002478
Tim Peters5af4e6c2002-08-12 02:31:19 +00002479 z = _PyLong_New(size_a + size_b);
2480 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002481 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002482
Christian Heimes90aa7642007-12-19 02:45:37 +00002483 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002484 if (a == b) {
2485 /* Efficient squaring per HAC, Algorithm 14.16:
2486 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2487 * Gives slightly less than a 2x speedup when a == b,
2488 * via exploiting that each entry in the multiplication
2489 * pyramid appears twice (except for the size_a squares).
2490 */
2491 for (i = 0; i < size_a; ++i) {
2492 twodigits carry;
2493 twodigits f = a->ob_digit[i];
2494 digit *pz = z->ob_digit + (i << 1);
2495 digit *pa = a->ob_digit + i + 1;
2496 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002497
Tim Peters0973b992004-08-29 22:16:50 +00002498 SIGCHECK({
2499 Py_DECREF(z);
2500 return NULL;
2501 })
2502
2503 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002504 *pz++ = (digit)(carry & PyLong_MASK);
2505 carry >>= PyLong_SHIFT;
2506 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002507
2508 /* Now f is added in twice in each column of the
2509 * pyramid it appears. Same as adding f<<1 once.
2510 */
2511 f <<= 1;
2512 while (pa < paend) {
2513 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002514 *pz++ = (digit)(carry & PyLong_MASK);
2515 carry >>= PyLong_SHIFT;
2516 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002517 }
2518 if (carry) {
2519 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002520 *pz++ = (digit)(carry & PyLong_MASK);
2521 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002522 }
2523 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002524 *pz += (digit)(carry & PyLong_MASK);
2525 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002526 }
Tim Peters0973b992004-08-29 22:16:50 +00002527 }
2528 else { /* a is not the same as b -- gradeschool long mult */
2529 for (i = 0; i < size_a; ++i) {
2530 twodigits carry = 0;
2531 twodigits f = a->ob_digit[i];
2532 digit *pz = z->ob_digit + i;
2533 digit *pb = b->ob_digit;
2534 digit *pbend = b->ob_digit + size_b;
2535
2536 SIGCHECK({
2537 Py_DECREF(z);
2538 return NULL;
2539 })
2540
2541 while (pb < pbend) {
2542 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002543 *pz++ = (digit)(carry & PyLong_MASK);
2544 carry >>= PyLong_SHIFT;
2545 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002546 }
2547 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002548 *pz += (digit)(carry & PyLong_MASK);
2549 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002550 }
2551 }
Tim Peters44121a62002-08-12 06:17:58 +00002552 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002553}
2554
2555/* A helper for Karatsuba multiplication (k_mul).
2556 Takes a long "n" and an integer "size" representing the place to
2557 split, and sets low and high such that abs(n) == (high << size) + low,
2558 viewing the shift as being by digits. The sign bit is ignored, and
2559 the return values are >= 0.
2560 Returns 0 on success, -1 on failure.
2561*/
2562static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002563kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002564{
2565 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002566 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002567 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002568
2569 size_lo = MIN(size_n, size);
2570 size_hi = size_n - size_lo;
2571
2572 if ((hi = _PyLong_New(size_hi)) == NULL)
2573 return -1;
2574 if ((lo = _PyLong_New(size_lo)) == NULL) {
2575 Py_DECREF(hi);
2576 return -1;
2577 }
2578
2579 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2580 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2581
2582 *high = long_normalize(hi);
2583 *low = long_normalize(lo);
2584 return 0;
2585}
2586
Tim Peters60004642002-08-12 22:01:34 +00002587static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2588
Tim Peters5af4e6c2002-08-12 02:31:19 +00002589/* Karatsuba multiplication. Ignores the input signs, and returns the
2590 * absolute value of the product (or NULL if error).
2591 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2592 */
2593static PyLongObject *
2594k_mul(PyLongObject *a, PyLongObject *b)
2595{
Christian Heimes90aa7642007-12-19 02:45:37 +00002596 Py_ssize_t asize = ABS(Py_SIZE(a));
2597 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002598 PyLongObject *ah = NULL;
2599 PyLongObject *al = NULL;
2600 PyLongObject *bh = NULL;
2601 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002602 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002603 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002604 Py_ssize_t shift; /* the number of digits we split off */
2605 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002606
Tim Peters5af4e6c2002-08-12 02:31:19 +00002607 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2608 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2609 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002610 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002611 * By picking X to be a power of 2, "*X" is just shifting, and it's
2612 * been reduced to 3 multiplies on numbers half the size.
2613 */
2614
Tim Petersfc07e562002-08-12 02:54:10 +00002615 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002616 * is largest.
2617 */
Tim Peters738eda72002-08-12 15:08:20 +00002618 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002619 t1 = a;
2620 a = b;
2621 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002622
2623 i = asize;
2624 asize = bsize;
2625 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002626 }
2627
2628 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002629 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2630 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002631 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002632 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002633 else
2634 return x_mul(a, b);
2635 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002636
Tim Peters60004642002-08-12 22:01:34 +00002637 /* If a is small compared to b, splitting on b gives a degenerate
2638 * case with ah==0, and Karatsuba may be (even much) less efficient
2639 * than "grade school" then. However, we can still win, by viewing
2640 * b as a string of "big digits", each of width a->ob_size. That
2641 * leads to a sequence of balanced calls to k_mul.
2642 */
2643 if (2 * asize <= bsize)
2644 return k_lopsided_mul(a, b);
2645
Tim Petersd6974a52002-08-13 20:37:51 +00002646 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002647 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002649 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002650
Tim Peters0973b992004-08-29 22:16:50 +00002651 if (a == b) {
2652 bh = ah;
2653 bl = al;
2654 Py_INCREF(bh);
2655 Py_INCREF(bl);
2656 }
2657 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002658
Tim Petersd64c1de2002-08-12 17:36:03 +00002659 /* The plan:
2660 * 1. Allocate result space (asize + bsize digits: that's always
2661 * enough).
2662 * 2. Compute ah*bh, and copy into result at 2*shift.
2663 * 3. Compute al*bl, and copy into result at 0. Note that this
2664 * can't overlap with #2.
2665 * 4. Subtract al*bl from the result, starting at shift. This may
2666 * underflow (borrow out of the high digit), but we don't care:
2667 * we're effectively doing unsigned arithmetic mod
2668 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2669 * borrows and carries out of the high digit can be ignored.
2670 * 5. Subtract ah*bh from the result, starting at shift.
2671 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2672 * at shift.
2673 */
2674
2675 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002676 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002677 if (ret == NULL) goto fail;
2678#ifdef Py_DEBUG
2679 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002680 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002681#endif
Tim Peters44121a62002-08-12 06:17:58 +00002682
Tim Petersd64c1de2002-08-12 17:36:03 +00002683 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002684 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002685 assert(Py_SIZE(t1) >= 0);
2686 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002687 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002688 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002689
2690 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002691 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002692 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002693 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002694 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002695
Tim Petersd64c1de2002-08-12 17:36:03 +00002696 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002697 if ((t2 = k_mul(al, bl)) == NULL) {
2698 Py_DECREF(t1);
2699 goto fail;
2700 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002701 assert(Py_SIZE(t2) >= 0);
2702 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2703 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002704
2705 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002706 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002707 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002708 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002709
Tim Petersd64c1de2002-08-12 17:36:03 +00002710 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2711 * because it's fresher in cache.
2712 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002713 i = Py_SIZE(ret) - shift; /* # digits after shift */
2714 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002715 Py_DECREF(t2);
2716
Christian Heimes90aa7642007-12-19 02:45:37 +00002717 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002718 Py_DECREF(t1);
2719
Tim Petersd64c1de2002-08-12 17:36:03 +00002720 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002721 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2722 Py_DECREF(ah);
2723 Py_DECREF(al);
2724 ah = al = NULL;
2725
Tim Peters0973b992004-08-29 22:16:50 +00002726 if (a == b) {
2727 t2 = t1;
2728 Py_INCREF(t2);
2729 }
2730 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002731 Py_DECREF(t1);
2732 goto fail;
2733 }
2734 Py_DECREF(bh);
2735 Py_DECREF(bl);
2736 bh = bl = NULL;
2737
Tim Peters738eda72002-08-12 15:08:20 +00002738 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002739 Py_DECREF(t1);
2740 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002741 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002742 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002743
Tim Petersd6974a52002-08-13 20:37:51 +00002744 /* Add t3. It's not obvious why we can't run out of room here.
2745 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002746 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002747 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002748 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002749
Tim Peters5af4e6c2002-08-12 02:31:19 +00002750 return long_normalize(ret);
2751
2752 fail:
2753 Py_XDECREF(ret);
2754 Py_XDECREF(ah);
2755 Py_XDECREF(al);
2756 Py_XDECREF(bh);
2757 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002758 return NULL;
2759}
2760
Tim Petersd6974a52002-08-13 20:37:51 +00002761/* (*) Why adding t3 can't "run out of room" above.
2762
Tim Petersab86c2b2002-08-15 20:06:00 +00002763Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2764to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002765
Tim Petersab86c2b2002-08-15 20:06:00 +000027661. For any integer i, i = c(i/2) + f(i/2). In particular,
2767 bsize = c(bsize/2) + f(bsize/2).
27682. shift = f(bsize/2)
27693. asize <= bsize
27704. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2771 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002772
Tim Petersab86c2b2002-08-15 20:06:00 +00002773We allocated asize + bsize result digits, and add t3 into them at an offset
2774of shift. This leaves asize+bsize-shift allocated digit positions for t3
2775to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2776asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002777
Tim Petersab86c2b2002-08-15 20:06:00 +00002778bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2779at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002780
Tim Petersab86c2b2002-08-15 20:06:00 +00002781If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2782digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2783most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002784
Tim Petersab86c2b2002-08-15 20:06:00 +00002785The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002786
Tim Petersab86c2b2002-08-15 20:06:00 +00002787 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002788
Tim Petersab86c2b2002-08-15 20:06:00 +00002789and we have asize + c(bsize/2) available digit positions. We need to show
2790this is always enough. An instance of c(bsize/2) cancels out in both, so
2791the question reduces to whether asize digits is enough to hold
2792(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2793then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2794asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002795digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002796asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002797c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2798is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2799bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002800
Tim Peters48d52c02002-08-14 17:07:32 +00002801Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2802clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2803ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002804*/
2805
Tim Peters60004642002-08-12 22:01:34 +00002806/* b has at least twice the digits of a, and a is big enough that Karatsuba
2807 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2808 * of slices, each with a->ob_size digits, and multiply the slices by a,
2809 * one at a time. This gives k_mul balanced inputs to work with, and is
2810 * also cache-friendly (we compute one double-width slice of the result
2811 * at a time, then move on, never bactracking except for the helpful
2812 * single-width slice overlap between successive partial sums).
2813 */
2814static PyLongObject *
2815k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2816{
Christian Heimes90aa7642007-12-19 02:45:37 +00002817 const Py_ssize_t asize = ABS(Py_SIZE(a));
2818 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002819 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002820 PyLongObject *ret;
2821 PyLongObject *bslice = NULL;
2822
2823 assert(asize > KARATSUBA_CUTOFF);
2824 assert(2 * asize <= bsize);
2825
2826 /* Allocate result space, and zero it out. */
2827 ret = _PyLong_New(asize + bsize);
2828 if (ret == NULL)
2829 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002830 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002831
2832 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002833 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002834 if (bslice == NULL)
2835 goto fail;
2836
2837 nbdone = 0;
2838 while (bsize > 0) {
2839 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002840 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002841
2842 /* Multiply the next slice of b by a. */
2843 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2844 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002845 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002846 product = k_mul(a, bslice);
2847 if (product == NULL)
2848 goto fail;
2849
2850 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002851 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2852 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002853 Py_DECREF(product);
2854
2855 bsize -= nbtouse;
2856 nbdone += nbtouse;
2857 }
2858
2859 Py_DECREF(bslice);
2860 return long_normalize(ret);
2861
2862 fail:
2863 Py_DECREF(ret);
2864 Py_XDECREF(bslice);
2865 return NULL;
2866}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002867
2868static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002869long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002870{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002871 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002872
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002873 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002874
Christian Heimes90aa7642007-12-19 02:45:37 +00002875 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002876 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002877 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002878 return r;
2879 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002880
Tim Petersd64c1de2002-08-12 17:36:03 +00002881 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002882 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002883 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002884 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002885 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002886}
2887
Guido van Rossume32e0141992-01-19 16:31:05 +00002888/* The / and % operators are now defined in terms of divmod().
2889 The expression a mod b has the value a - b*floor(a/b).
2890 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002891 |a| by |b|, with the sign of a. This is also expressed
2892 as a - b*trunc(a/b), if trunc truncates towards zero.
2893 Some examples:
2894 a b a rem b a mod b
2895 13 10 3 3
2896 -13 10 -3 7
2897 13 -10 3 -7
2898 -13 -10 -3 -3
2899 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002900 have different signs. We then subtract one from the 'div'
2901 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002902
Tim Peters47e52ee2004-08-30 02:44:38 +00002903/* Compute
2904 * *pdiv, *pmod = divmod(v, w)
2905 * NULL can be passed for pdiv or pmod, in which case that part of
2906 * the result is simply thrown away. The caller owns a reference to
2907 * each of these it requests (does not pass NULL for).
2908 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002909static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002910l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002911 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002912{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002913 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002914
Guido van Rossume32e0141992-01-19 16:31:05 +00002915 if (long_divrem(v, w, &div, &mod) < 0)
2916 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002917 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2918 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002919 PyLongObject *temp;
2920 PyLongObject *one;
2921 temp = (PyLongObject *) long_add(mod, w);
2922 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002923 mod = temp;
2924 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002925 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002926 return -1;
2927 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002929 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002930 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2931 Py_DECREF(mod);
2932 Py_DECREF(div);
2933 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002934 return -1;
2935 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002936 Py_DECREF(one);
2937 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002938 div = temp;
2939 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002940 if (pdiv != NULL)
2941 *pdiv = div;
2942 else
2943 Py_DECREF(div);
2944
2945 if (pmod != NULL)
2946 *pmod = mod;
2947 else
2948 Py_DECREF(mod);
2949
Guido van Rossume32e0141992-01-19 16:31:05 +00002950 return 0;
2951}
2952
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002953static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002954long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002955{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002956 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002957
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002958 CHECK_BINOP(a, b);
2959 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002960 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002961 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002962}
2963
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002964static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002965long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002966{
Tim Peterse2a60002001-09-04 06:17:36 +00002967 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002968 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002969
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002970 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002971 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2972 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002973 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002974 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002975 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002976 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2977 but should really be set correctly after sucessful calls to
2978 _PyLong_AsScaledDouble() */
2979 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002980
2981 if (bd == 0.0) {
2982 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002983 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002984 return NULL;
2985 }
2986
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002987 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002988 ad /= bd; /* overflow/underflow impossible here */
2989 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002990 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002991 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002992 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002993 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002994 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002995 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002996 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002997 goto overflow;
2998 return PyFloat_FromDouble(ad);
2999
3000overflow:
3001 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003002 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003003 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003004
Tim Peters20dab9f2001-09-04 05:31:47 +00003005}
3006
3007static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003008long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003009{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003010 PyLongObject *mod;
3011
3012 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003013
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003014 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003015 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003016 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003017}
3018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003019static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003020long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003021{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003022 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003023 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003024
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003025 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003026
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003027 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003028 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003029 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003030 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003031 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003032 PyTuple_SetItem(z, 0, (PyObject *) div);
3033 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003034 }
3035 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003036 Py_DECREF(div);
3037 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003038 }
3039 return z;
3040}
3041
Tim Peters47e52ee2004-08-30 02:44:38 +00003042/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003043static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003044long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003045{
Tim Peters47e52ee2004-08-30 02:44:38 +00003046 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3047 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003048
Tim Peters47e52ee2004-08-30 02:44:38 +00003049 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003050 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003051 PyLongObject *temp = NULL;
3052
3053 /* 5-ary values. If the exponent is large enough, table is
3054 * precomputed so that table[i] == a**i % c for i in range(32).
3055 */
3056 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3057 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3058
3059 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003060 CHECK_BINOP(v, w);
3061 a = (PyLongObject*)v; Py_INCREF(a);
3062 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003063 if (PyLong_Check(x)) {
3064 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003065 Py_INCREF(x);
3066 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003067 else if (x == Py_None)
3068 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003069 else {
3070 Py_DECREF(a);
3071 Py_DECREF(b);
3072 Py_INCREF(Py_NotImplemented);
3073 return Py_NotImplemented;
3074 }
Tim Peters4c483c42001-09-05 06:24:58 +00003075
Christian Heimes90aa7642007-12-19 02:45:37 +00003076 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003077 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003078 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003079 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003080 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003081 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003082 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003083 /* else return a float. This works because we know
3084 that this calls float_pow() which converts its
3085 arguments to double. */
3086 Py_DECREF(a);
3087 Py_DECREF(b);
3088 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003089 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003090 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003091
3092 if (c) {
3093 /* if modulus == 0:
3094 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003095 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003096 PyErr_SetString(PyExc_ValueError,
3097 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003098 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003099 }
3100
3101 /* if modulus < 0:
3102 negativeOutput = True
3103 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003104 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003105 negativeOutput = 1;
3106 temp = (PyLongObject *)_PyLong_Copy(c);
3107 if (temp == NULL)
3108 goto Error;
3109 Py_DECREF(c);
3110 c = temp;
3111 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003112 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003113 }
3114
3115 /* if modulus == 1:
3116 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003117 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003118 z = (PyLongObject *)PyLong_FromLong(0L);
3119 goto Done;
3120 }
3121
3122 /* if base < 0:
3123 base = base % modulus
3124 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003125 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003126 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003127 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003128 Py_DECREF(a);
3129 a = temp;
3130 temp = NULL;
3131 }
3132 }
3133
3134 /* At this point a, b, and c are guaranteed non-negative UNLESS
3135 c is NULL, in which case a may be negative. */
3136
3137 z = (PyLongObject *)PyLong_FromLong(1L);
3138 if (z == NULL)
3139 goto Error;
3140
3141 /* Perform a modular reduction, X = X % c, but leave X alone if c
3142 * is NULL.
3143 */
3144#define REDUCE(X) \
3145 if (c != NULL) { \
3146 if (l_divmod(X, c, NULL, &temp) < 0) \
3147 goto Error; \
3148 Py_XDECREF(X); \
3149 X = temp; \
3150 temp = NULL; \
3151 }
3152
3153 /* Multiply two values, then reduce the result:
3154 result = X*Y % c. If c is NULL, skip the mod. */
3155#define MULT(X, Y, result) \
3156{ \
3157 temp = (PyLongObject *)long_mul(X, Y); \
3158 if (temp == NULL) \
3159 goto Error; \
3160 Py_XDECREF(result); \
3161 result = temp; \
3162 temp = NULL; \
3163 REDUCE(result) \
3164}
3165
Christian Heimes90aa7642007-12-19 02:45:37 +00003166 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003167 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3168 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003169 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003170 digit bi = b->ob_digit[i];
3171
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003172 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003173 MULT(z, z, z)
3174 if (bi & j)
3175 MULT(z, a, z)
3176 }
3177 }
3178 }
3179 else {
3180 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3181 Py_INCREF(z); /* still holds 1L */
3182 table[0] = z;
3183 for (i = 1; i < 32; ++i)
3184 MULT(table[i-1], a, table[i])
3185
Christian Heimes90aa7642007-12-19 02:45:37 +00003186 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003187 const digit bi = b->ob_digit[i];
3188
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003189 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003190 const int index = (bi >> j) & 0x1f;
3191 for (k = 0; k < 5; ++k)
3192 MULT(z, z, z)
3193 if (index)
3194 MULT(z, table[index], z)
3195 }
3196 }
3197 }
3198
Christian Heimes90aa7642007-12-19 02:45:37 +00003199 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003200 temp = (PyLongObject *)long_sub(z, c);
3201 if (temp == NULL)
3202 goto Error;
3203 Py_DECREF(z);
3204 z = temp;
3205 temp = NULL;
3206 }
3207 goto Done;
3208
3209 Error:
3210 if (z != NULL) {
3211 Py_DECREF(z);
3212 z = NULL;
3213 }
3214 /* fall through */
3215 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003216 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003217 for (i = 0; i < 32; ++i)
3218 Py_XDECREF(table[i]);
3219 }
Tim Petersde7990b2005-07-17 23:45:23 +00003220 Py_DECREF(a);
3221 Py_DECREF(b);
3222 Py_XDECREF(c);
3223 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003224 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003225}
3226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003227static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003228long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003229{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003230 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003231 PyLongObject *x;
3232 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003233 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003234 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003235 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003236 if (w == NULL)
3237 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003238 x = (PyLongObject *) long_add(v, w);
3239 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003240 if (x == NULL)
3241 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003242 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003243 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003244}
3245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003246static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003247long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003248{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003249 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003250 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003251 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003252 z = (PyLongObject *)_PyLong_Copy(v);
3253 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003254 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003255 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003256}
3257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003258static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003259long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003260{
Christian Heimes90aa7642007-12-19 02:45:37 +00003261 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003262 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003263 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003264 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003265}
3266
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003267static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003268long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003269{
Christian Heimes90aa7642007-12-19 02:45:37 +00003270 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003271}
3272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003273static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003274long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003275{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003276 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003277 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003278 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003279 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003280
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003281 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003282
Christian Heimes90aa7642007-12-19 02:45:37 +00003283 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003284 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003285 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003286 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003287 if (a1 == NULL)
3288 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003289 a2 = (PyLongObject *) long_rshift(a1, b);
3290 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003291 if (a2 == NULL)
3292 goto rshift_error;
3293 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003294 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003295 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003297
Neil Schemenauerba872e22001-01-04 01:46:03 +00003298 shiftby = PyLong_AsLong((PyObject *)b);
3299 if (shiftby == -1L && PyErr_Occurred())
3300 goto rshift_error;
3301 if (shiftby < 0) {
3302 PyErr_SetString(PyExc_ValueError,
3303 "negative shift count");
3304 goto rshift_error;
3305 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003306 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003307 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003308 if (newsize <= 0)
3309 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003310 loshift = shiftby % PyLong_SHIFT;
3311 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003312 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003313 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003314 z = _PyLong_New(newsize);
3315 if (z == NULL)
3316 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003317 if (Py_SIZE(a) < 0)
3318 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003319 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3320 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3321 if (i+1 < newsize)
3322 z->ob_digit[i] |=
3323 (a->ob_digit[j+1] << hishift) & himask;
3324 }
3325 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003326 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003327rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003328 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003329
Guido van Rossumc6913e71991-11-19 20:26:46 +00003330}
3331
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003332static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003333long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003334{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003335 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003336 PyLongObject *a = (PyLongObject*)v;
3337 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003338 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003339 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003340 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003341 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003342
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003343 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003344
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003345 shiftby = PyLong_AsLong((PyObject *)b);
3346 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003347 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003348 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003349 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003350 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003351 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003352 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003353 PyErr_SetString(PyExc_ValueError,
3354 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003355 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003356 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003357 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3358 wordshift = (int)shiftby / PyLong_SHIFT;
3359 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003360
Christian Heimes90aa7642007-12-19 02:45:37 +00003361 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003362 newsize = oldsize + wordshift;
3363 if (remshift)
3364 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003365 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003366 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003367 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003368 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003369 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003370 for (i = 0; i < wordshift; i++)
3371 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003372 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003373 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003374 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003375 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3376 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003377 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003378 if (remshift)
3379 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003380 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003381 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003382 z = long_normalize(z);
3383lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003384 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003385}
3386
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003387
3388/* Bitwise and/xor/or operations */
3389
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003390static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003391long_bitwise(PyLongObject *a,
3392 int op, /* '&', '|', '^' */
3393 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003394{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003395 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003396 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003397 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003398 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003399 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003400 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003401 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003402
Christian Heimes90aa7642007-12-19 02:45:37 +00003403 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003404 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003405 if (a == NULL)
3406 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003407 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003408 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003409 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003410 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003411 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003412 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003413 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003414 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003415 if (b == NULL) {
3416 Py_DECREF(a);
3417 return NULL;
3418 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003419 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003420 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003421 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003422 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003423 maskb = 0;
3424 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003425
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003426 negz = 0;
3427 switch (op) {
3428 case '^':
3429 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003430 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003431 negz = -1;
3432 }
3433 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003434 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003435 if (maska && maskb) {
3436 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003437 maska ^= PyLong_MASK;
3438 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003439 negz = -1;
3440 }
3441 break;
3442 case '|':
3443 if (maska || maskb) {
3444 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003445 maska ^= PyLong_MASK;
3446 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003447 negz = -1;
3448 }
3449 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003450 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003451
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003452 /* JRH: The original logic here was to allocate the result value (z)
3453 as the longer of the two operands. However, there are some cases
3454 where the result is guaranteed to be shorter than that: AND of two
3455 positives, OR of two negatives: use the shorter number. AND with
3456 mixed signs: use the positive number. OR with mixed signs: use the
3457 negative number. After the transformations above, op will be '&'
3458 iff one of these cases applies, and mask will be non-0 for operands
3459 whose length should be ignored.
3460 */
3461
Christian Heimes90aa7642007-12-19 02:45:37 +00003462 size_a = Py_SIZE(a);
3463 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003464 size_z = op == '&'
3465 ? (maska
3466 ? size_b
3467 : (maskb ? size_a : MIN(size_a, size_b)))
3468 : MAX(size_a, size_b);
3469 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003470 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003471 Py_DECREF(a);
3472 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003473 return NULL;
3474 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003475
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003476 for (i = 0; i < size_z; ++i) {
3477 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3478 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3479 switch (op) {
3480 case '&': z->ob_digit[i] = diga & digb; break;
3481 case '|': z->ob_digit[i] = diga | digb; break;
3482 case '^': z->ob_digit[i] = diga ^ digb; break;
3483 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003484 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003485
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003486 Py_DECREF(a);
3487 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003488 z = long_normalize(z);
3489 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003490 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003491 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003492 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003493 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003494}
3495
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003496static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003497long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003498{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003499 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003500 CHECK_BINOP(a, b);
3501 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003502 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003503}
3504
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003505static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003506long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003507{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003508 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003509 CHECK_BINOP(a, b);
3510 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003511 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003512}
3513
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003514static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003515long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003516{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003517 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003518 CHECK_BINOP(a, b);
3519 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003520 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003521}
3522
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003523static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003524long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003525{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003526 if (PyLong_CheckExact(v))
3527 Py_INCREF(v);
3528 else
3529 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003530 return v;
3531}
3532
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003533static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003534long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003535{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003536 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003537 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003538 if (result == -1.0 && PyErr_Occurred())
3539 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003540 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003541}
3542
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003543static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003544long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003545
Tim Peters6d6c1a32001-08-02 04:15:00 +00003546static PyObject *
3547long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3548{
3549 PyObject *x = NULL;
3550 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003551 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003552
Guido van Rossumbef14172001-08-29 15:47:46 +00003553 if (type != &PyLong_Type)
3554 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003555 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003556 &x, &base))
3557 return NULL;
3558 if (x == NULL)
3559 return PyLong_FromLong(0L);
3560 if (base == -909)
3561 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003562 else if (PyUnicode_Check(x))
3563 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3564 PyUnicode_GET_SIZE(x),
3565 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003566 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003567 /* Since PyLong_FromString doesn't have a length parameter,
3568 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003569 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003570 int size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003571 if (PyByteArray_Check(x))
3572 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003573 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003574 string = PyBytes_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003575 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003576 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003577 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003578 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003579 "invalid literal for int() with base %d: %R",
3580 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003581 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003582 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003583 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003584 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003585 else {
3586 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003587 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003588 return NULL;
3589 }
3590}
3591
Guido van Rossumbef14172001-08-29 15:47:46 +00003592/* Wimpy, slow approach to tp_new calls for subtypes of long:
3593 first create a regular long from whatever arguments we got,
3594 then allocate a subtype instance and initialize it from
3595 the regular long. The regular long is then thrown away.
3596*/
3597static PyObject *
3598long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3599{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003600 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003601 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003602
3603 assert(PyType_IsSubtype(type, &PyLong_Type));
3604 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3605 if (tmp == NULL)
3606 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003607 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003608 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003609 if (n < 0)
3610 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003611 newobj = (PyLongObject *)type->tp_alloc(type, n);
3612 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003613 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003614 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003615 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003616 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003617 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003618 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003619 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003620 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003621 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003622}
3623
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003624static PyObject *
3625long_getnewargs(PyLongObject *v)
3626{
3627 return Py_BuildValue("(N)", _PyLong_Copy(v));
3628}
3629
Guido van Rossumb43daf72007-08-01 18:08:08 +00003630static PyObject *
3631long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003632 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003633}
3634
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003635static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003636long__format__(PyObject *self, PyObject *args)
3637{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003638 PyObject *format_spec;
3639
3640 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3641 return NULL;
3642 return _PyLong_FormatAdvanced(self,
3643 PyUnicode_AS_UNICODE(format_spec),
3644 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003645}
3646
3647
3648static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003649long_round(PyObject *self, PyObject *args)
3650{
3651#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3652 int ndigits = UNDEF_NDIGITS;
3653 double x;
3654 PyObject *res;
3655
3656 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3657 return NULL;
3658
3659 if (ndigits == UNDEF_NDIGITS)
3660 return long_long(self);
3661
3662 /* If called with two args, defer to float.__round__(). */
3663 x = PyLong_AsDouble(self);
3664 if (x == -1.0 && PyErr_Occurred())
3665 return NULL;
3666 self = PyFloat_FromDouble(x);
3667 if (self == NULL)
3668 return NULL;
3669 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3670 Py_DECREF(self);
3671 return res;
3672#undef UNDEF_NDIGITS
3673}
3674
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003675static PyObject *
3676long_sizeof(PyLongObject *v)
3677{
3678 Py_ssize_t res;
3679
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003680 res = sizeof(PyVarObject) + abs(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003681 return PyLong_FromSsize_t(res);
3682}
3683
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003684static const unsigned char BitLengthTable[32] = {
3685 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3686 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3687};
3688
3689static PyObject *
3690long_bit_length(PyLongObject *v)
3691{
3692 PyLongObject *result, *x, *y;
3693 Py_ssize_t ndigits, msd_bits = 0;
3694 digit msd;
3695
3696 assert(v != NULL);
3697 assert(PyLong_Check(v));
3698
3699 ndigits = ABS(Py_SIZE(v));
3700 if (ndigits == 0)
3701 return PyLong_FromLong(0);
3702
3703 msd = v->ob_digit[ndigits-1];
3704 while (msd >= 32) {
3705 msd_bits += 6;
3706 msd >>= 6;
3707 }
3708 msd_bits += (long)(BitLengthTable[msd]);
3709
3710 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3711 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3712
3713 /* expression above may overflow; use Python integers instead */
3714 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3715 if (result == NULL)
3716 return NULL;
3717 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3718 if (x == NULL)
3719 goto error;
3720 y = (PyLongObject *)long_mul(result, x);
3721 Py_DECREF(x);
3722 if (y == NULL)
3723 goto error;
3724 Py_DECREF(result);
3725 result = y;
3726
3727 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3728 if (x == NULL)
3729 goto error;
3730 y = (PyLongObject *)long_add(result, x);
3731 Py_DECREF(x);
3732 if (y == NULL)
3733 goto error;
3734 Py_DECREF(result);
3735 result = y;
3736
3737 return (PyObject *)result;
3738
3739error:
3740 Py_DECREF(result);
3741 return NULL;
3742}
3743
3744PyDoc_STRVAR(long_bit_length_doc,
3745"int.bit_length() -> int\n\
3746\n\
3747Number of bits necessary to represent self in binary.\n\
3748>>> bin(37)\n\
3749'0b100101'\n\
3750>>> (37).bit_length()\n\
37516");
3752
Christian Heimes53876d92008-04-19 00:31:39 +00003753#if 0
3754static PyObject *
3755long_is_finite(PyObject *v)
3756{
3757 Py_RETURN_TRUE;
3758}
3759#endif
3760
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003761static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003762 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3763 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003764 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3765 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003766#if 0
3767 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3768 "Returns always True."},
3769#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003770 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3771 "Truncating an Integral returns itself."},
3772 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3773 "Flooring an Integral returns itself."},
3774 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3775 "Ceiling of an Integral returns itself."},
3776 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3777 "Rounding an Integral returns itself.\n"
3778 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003779 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003780 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003781 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3782 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003783 {NULL, NULL} /* sentinel */
3784};
3785
Guido van Rossumb43daf72007-08-01 18:08:08 +00003786static PyGetSetDef long_getset[] = {
3787 {"real",
3788 (getter)long_long, (setter)NULL,
3789 "the real part of a complex number",
3790 NULL},
3791 {"imag",
3792 (getter)long_getN, (setter)NULL,
3793 "the imaginary part of a complex number",
3794 (void*)0},
3795 {"numerator",
3796 (getter)long_long, (setter)NULL,
3797 "the numerator of a rational number in lowest terms",
3798 NULL},
3799 {"denominator",
3800 (getter)long_getN, (setter)NULL,
3801 "the denominator of a rational number in lowest terms",
3802 (void*)1},
3803 {NULL} /* Sentinel */
3804};
3805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003806PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003807"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003809Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003810point argument will be truncated towards zero (this does not include a\n\
3811string representation of a floating point number!) When converting a\n\
3812string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003813converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003814
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003815static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003816 (binaryfunc) long_add, /*nb_add*/
3817 (binaryfunc) long_sub, /*nb_subtract*/
3818 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003819 long_mod, /*nb_remainder*/
3820 long_divmod, /*nb_divmod*/
3821 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003822 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003823 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003824 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003825 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003826 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003827 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003828 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003829 long_and, /*nb_and*/
3830 long_xor, /*nb_xor*/
3831 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003832 long_long, /*nb_int*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003833 long_long, /*nb_long*/
3834 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003835 0, /* nb_inplace_add */
3836 0, /* nb_inplace_subtract */
3837 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003838 0, /* nb_inplace_remainder */
3839 0, /* nb_inplace_power */
3840 0, /* nb_inplace_lshift */
3841 0, /* nb_inplace_rshift */
3842 0, /* nb_inplace_and */
3843 0, /* nb_inplace_xor */
3844 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003845 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003846 long_true_divide, /* nb_true_divide */
3847 0, /* nb_inplace_floor_divide */
3848 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003849 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003850};
3851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003852PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003853 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003854 "int", /* tp_name */
3855 /* See _PyLong_New for why this isn't
3856 sizeof(PyLongObject) - sizeof(digit) */
3857 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003859 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003860 0, /* tp_print */
3861 0, /* tp_getattr */
3862 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003863 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003864 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003865 &long_as_number, /* tp_as_number */
3866 0, /* tp_as_sequence */
3867 0, /* tp_as_mapping */
3868 (hashfunc)long_hash, /* tp_hash */
3869 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003870 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003871 PyObject_GenericGetAttr, /* tp_getattro */
3872 0, /* tp_setattro */
3873 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003874 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3875 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003876 long_doc, /* tp_doc */
3877 0, /* tp_traverse */
3878 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003879 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003880 0, /* tp_weaklistoffset */
3881 0, /* tp_iter */
3882 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003883 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003885 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003886 0, /* tp_base */
3887 0, /* tp_dict */
3888 0, /* tp_descr_get */
3889 0, /* tp_descr_set */
3890 0, /* tp_dictoffset */
3891 0, /* tp_init */
3892 0, /* tp_alloc */
3893 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003894 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003895};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003896
3897int
3898_PyLong_Init(void)
3899{
3900#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003901 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003902 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003903
3904 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
3905 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
3906 if (Py_TYPE(v) == &PyLong_Type) {
3907 /* The element is already initialized, most likely
3908 * the Python interpreter was initialized before.
3909 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00003910 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003911 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003912
Christian Heimes48aa4b12008-02-01 16:56:30 +00003913 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
3914 _Py_NewReference(op);
3915 /* _Py_NewReference sets the ref count to 1 but
3916 * the ref count might be larger. Set the refcnt
3917 * to the original refcnt + 1 */
3918 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003919 assert(Py_SIZE(op) == size);
3920 assert(v->ob_digit[0] == abs(ival));
3921 }
3922 else {
3923 PyObject_INIT(v, &PyLong_Type);
3924 }
3925 Py_SIZE(v) = size;
3926 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003927 }
3928#endif
3929 return 1;
3930}
3931
3932void
3933PyLong_Fini(void)
3934{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003935 /* Integers are currently statically allocated. Py_DECREF is not
3936 needed, but Python must forget about the reference or multiple
3937 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003938#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003939 int i;
3940 PyLongObject *v = small_ints;
3941 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
3942 _Py_DEC_REFTOTAL;
3943 _Py_ForgetReference((PyObject*)v);
3944 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003945#endif
3946}