blob: 0493dbc3e717d938e71d507910fd80f9183dea2e [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;
Mark Dickinsond4624c32009-01-24 15:02:35 +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) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000186 /* negate: can't write this as abs_ival = -ival since that
187 invokes undefined behaviour when ival is LONG_MIN */
188 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000189 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000190 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000191 else {
192 abs_ival = (unsigned long)ival;
193 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000194
Mark Dickinsond4624c32009-01-24 15:02:35 +0000195 /* Fast path for single-digit ints */
196 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000197 v = _PyLong_New(1);
198 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000199 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000200 v->ob_digit[0] = Py_SAFE_DOWNCAST(
201 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000202 }
203 return (PyObject*)v;
204 }
205
206 /* 2 digits */
Mark Dickinsond4624c32009-01-24 15:02:35 +0000207 if (!(abs_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;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000215 }
216 return (PyObject*)v;
217 }
218
219 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000220 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000221 while (t) {
222 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000223 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000224 }
225 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000226 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000227 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000228 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000229 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000230 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000231 *p++ = Py_SAFE_DOWNCAST(
232 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000233 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000234 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000235 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000236 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000237}
238
Guido van Rossum53756b11997-01-03 17:14:46 +0000239/* Create a new long int object from a C unsigned long int */
240
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000241PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000242PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000243{
Tim Petersce9de2f2001-06-14 04:56:19 +0000244 PyLongObject *v;
245 unsigned long t;
246 int ndigits = 0;
247
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000248 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000249 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000250 /* Count the number of Python digits. */
251 t = (unsigned long)ival;
252 while (t) {
253 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000254 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000255 }
256 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000257 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000258 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000259 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000260 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000261 *p++ = (digit)(ival & PyLong_MASK);
262 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000263 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000264 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000265 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000266}
267
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000268/* Create a new long int object from a C double */
269
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000270PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274 double frac;
275 int i, ndig, expo, neg;
276 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000277 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000278 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000279 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000280 return NULL;
281 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000282 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000283 PyErr_SetString(PyExc_ValueError,
284 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000285 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000286 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000287 if (dval < 0.0) {
288 neg = 1;
289 dval = -dval;
290 }
291 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
292 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000293 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000294 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000296 if (v == NULL)
297 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000298 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000299 for (i = ndig; --i >= 0; ) {
300 long bits = (long)frac;
Guido van Rossum2095d241997-04-09 19:41:24 +0000301 v->ob_digit[i] = (digit) bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000302 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000303 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304 }
305 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000306 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000307 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000308}
309
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
311 * anything about what happens when a signed integer operation overflows,
312 * and some compilers think they're doing you a favor by being "clever"
313 * then. The bit pattern for the largest postive signed long is
314 * (unsigned long)LONG_MAX, and for the smallest negative signed long
315 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
316 * However, some other compilers warn about applying unary minus to an
317 * unsigned operand. Hence the weird "0-".
318 */
319#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
320#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
321
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000322/* Get a C long int from a long int object.
323 Returns -1 and sets an error condition if overflow occurs. */
324
325long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000326PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000327{
Guido van Rossumf7531811998-05-26 14:33:37 +0000328 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000330 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000331 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000332 Py_ssize_t i;
333 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000334 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000335
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000336 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000337 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000338 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000339 return -1;
340 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000341
342 if (!PyLong_Check(vv)) {
343 PyNumberMethods *nb;
344 if ((nb = vv->ob_type->tp_as_number) == NULL ||
345 nb->nb_int == NULL) {
346 PyErr_SetString(PyExc_TypeError, "an integer is required");
347 return -1;
348 }
349 vv = (*nb->nb_int) (vv);
350 if (vv == NULL)
351 return -1;
352 do_decref = 1;
353 if (!PyLong_Check(vv)) {
354 Py_DECREF(vv);
355 PyErr_SetString(PyExc_TypeError,
356 "nb_int should return int object");
357 return -1;
358 }
359 }
360
Georg Brandl61c31b02007-02-26 14:46:30 +0000361 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000362 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000363 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000364
Georg Brandl61c31b02007-02-26 14:46:30 +0000365 switch (i) {
366 case -1:
367 res = -v->ob_digit[0];
368 break;
369 case 0:
370 res = 0;
371 break;
372 case 1:
373 res = v->ob_digit[0];
374 break;
375 default:
376 sign = 1;
377 x = 0;
378 if (i < 0) {
379 sign = -1;
380 i = -(i);
381 }
382 while (--i >= 0) {
383 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000384 x = (x << PyLong_SHIFT) + v->ob_digit[i];
385 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000386 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000387 goto exit;
388 }
389 }
390 /* Haven't lost any bits, but casting to long requires extra care
391 * (see comment above).
392 */
393 if (x <= (unsigned long)LONG_MAX) {
394 res = (long)x * sign;
395 }
396 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
397 res = LONG_MIN;
398 }
399 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000400 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000401 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000402 }
403 }
404 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405 if (do_decref) {
406 Py_DECREF(vv);
407 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000408 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000409}
410
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000411long
412PyLong_AsLong(PyObject *obj)
413{
414 int overflow;
415 long result = PyLong_AsLongAndOverflow(obj, &overflow);
416 if (overflow) {
417 /* XXX: could be cute and give a different
418 message for overflow == -1 */
419 PyErr_SetString(PyExc_OverflowError,
420 "Python int too large to convert to C long");
421 }
422 return result;
423}
424
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000425/* Get a Py_ssize_t from a long int object.
426 Returns -1 and sets an error condition if overflow occurs. */
427
428Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000429PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430 register PyLongObject *v;
431 size_t x, prev;
432 Py_ssize_t i;
433 int sign;
434
435 if (vv == NULL || !PyLong_Check(vv)) {
436 PyErr_BadInternalCall();
437 return -1;
438 }
439 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000440 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441 switch (i) {
442 case -1: return -v->ob_digit[0];
443 case 0: return 0;
444 case 1: return v->ob_digit[0];
445 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446 sign = 1;
447 x = 0;
448 if (i < 0) {
449 sign = -1;
450 i = -(i);
451 }
452 while (--i >= 0) {
453 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000454 x = (x << PyLong_SHIFT) + v->ob_digit[i];
455 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456 goto overflow;
457 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 /* Haven't lost any bits, but casting to a signed type requires
459 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000460 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461 if (x <= (size_t)PY_SSIZE_T_MAX) {
462 return (Py_ssize_t)x * sign;
463 }
464 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
465 return PY_SSIZE_T_MIN;
466 }
467 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000468
469 overflow:
470 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000471 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000472 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000473}
474
Guido van Rossumd8c80482002-08-13 00:24:58 +0000475/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000476 Returns -1 and sets an error condition if overflow occurs. */
477
478unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000479PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000480{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000482 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000483 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 if (vv == NULL || !PyLong_Check(vv)) {
486 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000487 return (unsigned long) -1;
488 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000490 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000491 x = 0;
492 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000494 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000495 return (unsigned long) -1;
496 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000497 switch (i) {
498 case 0: return 0;
499 case 1: return v->ob_digit[0];
500 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000501 while (--i >= 0) {
502 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000503 x = (x << PyLong_SHIFT) + v->ob_digit[i];
504 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000506 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000507 return (unsigned long) -1;
508 }
509 }
510 return x;
511}
512
513/* Get a C unsigned long int from a long int object.
514 Returns -1 and sets an error condition if overflow occurs. */
515
516size_t
517PyLong_AsSize_t(PyObject *vv)
518{
519 register PyLongObject *v;
520 size_t x, prev;
521 Py_ssize_t i;
522
523 if (vv == NULL || !PyLong_Check(vv)) {
524 PyErr_BadInternalCall();
525 return (unsigned long) -1;
526 }
527 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000528 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000529 x = 0;
530 if (i < 0) {
531 PyErr_SetString(PyExc_OverflowError,
532 "can't convert negative value to size_t");
533 return (size_t) -1;
534 }
535 switch (i) {
536 case 0: return 0;
537 case 1: return v->ob_digit[0];
538 }
539 while (--i >= 0) {
540 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000541 x = (x << PyLong_SHIFT) + v->ob_digit[i];
542 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000543 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000544 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000545 return (unsigned long) -1;
546 }
547 }
548 return x;
549}
550
Thomas Hellera4ea6032003-04-17 18:55:45 +0000551/* Get a C unsigned long int from a long int object, ignoring the high bits.
552 Returns -1 and sets an error condition if an error occurs. */
553
Guido van Rossumddefaf32007-01-14 03:31:43 +0000554static unsigned long
555_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000556{
557 register PyLongObject *v;
558 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000559 Py_ssize_t i;
560 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000561
562 if (vv == NULL || !PyLong_Check(vv)) {
563 PyErr_BadInternalCall();
564 return (unsigned long) -1;
565 }
566 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000567 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000568 switch (i) {
569 case 0: return 0;
570 case 1: return v->ob_digit[0];
571 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000572 sign = 1;
573 x = 0;
574 if (i < 0) {
575 sign = -1;
576 i = -i;
577 }
578 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000579 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000580 }
581 return x * sign;
582}
583
Guido van Rossumddefaf32007-01-14 03:31:43 +0000584unsigned long
585PyLong_AsUnsignedLongMask(register PyObject *op)
586{
587 PyNumberMethods *nb;
588 PyLongObject *lo;
589 unsigned long val;
590
591 if (op && PyLong_Check(op))
592 return _PyLong_AsUnsignedLongMask(op);
593
594 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
595 nb->nb_int == NULL) {
596 PyErr_SetString(PyExc_TypeError, "an integer is required");
597 return (unsigned long)-1;
598 }
599
600 lo = (PyLongObject*) (*nb->nb_int) (op);
601 if (lo == NULL)
602 return (unsigned long)-1;
603 if (PyLong_Check(lo)) {
604 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
605 Py_DECREF(lo);
606 if (PyErr_Occurred())
607 return (unsigned long)-1;
608 return val;
609 }
610 else
611 {
612 Py_DECREF(lo);
613 PyErr_SetString(PyExc_TypeError,
614 "nb_int should return int object");
615 return (unsigned long)-1;
616 }
617}
618
Tim Peters5b8132f2003-01-31 15:52:05 +0000619int
620_PyLong_Sign(PyObject *vv)
621{
622 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000623
624 assert(v != NULL);
625 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000626
Christian Heimes90aa7642007-12-19 02:45:37 +0000627 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000628}
629
Tim Petersbaefd9e2003-01-28 20:37:45 +0000630size_t
631_PyLong_NumBits(PyObject *vv)
632{
633 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000634 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000635 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000636
637 assert(v != NULL);
638 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000639 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000640 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
641 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000642 digit msd = v->ob_digit[ndigits - 1];
643
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000644 result = (ndigits - 1) * PyLong_SHIFT;
645 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000646 goto Overflow;
647 do {
648 ++result;
649 if (result == 0)
650 goto Overflow;
651 msd >>= 1;
652 } while (msd);
653 }
654 return result;
655
656Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000657 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658 "to express in a platform size_t");
659 return (size_t)-1;
660}
661
Tim Peters2a9b3672001-06-11 21:23:58 +0000662PyObject *
663_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
664 int little_endian, int is_signed)
665{
666 const unsigned char* pstartbyte;/* LSB of bytes */
667 int incr; /* direction to move pstartbyte */
668 const unsigned char* pendbyte; /* MSB of bytes */
669 size_t numsignificantbytes; /* number of bytes that matter */
670 size_t ndigits; /* number of Python long digits */
671 PyLongObject* v; /* result */
672 int idigit = 0; /* next free index in v->ob_digit */
673
674 if (n == 0)
675 return PyLong_FromLong(0L);
676
677 if (little_endian) {
678 pstartbyte = bytes;
679 pendbyte = bytes + n - 1;
680 incr = 1;
681 }
682 else {
683 pstartbyte = bytes + n - 1;
684 pendbyte = bytes;
685 incr = -1;
686 }
687
688 if (is_signed)
689 is_signed = *pendbyte >= 0x80;
690
691 /* Compute numsignificantbytes. This consists of finding the most
692 significant byte. Leading 0 bytes are insignficant if the number
693 is positive, and leading 0xff bytes if negative. */
694 {
695 size_t i;
696 const unsigned char* p = pendbyte;
697 const int pincr = -incr; /* search MSB to LSB */
698 const unsigned char insignficant = is_signed ? 0xff : 0x00;
699
700 for (i = 0; i < n; ++i, p += pincr) {
701 if (*p != insignficant)
702 break;
703 }
704 numsignificantbytes = n - i;
705 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
706 actually has 2 significant bytes. OTOH, 0xff0001 ==
707 -0x00ffff, so we wouldn't *need* to bump it there; but we
708 do for 0xffff = -0x0001. To be safe without bothering to
709 check every case, bump it regardless. */
710 if (is_signed && numsignificantbytes < n)
711 ++numsignificantbytes;
712 }
713
714 /* How many Python long digits do we need? We have
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000715 8*numsignificantbytes bits, and each Python long digit has PyLong_SHIFT
Tim Peters2a9b3672001-06-11 21:23:58 +0000716 bits, so it's the ceiling of the quotient. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000717 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Tim Peters2a9b3672001-06-11 21:23:58 +0000718 if (ndigits > (size_t)INT_MAX)
719 return PyErr_NoMemory();
720 v = _PyLong_New((int)ndigits);
721 if (v == NULL)
722 return NULL;
723
724 /* Copy the bits over. The tricky parts are computing 2's-comp on
725 the fly for signed numbers, and dealing with the mismatch between
726 8-bit bytes and (probably) 15-bit Python digits.*/
727 {
728 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000729 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000730 twodigits accum = 0; /* sliding register */
731 unsigned int accumbits = 0; /* number of bits in accum */
732 const unsigned char* p = pstartbyte;
733
734 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000735 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000736 /* Compute correction for 2's comp, if needed. */
737 if (is_signed) {
738 thisbyte = (0xff ^ thisbyte) + carry;
739 carry = thisbyte >> 8;
740 thisbyte &= 0xff;
741 }
742 /* Because we're going LSB to MSB, thisbyte is
743 more significant than what's already in accum,
744 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000745 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000746 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000747 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000748 /* There's enough to fill a Python digit. */
749 assert(idigit < (int)ndigits);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000750 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000751 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000752 accum >>= PyLong_SHIFT;
753 accumbits -= PyLong_SHIFT;
754 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 }
756 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000757 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000758 if (accumbits) {
759 assert(idigit < (int)ndigits);
760 v->ob_digit[idigit] = (digit)accum;
761 ++idigit;
762 }
763 }
764
Christian Heimes90aa7642007-12-19 02:45:37 +0000765 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 return (PyObject *)long_normalize(v);
767}
768
769int
770_PyLong_AsByteArray(PyLongObject* v,
771 unsigned char* bytes, size_t n,
772 int little_endian, int is_signed)
773{
Mark Dickinson17e55872009-01-24 15:56:57 +0000774 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000775 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000776 twodigits accum; /* sliding register */
777 unsigned int accumbits; /* # bits in accum */
778 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000779 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000780 size_t j; /* # bytes filled */
781 unsigned char* p; /* pointer to next byte in bytes */
782 int pincr; /* direction to move p */
783
784 assert(v != NULL && PyLong_Check(v));
785
Christian Heimes90aa7642007-12-19 02:45:37 +0000786 if (Py_SIZE(v) < 0) {
787 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000788 if (!is_signed) {
789 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000790 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000791 return -1;
792 }
793 do_twos_comp = 1;
794 }
795 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000796 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000797 do_twos_comp = 0;
798 }
799
800 if (little_endian) {
801 p = bytes;
802 pincr = 1;
803 }
804 else {
805 p = bytes + n - 1;
806 pincr = -1;
807 }
808
Tim Peters898cf852001-06-13 20:50:08 +0000809 /* Copy over all the Python digits.
810 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000811 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000812 normalized. */
813 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000814 j = 0;
815 accum = 0;
816 accumbits = 0;
817 carry = do_twos_comp ? 1 : 0;
818 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000819 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000820 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000821 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
822 carry = thisdigit >> PyLong_SHIFT;
823 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000824 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000825 /* Because we're going LSB to MSB, thisdigit is more
826 significant than what's already in accum, so needs to be
827 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000828 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000829
Tim Petersede05092001-06-14 08:53:38 +0000830 /* The most-significant digit may be (probably is) at least
831 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000832 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000833 /* Count # of sign bits -- they needn't be stored,
834 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000835 * make sure at least one sign bit gets stored. */
836 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
837 thisdigit;
838 while (s != 0) {
839 s >>= 1;
840 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000841 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000842 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000843 else
844 accumbits += PyLong_SHIFT;
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{
Mark Dickinson17e55872009-01-24 15:56:57 +00001364 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001365 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{
Mark Dickinson17e55872009-01-24 15:56:57 +00001390 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001391 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);
Mark Dickinson17e55872009-01-24 15:56:57 +00001456 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001457 }
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);
Mark Dickinson17e55872009-01-24 15:56:57 +00001715 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);
Mark Dickinson17e55872009-01-24 15:56:57 +00001719 assert(pdigit - z->ob_digit <= 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;
Mark Dickinson17e55872009-01-24 15:56:57 +00001728 assert(pdigit - z->ob_digit <= 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 while (*str && isspace(Py_CHARMASK(*str)))
1994 str++;
1995 if (*str != '\0')
1996 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001997 if (pend)
1998 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00001999 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002000 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002001
2002 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002003 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002004 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002005 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002006 if (strobj == NULL)
2007 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002008 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002009 "invalid literal for int() with base %d: %R",
2010 base, strobj);
2011 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002012 return NULL;
2013}
2014
2015PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002016PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002017{
Walter Dörwald07e14762002-11-06 16:15:14 +00002018 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002019 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002020
Walter Dörwald07e14762002-11-06 16:15:14 +00002021 if (buffer == NULL)
2022 return NULL;
2023
2024 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2025 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002026 return NULL;
2027 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002028 result = PyLong_FromString(buffer, NULL, base);
2029 PyMem_FREE(buffer);
2030 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002031}
2032
Tim Peters9f688bf2000-07-07 15:53:28 +00002033/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002034static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002035 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002036static PyObject *long_long(PyObject *v);
Tim Peters9f688bf2000-07-07 15:53:28 +00002037static int long_divrem(PyLongObject *, PyLongObject *,
2038 PyLongObject **, PyLongObject **);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002039
2040/* Long division with remainder, top-level routine */
2041
Guido van Rossume32e0141992-01-19 16:31:05 +00002042static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002043long_divrem(PyLongObject *a, PyLongObject *b,
2044 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045{
Christian Heimes90aa7642007-12-19 02:45:37 +00002046 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002047 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002048
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002050 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002051 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002052 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 }
2054 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002055 (size_a == size_b &&
2056 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002058 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002059 if (*pdiv == NULL)
2060 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002061 Py_INCREF(a);
2062 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002063 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002064 }
2065 if (size_b == 1) {
2066 digit rem = 0;
2067 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002068 if (z == NULL)
2069 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002071 if (*prem == NULL) {
2072 Py_DECREF(z);
2073 return -1;
2074 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002075 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002076 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002078 if (z == NULL)
2079 return -1;
2080 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 /* Set the signs.
2082 The quotient z has the sign of a*b;
2083 the remainder r has the sign of a,
2084 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002085 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002086 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002087 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002088 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002089 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002090 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002091}
2092
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002093/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002094
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002096x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002097{
Christian Heimes90aa7642007-12-19 02:45:37 +00002098 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002099 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 PyLongObject *v = mul1(v1, d);
2101 PyLongObject *w = mul1(w1, d);
2102 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002103 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002104
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002105 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 Py_XDECREF(v);
2107 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002108 return NULL;
2109 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002110
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002111 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002112 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2113 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
Christian Heimes90aa7642007-12-19 02:45:37 +00002115 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002116 k = size_v - size_w;
2117 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002118
Thomas Wouters477c8d52006-05-27 19:21:47 +00002119 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002120 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2121 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002122 stwodigits carry = 0;
Mark Dickinson17e55872009-01-24 15:56:57 +00002123 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002125 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002127 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002128 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002129 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002131 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002133 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002134 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002135
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002136 while (w->ob_digit[size_w-2]*q >
2137 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002138 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139 + v->ob_digit[j-1]
2140 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002141 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002142 + v->ob_digit[j-2])
2143 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002144
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145 for (i = 0; i < size_w && i+k < size_v; ++i) {
2146 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002147 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002148 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002149 + ((twodigits)zz << PyLong_SHIFT);
2150 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002151 carry = Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002152 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002153 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002155
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002156 if (i+k < size_v) {
2157 carry += v->ob_digit[i+k];
2158 v->ob_digit[i+k] = 0;
2159 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002160
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002162 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163 else {
2164 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002165 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002166 carry = 0;
2167 for (i = 0; i < size_w && i+k < size_v; ++i) {
2168 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002169 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002170 carry = Py_ARITHMETIC_RIGHT_SHIFT(
2171 BASE_TWODIGITS_TYPE,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002172 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002173 }
2174 }
2175 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002176
Guido van Rossumc206c761995-01-10 15:23:19 +00002177 if (a == NULL)
2178 *prem = NULL;
2179 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002180 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002181 *prem = divrem1(v, d, &d);
2182 /* d receives the (unused) remainder */
2183 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002185 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002186 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002187 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 Py_DECREF(v);
2189 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002190 return a;
2191}
2192
2193/* Methods */
2194
2195static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002196long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002197{
Christian Heimes90aa7642007-12-19 02:45:37 +00002198 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002199}
2200
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002201static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002202long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002203{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002204 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002205}
2206
2207static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002208long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002209{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002210 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002211
Christian Heimes90aa7642007-12-19 02:45:37 +00002212 if (Py_SIZE(a) != Py_SIZE(b)) {
2213 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002214 sign = 0;
2215 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002216 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002217 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002218 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002219 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002220 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2221 ;
2222 if (i < 0)
2223 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002224 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002225 sign = (int)a->ob_digit[i] - (int)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002226 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002227 sign = -sign;
2228 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002229 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002230 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002231}
2232
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002233#define TEST_COND(cond) \
2234 ((cond) ? Py_True : Py_False)
2235
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002236static PyObject *
2237long_richcompare(PyObject *self, PyObject *other, int op)
2238{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002239 int result;
2240 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002241 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002242 if (self == other)
2243 result = 0;
2244 else
2245 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2246 /* Convert the return value to a Boolean */
2247 switch (op) {
2248 case Py_EQ:
2249 v = TEST_COND(result == 0);
2250 break;
2251 case Py_NE:
2252 v = TEST_COND(result != 0);
2253 break;
2254 case Py_LE:
2255 v = TEST_COND(result <= 0);
2256 break;
2257 case Py_GE:
2258 v = TEST_COND(result >= 0);
2259 break;
2260 case Py_LT:
2261 v = TEST_COND(result == -1);
2262 break;
2263 case Py_GT:
2264 v = TEST_COND(result == 1);
2265 break;
2266 default:
2267 PyErr_BadArgument();
2268 return NULL;
2269 }
2270 Py_INCREF(v);
2271 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002272}
2273
Guido van Rossum9bfef441993-03-29 10:43:31 +00002274static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002275long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002276{
2277 long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002278 Py_ssize_t i;
2279 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002280
2281 /* This is designed so that Python ints and longs with the
2282 same value hash to the same value, otherwise comparisons
2283 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002284 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002285 switch(i) {
2286 case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
2287 case 0: return 0;
2288 case 1: return v->ob_digit[0];
2289 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002290 sign = 1;
2291 x = 0;
2292 if (i < 0) {
2293 sign = -1;
2294 i = -(i);
2295 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002296#define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT)
Thomas Woutersce272b62007-09-19 21:19:28 +00002297 /* The following loop produces a C long x such that (unsigned long)x
2298 is congruent to the absolute value of v modulo ULONG_MAX. The
2299 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002300 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002301 /* Force a native long #-bits (32 or 64) circular shift */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002302 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002303 x += v->ob_digit[i];
Thomas Woutersce272b62007-09-19 21:19:28 +00002304 /* If the addition above overflowed (thinking of x as
2305 unsigned), we compensate by incrementing. This preserves
2306 the value modulo ULONG_MAX. */
2307 if ((unsigned long)x < v->ob_digit[i])
2308 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002309 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002310#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002311 x = x * sign;
2312 if (x == -1)
2313 x = -2;
2314 return x;
2315}
2316
2317
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318/* Add the absolute values of two long integers. */
2319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002320static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002321x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002322{
Christian Heimes90aa7642007-12-19 02:45:37 +00002323 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002325 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002326 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002327
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002328 /* Ensure a is the larger of the two: */
2329 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002330 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002331 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332 size_a = size_b;
2333 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002334 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002335 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002336 if (z == NULL)
2337 return NULL;
2338 for (i = 0; i < size_b; ++i) {
2339 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002340 z->ob_digit[i] = carry & PyLong_MASK;
2341 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002342 }
2343 for (; i < size_a; ++i) {
2344 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002345 z->ob_digit[i] = carry & PyLong_MASK;
2346 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002347 }
2348 z->ob_digit[i] = carry;
2349 return long_normalize(z);
2350}
2351
2352/* Subtract the absolute values of two integers. */
2353
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002354static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002355x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002356{
Christian Heimes90aa7642007-12-19 02:45:37 +00002357 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002358 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002359 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360 int sign = 1;
2361 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002362
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002363 /* Ensure a is the larger of the two: */
2364 if (size_a < size_b) {
2365 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002366 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002367 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002368 size_a = size_b;
2369 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370 }
2371 else if (size_a == size_b) {
2372 /* Find highest digit where a and b differ: */
2373 i = size_a;
2374 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2375 ;
2376 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002377 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378 if (a->ob_digit[i] < b->ob_digit[i]) {
2379 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002380 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002381 }
2382 size_a = size_b = i+1;
2383 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002384 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002385 if (z == NULL)
2386 return NULL;
2387 for (i = 0; i < size_b; ++i) {
2388 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002389 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002390 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002391 z->ob_digit[i] = borrow & PyLong_MASK;
2392 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002393 borrow &= 1; /* Keep only one sign bit */
2394 }
2395 for (; i < size_a; ++i) {
2396 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002397 z->ob_digit[i] = borrow & PyLong_MASK;
2398 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002399 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002400 }
2401 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002402 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002403 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002404 return long_normalize(z);
2405}
2406
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002407static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002408long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002409{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002410 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002411
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002412 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002413
Christian Heimes90aa7642007-12-19 02:45:37 +00002414 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002415 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002416 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002417 return result;
2418 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002419 if (Py_SIZE(a) < 0) {
2420 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002421 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002422 if (z != NULL && Py_SIZE(z) != 0)
2423 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002424 }
2425 else
2426 z = x_sub(b, a);
2427 }
2428 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002429 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002430 z = x_sub(a, b);
2431 else
2432 z = x_add(a, b);
2433 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002434 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435}
2436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002437static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002438long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002439{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002440 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002441
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002442 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002443
Christian Heimes90aa7642007-12-19 02:45:37 +00002444 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002445 PyObject* r;
2446 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002447 return r;
2448 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002449 if (Py_SIZE(a) < 0) {
2450 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002451 z = x_sub(a, b);
2452 else
2453 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002454 if (z != NULL && Py_SIZE(z) != 0)
2455 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002456 }
2457 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002458 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002459 z = x_add(a, b);
2460 else
2461 z = x_sub(a, b);
2462 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002463 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002464}
2465
Tim Peters5af4e6c2002-08-12 02:31:19 +00002466/* Grade school multiplication, ignoring the signs.
2467 * Returns the absolute value of the product, or NULL if error.
2468 */
2469static PyLongObject *
2470x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002471{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002472 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002473 Py_ssize_t size_a = ABS(Py_SIZE(a));
2474 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002475 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002476
Tim Peters5af4e6c2002-08-12 02:31:19 +00002477 z = _PyLong_New(size_a + size_b);
2478 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002479 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002480
Christian Heimes90aa7642007-12-19 02:45:37 +00002481 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002482 if (a == b) {
2483 /* Efficient squaring per HAC, Algorithm 14.16:
2484 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2485 * Gives slightly less than a 2x speedup when a == b,
2486 * via exploiting that each entry in the multiplication
2487 * pyramid appears twice (except for the size_a squares).
2488 */
2489 for (i = 0; i < size_a; ++i) {
2490 twodigits carry;
2491 twodigits f = a->ob_digit[i];
2492 digit *pz = z->ob_digit + (i << 1);
2493 digit *pa = a->ob_digit + i + 1;
2494 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495
Tim Peters0973b992004-08-29 22:16:50 +00002496 SIGCHECK({
2497 Py_DECREF(z);
2498 return NULL;
2499 })
2500
2501 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002502 *pz++ = (digit)(carry & PyLong_MASK);
2503 carry >>= PyLong_SHIFT;
2504 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002505
2506 /* Now f is added in twice in each column of the
2507 * pyramid it appears. Same as adding f<<1 once.
2508 */
2509 f <<= 1;
2510 while (pa < paend) {
2511 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002512 *pz++ = (digit)(carry & PyLong_MASK);
2513 carry >>= PyLong_SHIFT;
2514 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002515 }
2516 if (carry) {
2517 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002518 *pz++ = (digit)(carry & PyLong_MASK);
2519 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002520 }
2521 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002522 *pz += (digit)(carry & PyLong_MASK);
2523 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002524 }
Tim Peters0973b992004-08-29 22:16:50 +00002525 }
2526 else { /* a is not the same as b -- gradeschool long mult */
2527 for (i = 0; i < size_a; ++i) {
2528 twodigits carry = 0;
2529 twodigits f = a->ob_digit[i];
2530 digit *pz = z->ob_digit + i;
2531 digit *pb = b->ob_digit;
2532 digit *pbend = b->ob_digit + size_b;
2533
2534 SIGCHECK({
2535 Py_DECREF(z);
2536 return NULL;
2537 })
2538
2539 while (pb < pbend) {
2540 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002541 *pz++ = (digit)(carry & PyLong_MASK);
2542 carry >>= PyLong_SHIFT;
2543 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002544 }
2545 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002546 *pz += (digit)(carry & PyLong_MASK);
2547 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002548 }
2549 }
Tim Peters44121a62002-08-12 06:17:58 +00002550 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002551}
2552
2553/* A helper for Karatsuba multiplication (k_mul).
2554 Takes a long "n" and an integer "size" representing the place to
2555 split, and sets low and high such that abs(n) == (high << size) + low,
2556 viewing the shift as being by digits. The sign bit is ignored, and
2557 the return values are >= 0.
2558 Returns 0 on success, -1 on failure.
2559*/
2560static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002561kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002562{
2563 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002564 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002565 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002566
2567 size_lo = MIN(size_n, size);
2568 size_hi = size_n - size_lo;
2569
2570 if ((hi = _PyLong_New(size_hi)) == NULL)
2571 return -1;
2572 if ((lo = _PyLong_New(size_lo)) == NULL) {
2573 Py_DECREF(hi);
2574 return -1;
2575 }
2576
2577 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2578 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2579
2580 *high = long_normalize(hi);
2581 *low = long_normalize(lo);
2582 return 0;
2583}
2584
Tim Peters60004642002-08-12 22:01:34 +00002585static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2586
Tim Peters5af4e6c2002-08-12 02:31:19 +00002587/* Karatsuba multiplication. Ignores the input signs, and returns the
2588 * absolute value of the product (or NULL if error).
2589 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2590 */
2591static PyLongObject *
2592k_mul(PyLongObject *a, PyLongObject *b)
2593{
Christian Heimes90aa7642007-12-19 02:45:37 +00002594 Py_ssize_t asize = ABS(Py_SIZE(a));
2595 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002596 PyLongObject *ah = NULL;
2597 PyLongObject *al = NULL;
2598 PyLongObject *bh = NULL;
2599 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002600 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002601 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002602 Py_ssize_t shift; /* the number of digits we split off */
2603 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002604
Tim Peters5af4e6c2002-08-12 02:31:19 +00002605 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2606 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2607 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002608 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002609 * By picking X to be a power of 2, "*X" is just shifting, and it's
2610 * been reduced to 3 multiplies on numbers half the size.
2611 */
2612
Tim Petersfc07e562002-08-12 02:54:10 +00002613 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002614 * is largest.
2615 */
Tim Peters738eda72002-08-12 15:08:20 +00002616 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002617 t1 = a;
2618 a = b;
2619 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002620
2621 i = asize;
2622 asize = bsize;
2623 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002624 }
2625
2626 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002627 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2628 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002629 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002630 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002631 else
2632 return x_mul(a, b);
2633 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002634
Tim Peters60004642002-08-12 22:01:34 +00002635 /* If a is small compared to b, splitting on b gives a degenerate
2636 * case with ah==0, and Karatsuba may be (even much) less efficient
2637 * than "grade school" then. However, we can still win, by viewing
2638 * b as a string of "big digits", each of width a->ob_size. That
2639 * leads to a sequence of balanced calls to k_mul.
2640 */
2641 if (2 * asize <= bsize)
2642 return k_lopsided_mul(a, b);
2643
Tim Petersd6974a52002-08-13 20:37:51 +00002644 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002645 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002647 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002648
Tim Peters0973b992004-08-29 22:16:50 +00002649 if (a == b) {
2650 bh = ah;
2651 bl = al;
2652 Py_INCREF(bh);
2653 Py_INCREF(bl);
2654 }
2655 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002656
Tim Petersd64c1de2002-08-12 17:36:03 +00002657 /* The plan:
2658 * 1. Allocate result space (asize + bsize digits: that's always
2659 * enough).
2660 * 2. Compute ah*bh, and copy into result at 2*shift.
2661 * 3. Compute al*bl, and copy into result at 0. Note that this
2662 * can't overlap with #2.
2663 * 4. Subtract al*bl from the result, starting at shift. This may
2664 * underflow (borrow out of the high digit), but we don't care:
2665 * we're effectively doing unsigned arithmetic mod
2666 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2667 * borrows and carries out of the high digit can be ignored.
2668 * 5. Subtract ah*bh from the result, starting at shift.
2669 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2670 * at shift.
2671 */
2672
2673 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002674 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002675 if (ret == NULL) goto fail;
2676#ifdef Py_DEBUG
2677 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002678 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679#endif
Tim Peters44121a62002-08-12 06:17:58 +00002680
Tim Petersd64c1de2002-08-12 17:36:03 +00002681 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002682 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002683 assert(Py_SIZE(t1) >= 0);
2684 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002685 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002686 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002687
2688 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002689 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002690 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002691 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002692 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002693
Tim Petersd64c1de2002-08-12 17:36:03 +00002694 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002695 if ((t2 = k_mul(al, bl)) == NULL) {
2696 Py_DECREF(t1);
2697 goto fail;
2698 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002699 assert(Py_SIZE(t2) >= 0);
2700 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2701 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002702
2703 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002704 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002705 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002706 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002707
Tim Petersd64c1de2002-08-12 17:36:03 +00002708 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2709 * because it's fresher in cache.
2710 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002711 i = Py_SIZE(ret) - shift; /* # digits after shift */
2712 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002713 Py_DECREF(t2);
2714
Christian Heimes90aa7642007-12-19 02:45:37 +00002715 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002716 Py_DECREF(t1);
2717
Tim Petersd64c1de2002-08-12 17:36:03 +00002718 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002719 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2720 Py_DECREF(ah);
2721 Py_DECREF(al);
2722 ah = al = NULL;
2723
Tim Peters0973b992004-08-29 22:16:50 +00002724 if (a == b) {
2725 t2 = t1;
2726 Py_INCREF(t2);
2727 }
2728 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002729 Py_DECREF(t1);
2730 goto fail;
2731 }
2732 Py_DECREF(bh);
2733 Py_DECREF(bl);
2734 bh = bl = NULL;
2735
Tim Peters738eda72002-08-12 15:08:20 +00002736 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002737 Py_DECREF(t1);
2738 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002739 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002740 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002741
Tim Petersd6974a52002-08-13 20:37:51 +00002742 /* Add t3. It's not obvious why we can't run out of room here.
2743 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002744 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002745 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002746 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002747
Tim Peters5af4e6c2002-08-12 02:31:19 +00002748 return long_normalize(ret);
2749
2750 fail:
2751 Py_XDECREF(ret);
2752 Py_XDECREF(ah);
2753 Py_XDECREF(al);
2754 Py_XDECREF(bh);
2755 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002756 return NULL;
2757}
2758
Tim Petersd6974a52002-08-13 20:37:51 +00002759/* (*) Why adding t3 can't "run out of room" above.
2760
Tim Petersab86c2b2002-08-15 20:06:00 +00002761Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2762to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002763
Tim Petersab86c2b2002-08-15 20:06:00 +000027641. For any integer i, i = c(i/2) + f(i/2). In particular,
2765 bsize = c(bsize/2) + f(bsize/2).
27662. shift = f(bsize/2)
27673. asize <= bsize
27684. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2769 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002770
Tim Petersab86c2b2002-08-15 20:06:00 +00002771We allocated asize + bsize result digits, and add t3 into them at an offset
2772of shift. This leaves asize+bsize-shift allocated digit positions for t3
2773to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2774asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002775
Tim Petersab86c2b2002-08-15 20:06:00 +00002776bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2777at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002778
Tim Petersab86c2b2002-08-15 20:06:00 +00002779If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2780digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2781most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002782
Tim Petersab86c2b2002-08-15 20:06:00 +00002783The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002784
Tim Petersab86c2b2002-08-15 20:06:00 +00002785 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002786
Tim Petersab86c2b2002-08-15 20:06:00 +00002787and we have asize + c(bsize/2) available digit positions. We need to show
2788this is always enough. An instance of c(bsize/2) cancels out in both, so
2789the question reduces to whether asize digits is enough to hold
2790(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2791then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2792asize 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 +00002793digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002794asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002795c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2796is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2797bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002798
Tim Peters48d52c02002-08-14 17:07:32 +00002799Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2800clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2801ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002802*/
2803
Tim Peters60004642002-08-12 22:01:34 +00002804/* b has at least twice the digits of a, and a is big enough that Karatsuba
2805 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2806 * of slices, each with a->ob_size digits, and multiply the slices by a,
2807 * one at a time. This gives k_mul balanced inputs to work with, and is
2808 * also cache-friendly (we compute one double-width slice of the result
2809 * at a time, then move on, never bactracking except for the helpful
2810 * single-width slice overlap between successive partial sums).
2811 */
2812static PyLongObject *
2813k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2814{
Christian Heimes90aa7642007-12-19 02:45:37 +00002815 const Py_ssize_t asize = ABS(Py_SIZE(a));
2816 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002817 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002818 PyLongObject *ret;
2819 PyLongObject *bslice = NULL;
2820
2821 assert(asize > KARATSUBA_CUTOFF);
2822 assert(2 * asize <= bsize);
2823
2824 /* Allocate result space, and zero it out. */
2825 ret = _PyLong_New(asize + bsize);
2826 if (ret == NULL)
2827 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002828 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002829
2830 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002831 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002832 if (bslice == NULL)
2833 goto fail;
2834
2835 nbdone = 0;
2836 while (bsize > 0) {
2837 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002838 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002839
2840 /* Multiply the next slice of b by a. */
2841 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2842 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002843 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002844 product = k_mul(a, bslice);
2845 if (product == NULL)
2846 goto fail;
2847
2848 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002849 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2850 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002851 Py_DECREF(product);
2852
2853 bsize -= nbtouse;
2854 nbdone += nbtouse;
2855 }
2856
2857 Py_DECREF(bslice);
2858 return long_normalize(ret);
2859
2860 fail:
2861 Py_DECREF(ret);
2862 Py_XDECREF(bslice);
2863 return NULL;
2864}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002865
2866static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002867long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002868{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002869 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002870
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002871 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002872
Christian Heimes90aa7642007-12-19 02:45:37 +00002873 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002874 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002875 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002876 return r;
2877 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002878
Tim Petersd64c1de2002-08-12 17:36:03 +00002879 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002880 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002881 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002882 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002883 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002884}
2885
Guido van Rossume32e0141992-01-19 16:31:05 +00002886/* The / and % operators are now defined in terms of divmod().
2887 The expression a mod b has the value a - b*floor(a/b).
2888 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002889 |a| by |b|, with the sign of a. This is also expressed
2890 as a - b*trunc(a/b), if trunc truncates towards zero.
2891 Some examples:
2892 a b a rem b a mod b
2893 13 10 3 3
2894 -13 10 -3 7
2895 13 -10 3 -7
2896 -13 -10 -3 -3
2897 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002898 have different signs. We then subtract one from the 'div'
2899 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002900
Tim Peters47e52ee2004-08-30 02:44:38 +00002901/* Compute
2902 * *pdiv, *pmod = divmod(v, w)
2903 * NULL can be passed for pdiv or pmod, in which case that part of
2904 * the result is simply thrown away. The caller owns a reference to
2905 * each of these it requests (does not pass NULL for).
2906 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002907static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002908l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002909 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002910{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002911 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002912
Guido van Rossume32e0141992-01-19 16:31:05 +00002913 if (long_divrem(v, w, &div, &mod) < 0)
2914 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002915 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2916 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002917 PyLongObject *temp;
2918 PyLongObject *one;
2919 temp = (PyLongObject *) long_add(mod, w);
2920 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002921 mod = temp;
2922 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002923 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002924 return -1;
2925 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002926 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002927 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2929 Py_DECREF(mod);
2930 Py_DECREF(div);
2931 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002932 return -1;
2933 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002934 Py_DECREF(one);
2935 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002936 div = temp;
2937 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002938 if (pdiv != NULL)
2939 *pdiv = div;
2940 else
2941 Py_DECREF(div);
2942
2943 if (pmod != NULL)
2944 *pmod = mod;
2945 else
2946 Py_DECREF(mod);
2947
Guido van Rossume32e0141992-01-19 16:31:05 +00002948 return 0;
2949}
2950
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002951static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002952long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002953{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002954 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002955
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002956 CHECK_BINOP(a, b);
2957 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002958 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002959 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002960}
2961
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002962static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002963long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002964{
Tim Peterse2a60002001-09-04 06:17:36 +00002965 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002966 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002967
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002968 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002969 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2970 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002971 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002972 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002973 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002974 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2975 but should really be set correctly after sucessful calls to
2976 _PyLong_AsScaledDouble() */
2977 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002978
2979 if (bd == 0.0) {
2980 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002981 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002982 return NULL;
2983 }
2984
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002985 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002986 ad /= bd; /* overflow/underflow impossible here */
2987 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002988 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002989 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002990 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002991 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002992 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002993 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002994 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002995 goto overflow;
2996 return PyFloat_FromDouble(ad);
2997
2998overflow:
2999 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003000 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003001 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003002
Tim Peters20dab9f2001-09-04 05:31:47 +00003003}
3004
3005static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003006long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003007{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003008 PyLongObject *mod;
3009
3010 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003011
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003012 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003013 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003014 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003015}
3016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003017static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003018long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003019{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003020 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003021 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003022
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003023 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003024
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003025 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003026 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003027 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003028 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003029 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003030 PyTuple_SetItem(z, 0, (PyObject *) div);
3031 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003032 }
3033 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003034 Py_DECREF(div);
3035 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003036 }
3037 return z;
3038}
3039
Tim Peters47e52ee2004-08-30 02:44:38 +00003040/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003041static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003042long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003043{
Tim Peters47e52ee2004-08-30 02:44:38 +00003044 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3045 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003046
Tim Peters47e52ee2004-08-30 02:44:38 +00003047 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003048 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003049 PyLongObject *temp = NULL;
3050
3051 /* 5-ary values. If the exponent is large enough, table is
3052 * precomputed so that table[i] == a**i % c for i in range(32).
3053 */
3054 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3055 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3056
3057 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003058 CHECK_BINOP(v, w);
3059 a = (PyLongObject*)v; Py_INCREF(a);
3060 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003061 if (PyLong_Check(x)) {
3062 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003063 Py_INCREF(x);
3064 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003065 else if (x == Py_None)
3066 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003067 else {
3068 Py_DECREF(a);
3069 Py_DECREF(b);
3070 Py_INCREF(Py_NotImplemented);
3071 return Py_NotImplemented;
3072 }
Tim Peters4c483c42001-09-05 06:24:58 +00003073
Christian Heimes90aa7642007-12-19 02:45:37 +00003074 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003075 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003076 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003077 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003078 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003079 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003080 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003081 /* else return a float. This works because we know
3082 that this calls float_pow() which converts its
3083 arguments to double. */
3084 Py_DECREF(a);
3085 Py_DECREF(b);
3086 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003087 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003088 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003089
3090 if (c) {
3091 /* if modulus == 0:
3092 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003093 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003094 PyErr_SetString(PyExc_ValueError,
3095 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003096 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003097 }
3098
3099 /* if modulus < 0:
3100 negativeOutput = True
3101 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003102 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003103 negativeOutput = 1;
3104 temp = (PyLongObject *)_PyLong_Copy(c);
3105 if (temp == NULL)
3106 goto Error;
3107 Py_DECREF(c);
3108 c = temp;
3109 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003110 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003111 }
3112
3113 /* if modulus == 1:
3114 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003115 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003116 z = (PyLongObject *)PyLong_FromLong(0L);
3117 goto Done;
3118 }
3119
3120 /* if base < 0:
3121 base = base % modulus
3122 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003123 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003124 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003125 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003126 Py_DECREF(a);
3127 a = temp;
3128 temp = NULL;
3129 }
3130 }
3131
3132 /* At this point a, b, and c are guaranteed non-negative UNLESS
3133 c is NULL, in which case a may be negative. */
3134
3135 z = (PyLongObject *)PyLong_FromLong(1L);
3136 if (z == NULL)
3137 goto Error;
3138
3139 /* Perform a modular reduction, X = X % c, but leave X alone if c
3140 * is NULL.
3141 */
3142#define REDUCE(X) \
3143 if (c != NULL) { \
3144 if (l_divmod(X, c, NULL, &temp) < 0) \
3145 goto Error; \
3146 Py_XDECREF(X); \
3147 X = temp; \
3148 temp = NULL; \
3149 }
3150
3151 /* Multiply two values, then reduce the result:
3152 result = X*Y % c. If c is NULL, skip the mod. */
3153#define MULT(X, Y, result) \
3154{ \
3155 temp = (PyLongObject *)long_mul(X, Y); \
3156 if (temp == NULL) \
3157 goto Error; \
3158 Py_XDECREF(result); \
3159 result = temp; \
3160 temp = NULL; \
3161 REDUCE(result) \
3162}
3163
Christian Heimes90aa7642007-12-19 02:45:37 +00003164 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003165 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3166 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003167 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003168 digit bi = b->ob_digit[i];
3169
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003170 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003171 MULT(z, z, z)
3172 if (bi & j)
3173 MULT(z, a, z)
3174 }
3175 }
3176 }
3177 else {
3178 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3179 Py_INCREF(z); /* still holds 1L */
3180 table[0] = z;
3181 for (i = 1; i < 32; ++i)
3182 MULT(table[i-1], a, table[i])
3183
Christian Heimes90aa7642007-12-19 02:45:37 +00003184 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003185 const digit bi = b->ob_digit[i];
3186
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003187 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003188 const int index = (bi >> j) & 0x1f;
3189 for (k = 0; k < 5; ++k)
3190 MULT(z, z, z)
3191 if (index)
3192 MULT(z, table[index], z)
3193 }
3194 }
3195 }
3196
Christian Heimes90aa7642007-12-19 02:45:37 +00003197 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003198 temp = (PyLongObject *)long_sub(z, c);
3199 if (temp == NULL)
3200 goto Error;
3201 Py_DECREF(z);
3202 z = temp;
3203 temp = NULL;
3204 }
3205 goto Done;
3206
3207 Error:
3208 if (z != NULL) {
3209 Py_DECREF(z);
3210 z = NULL;
3211 }
3212 /* fall through */
3213 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003214 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003215 for (i = 0; i < 32; ++i)
3216 Py_XDECREF(table[i]);
3217 }
Tim Petersde7990b2005-07-17 23:45:23 +00003218 Py_DECREF(a);
3219 Py_DECREF(b);
3220 Py_XDECREF(c);
3221 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003222 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003223}
3224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003225static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003226long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003227{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003228 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003229 PyLongObject *x;
3230 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003231 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003232 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003233 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003234 if (w == NULL)
3235 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236 x = (PyLongObject *) long_add(v, w);
3237 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003238 if (x == NULL)
3239 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003240 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003241 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003242}
3243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003244static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003245long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003246{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003247 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003248 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003249 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003250 z = (PyLongObject *)_PyLong_Copy(v);
3251 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003252 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003253 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003254}
3255
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003256static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003257long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003258{
Christian Heimes90aa7642007-12-19 02:45:37 +00003259 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003260 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003261 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003262 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003263}
3264
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003265static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003266long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003267{
Christian Heimes90aa7642007-12-19 02:45:37 +00003268 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003269}
3270
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003271static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003272long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003273{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003274 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003275 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003276 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003277 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003278
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003279 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003280
Christian Heimes90aa7642007-12-19 02:45:37 +00003281 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003282 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003283 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003284 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003285 if (a1 == NULL)
3286 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003287 a2 = (PyLongObject *) long_rshift(a1, b);
3288 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003289 if (a2 == NULL)
3290 goto rshift_error;
3291 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003292 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003293 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003294 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003295
Neil Schemenauerba872e22001-01-04 01:46:03 +00003296 shiftby = PyLong_AsLong((PyObject *)b);
3297 if (shiftby == -1L && PyErr_Occurred())
3298 goto rshift_error;
3299 if (shiftby < 0) {
3300 PyErr_SetString(PyExc_ValueError,
3301 "negative shift count");
3302 goto rshift_error;
3303 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003304 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003305 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003306 if (newsize <= 0)
3307 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003308 loshift = shiftby % PyLong_SHIFT;
3309 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003310 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003311 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003312 z = _PyLong_New(newsize);
3313 if (z == NULL)
3314 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003315 if (Py_SIZE(a) < 0)
3316 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003317 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3318 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3319 if (i+1 < newsize)
3320 z->ob_digit[i] |=
3321 (a->ob_digit[j+1] << hishift) & himask;
3322 }
3323 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003324 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003325rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003326 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003327
Guido van Rossumc6913e71991-11-19 20:26:46 +00003328}
3329
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003330static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003331long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003332{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003333 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003334 PyLongObject *a = (PyLongObject*)v;
3335 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003336 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003337 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003338 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003339 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003340
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003341 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003342
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003343 shiftby = PyLong_AsLong((PyObject *)b);
3344 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003345 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003346 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003347 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003348 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003349 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003350 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003351 PyErr_SetString(PyExc_ValueError,
3352 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003353 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003354 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003355 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3356 wordshift = (int)shiftby / PyLong_SHIFT;
3357 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003358
Christian Heimes90aa7642007-12-19 02:45:37 +00003359 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003360 newsize = oldsize + wordshift;
3361 if (remshift)
3362 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003363 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003364 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003365 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003366 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003367 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003368 for (i = 0; i < wordshift; i++)
3369 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003370 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003371 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003372 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003373 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3374 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003375 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003376 if (remshift)
3377 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003378 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003379 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003380 z = long_normalize(z);
3381lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003382 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003383}
3384
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003385
3386/* Bitwise and/xor/or operations */
3387
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003388static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003389long_bitwise(PyLongObject *a,
3390 int op, /* '&', '|', '^' */
3391 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003392{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003393 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003394 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003395 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003396 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003397 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003398 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003399 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Christian Heimes90aa7642007-12-19 02:45:37 +00003401 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003402 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003403 if (a == NULL)
3404 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003405 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003406 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003407 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003408 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003409 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003410 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003411 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003412 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003413 if (b == NULL) {
3414 Py_DECREF(a);
3415 return NULL;
3416 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003417 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003418 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003419 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003420 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003421 maskb = 0;
3422 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003423
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003424 negz = 0;
3425 switch (op) {
3426 case '^':
3427 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003428 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003429 negz = -1;
3430 }
3431 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003432 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003433 if (maska && maskb) {
3434 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003435 maska ^= PyLong_MASK;
3436 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003437 negz = -1;
3438 }
3439 break;
3440 case '|':
3441 if (maska || maskb) {
3442 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003443 maska ^= PyLong_MASK;
3444 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003445 negz = -1;
3446 }
3447 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003448 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003449
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003450 /* JRH: The original logic here was to allocate the result value (z)
3451 as the longer of the two operands. However, there are some cases
3452 where the result is guaranteed to be shorter than that: AND of two
3453 positives, OR of two negatives: use the shorter number. AND with
3454 mixed signs: use the positive number. OR with mixed signs: use the
3455 negative number. After the transformations above, op will be '&'
3456 iff one of these cases applies, and mask will be non-0 for operands
3457 whose length should be ignored.
3458 */
3459
Christian Heimes90aa7642007-12-19 02:45:37 +00003460 size_a = Py_SIZE(a);
3461 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003462 size_z = op == '&'
3463 ? (maska
3464 ? size_b
3465 : (maskb ? size_a : MIN(size_a, size_b)))
3466 : MAX(size_a, size_b);
3467 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003468 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003469 Py_DECREF(a);
3470 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003471 return NULL;
3472 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003473
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003474 for (i = 0; i < size_z; ++i) {
3475 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3476 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3477 switch (op) {
3478 case '&': z->ob_digit[i] = diga & digb; break;
3479 case '|': z->ob_digit[i] = diga | digb; break;
3480 case '^': z->ob_digit[i] = diga ^ digb; break;
3481 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003482 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003483
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003484 Py_DECREF(a);
3485 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003486 z = long_normalize(z);
3487 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003488 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003489 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003490 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003491 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003492}
3493
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003494static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003495long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003496{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003497 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003498 CHECK_BINOP(a, b);
3499 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003500 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003501}
3502
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003503static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003504long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003505{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003506 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003507 CHECK_BINOP(a, b);
3508 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003509 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003510}
3511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003512static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003513long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003514{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003515 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003516 CHECK_BINOP(a, b);
3517 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003518 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003519}
3520
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003521static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003522long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003523{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003524 if (PyLong_CheckExact(v))
3525 Py_INCREF(v);
3526 else
3527 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003528 return v;
3529}
3530
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003531static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003532long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003533{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003534 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003535 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003536 if (result == -1.0 && PyErr_Occurred())
3537 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003538 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003539}
3540
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003541static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003542long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003543
Tim Peters6d6c1a32001-08-02 04:15:00 +00003544static PyObject *
3545long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3546{
3547 PyObject *x = NULL;
3548 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003549 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003550
Guido van Rossumbef14172001-08-29 15:47:46 +00003551 if (type != &PyLong_Type)
3552 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003553 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003554 &x, &base))
3555 return NULL;
3556 if (x == NULL)
3557 return PyLong_FromLong(0L);
3558 if (base == -909)
3559 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003560 else if (PyUnicode_Check(x))
3561 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3562 PyUnicode_GET_SIZE(x),
3563 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003564 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003565 /* Since PyLong_FromString doesn't have a length parameter,
3566 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003567 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003568 int size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003569 if (PyByteArray_Check(x))
3570 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003571 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003572 string = PyBytes_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003573 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003574 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003575 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003576 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003577 "invalid literal for int() with base %d: %R",
3578 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003579 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003580 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003581 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003582 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003583 else {
3584 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003585 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003586 return NULL;
3587 }
3588}
3589
Guido van Rossumbef14172001-08-29 15:47:46 +00003590/* Wimpy, slow approach to tp_new calls for subtypes of long:
3591 first create a regular long from whatever arguments we got,
3592 then allocate a subtype instance and initialize it from
3593 the regular long. The regular long is then thrown away.
3594*/
3595static PyObject *
3596long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3597{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003598 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003599 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003600
3601 assert(PyType_IsSubtype(type, &PyLong_Type));
3602 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3603 if (tmp == NULL)
3604 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003605 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003606 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003607 if (n < 0)
3608 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003609 newobj = (PyLongObject *)type->tp_alloc(type, n);
3610 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003611 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003612 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003613 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003614 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003615 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003616 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003617 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003618 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003619 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003620}
3621
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003622static PyObject *
3623long_getnewargs(PyLongObject *v)
3624{
3625 return Py_BuildValue("(N)", _PyLong_Copy(v));
3626}
3627
Guido van Rossumb43daf72007-08-01 18:08:08 +00003628static PyObject *
3629long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003630 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003631}
3632
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003633static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003634long__format__(PyObject *self, PyObject *args)
3635{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003636 PyObject *format_spec;
3637
3638 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3639 return NULL;
3640 return _PyLong_FormatAdvanced(self,
3641 PyUnicode_AS_UNICODE(format_spec),
3642 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003643}
3644
3645
3646static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003647long_round(PyObject *self, PyObject *args)
3648{
3649#define UNDEF_NDIGITS (-0x7fffffff) /* Unlikely ndigits value */
3650 int ndigits = UNDEF_NDIGITS;
3651 double x;
3652 PyObject *res;
3653
3654 if (!PyArg_ParseTuple(args, "|i", &ndigits))
3655 return NULL;
3656
3657 if (ndigits == UNDEF_NDIGITS)
3658 return long_long(self);
3659
3660 /* If called with two args, defer to float.__round__(). */
3661 x = PyLong_AsDouble(self);
3662 if (x == -1.0 && PyErr_Occurred())
3663 return NULL;
3664 self = PyFloat_FromDouble(x);
3665 if (self == NULL)
3666 return NULL;
3667 res = PyObject_CallMethod(self, "__round__", "i", ndigits);
3668 Py_DECREF(self);
3669 return res;
3670#undef UNDEF_NDIGITS
3671}
3672
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003673static PyObject *
3674long_sizeof(PyLongObject *v)
3675{
3676 Py_ssize_t res;
3677
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003678 res = sizeof(PyVarObject) + abs(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003679 return PyLong_FromSsize_t(res);
3680}
3681
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003682static const unsigned char BitLengthTable[32] = {
3683 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3684 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3685};
3686
3687static PyObject *
3688long_bit_length(PyLongObject *v)
3689{
3690 PyLongObject *result, *x, *y;
3691 Py_ssize_t ndigits, msd_bits = 0;
3692 digit msd;
3693
3694 assert(v != NULL);
3695 assert(PyLong_Check(v));
3696
3697 ndigits = ABS(Py_SIZE(v));
3698 if (ndigits == 0)
3699 return PyLong_FromLong(0);
3700
3701 msd = v->ob_digit[ndigits-1];
3702 while (msd >= 32) {
3703 msd_bits += 6;
3704 msd >>= 6;
3705 }
3706 msd_bits += (long)(BitLengthTable[msd]);
3707
3708 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3709 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3710
3711 /* expression above may overflow; use Python integers instead */
3712 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3713 if (result == NULL)
3714 return NULL;
3715 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3716 if (x == NULL)
3717 goto error;
3718 y = (PyLongObject *)long_mul(result, x);
3719 Py_DECREF(x);
3720 if (y == NULL)
3721 goto error;
3722 Py_DECREF(result);
3723 result = y;
3724
3725 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3726 if (x == NULL)
3727 goto error;
3728 y = (PyLongObject *)long_add(result, x);
3729 Py_DECREF(x);
3730 if (y == NULL)
3731 goto error;
3732 Py_DECREF(result);
3733 result = y;
3734
3735 return (PyObject *)result;
3736
3737error:
3738 Py_DECREF(result);
3739 return NULL;
3740}
3741
3742PyDoc_STRVAR(long_bit_length_doc,
3743"int.bit_length() -> int\n\
3744\n\
3745Number of bits necessary to represent self in binary.\n\
3746>>> bin(37)\n\
3747'0b100101'\n\
3748>>> (37).bit_length()\n\
37496");
3750
Christian Heimes53876d92008-04-19 00:31:39 +00003751#if 0
3752static PyObject *
3753long_is_finite(PyObject *v)
3754{
3755 Py_RETURN_TRUE;
3756}
3757#endif
3758
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003759static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003760 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3761 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003762 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3763 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003764#if 0
3765 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3766 "Returns always True."},
3767#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003768 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3769 "Truncating an Integral returns itself."},
3770 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3771 "Flooring an Integral returns itself."},
3772 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3773 "Ceiling of an Integral returns itself."},
3774 {"__round__", (PyCFunction)long_round, METH_VARARGS,
3775 "Rounding an Integral returns itself.\n"
3776 "Rounding with an ndigits arguments defers to float.__round__."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003777 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003778 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003779 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3780 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003781 {NULL, NULL} /* sentinel */
3782};
3783
Guido van Rossumb43daf72007-08-01 18:08:08 +00003784static PyGetSetDef long_getset[] = {
3785 {"real",
3786 (getter)long_long, (setter)NULL,
3787 "the real part of a complex number",
3788 NULL},
3789 {"imag",
3790 (getter)long_getN, (setter)NULL,
3791 "the imaginary part of a complex number",
3792 (void*)0},
3793 {"numerator",
3794 (getter)long_long, (setter)NULL,
3795 "the numerator of a rational number in lowest terms",
3796 NULL},
3797 {"denominator",
3798 (getter)long_getN, (setter)NULL,
3799 "the denominator of a rational number in lowest terms",
3800 (void*)1},
3801 {NULL} /* Sentinel */
3802};
3803
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003804PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003805"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003806\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003807Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003808point argument will be truncated towards zero (this does not include a\n\
3809string representation of a floating point number!) When converting a\n\
3810string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003811converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003812
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003813static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003814 (binaryfunc) long_add, /*nb_add*/
3815 (binaryfunc) long_sub, /*nb_subtract*/
3816 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003817 long_mod, /*nb_remainder*/
3818 long_divmod, /*nb_divmod*/
3819 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003820 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003821 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003822 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003823 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003824 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003825 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003826 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003827 long_and, /*nb_and*/
3828 long_xor, /*nb_xor*/
3829 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003830 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00003831 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003832 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003833 0, /* nb_inplace_add */
3834 0, /* nb_inplace_subtract */
3835 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003836 0, /* nb_inplace_remainder */
3837 0, /* nb_inplace_power */
3838 0, /* nb_inplace_lshift */
3839 0, /* nb_inplace_rshift */
3840 0, /* nb_inplace_and */
3841 0, /* nb_inplace_xor */
3842 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003843 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003844 long_true_divide, /* nb_true_divide */
3845 0, /* nb_inplace_floor_divide */
3846 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003847 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003848};
3849
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003850PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003851 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003852 "int", /* tp_name */
3853 /* See _PyLong_New for why this isn't
3854 sizeof(PyLongObject) - sizeof(digit) */
3855 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003856 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003857 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003858 0, /* tp_print */
3859 0, /* tp_getattr */
3860 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003861 0, /* tp_compare */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003862 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003863 &long_as_number, /* tp_as_number */
3864 0, /* tp_as_sequence */
3865 0, /* tp_as_mapping */
3866 (hashfunc)long_hash, /* tp_hash */
3867 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003868 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003869 PyObject_GenericGetAttr, /* tp_getattro */
3870 0, /* tp_setattro */
3871 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003872 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3873 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003874 long_doc, /* tp_doc */
3875 0, /* tp_traverse */
3876 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003877 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003878 0, /* tp_weaklistoffset */
3879 0, /* tp_iter */
3880 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003881 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003882 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003883 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003884 0, /* tp_base */
3885 0, /* tp_dict */
3886 0, /* tp_descr_get */
3887 0, /* tp_descr_set */
3888 0, /* tp_dictoffset */
3889 0, /* tp_init */
3890 0, /* tp_alloc */
3891 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00003892 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003893};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003894
3895int
3896_PyLong_Init(void)
3897{
3898#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003899 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003900 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003901
3902 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
3903 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
3904 if (Py_TYPE(v) == &PyLong_Type) {
3905 /* The element is already initialized, most likely
3906 * the Python interpreter was initialized before.
3907 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00003908 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003909 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003910
Christian Heimes48aa4b12008-02-01 16:56:30 +00003911 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
3912 _Py_NewReference(op);
3913 /* _Py_NewReference sets the ref count to 1 but
3914 * the ref count might be larger. Set the refcnt
3915 * to the original refcnt + 1 */
3916 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003917 assert(Py_SIZE(op) == size);
3918 assert(v->ob_digit[0] == abs(ival));
3919 }
3920 else {
3921 PyObject_INIT(v, &PyLong_Type);
3922 }
3923 Py_SIZE(v) = size;
3924 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003925 }
3926#endif
3927 return 1;
3928}
3929
3930void
3931PyLong_Fini(void)
3932{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003933 /* Integers are currently statically allocated. Py_DECREF is not
3934 needed, but Python must forget about the reference or multiple
3935 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003936#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003937 int i;
3938 PyLongObject *v = small_ints;
3939 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
3940 _Py_DEC_REFTOTAL;
3941 _Py_ForgetReference((PyObject*)v);
3942 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003943#endif
3944}