blob: e2ab078b9061afe393bfebfb43b4010586717782 [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) {
Mark Dickinson21776072009-02-10 16:13:25 +0000789 PyErr_SetString(PyExc_OverflowError,
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{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002277 unsigned 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)
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002297 /* The following loop produces a C unsigned long x such that x is
2298 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002299 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 */
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002302 x = ((x << PyLong_SHIFT) & ~PyLong_MASK) |
2303 ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002304 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002305 /* If the addition above overflowed we compensate by
2306 incrementing. This preserves the value modulo
2307 ULONG_MAX. */
2308 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002309 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002310 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002311#undef LONG_BIT_PyLong_SHIFT
Guido van Rossum9bfef441993-03-29 10:43:31 +00002312 x = x * sign;
2313 if (x == -1)
2314 x = -2;
2315 return x;
2316}
2317
2318
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319/* Add the absolute values of two long integers. */
2320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002321static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002322x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002323{
Christian Heimes90aa7642007-12-19 02:45:37 +00002324 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002325 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002326 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002327 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002328
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002329 /* Ensure a is the larger of the two: */
2330 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002331 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002332 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002333 size_a = size_b;
2334 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002335 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002336 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002337 if (z == NULL)
2338 return NULL;
2339 for (i = 0; i < size_b; ++i) {
2340 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002341 z->ob_digit[i] = carry & PyLong_MASK;
2342 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002343 }
2344 for (; i < size_a; ++i) {
2345 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002346 z->ob_digit[i] = carry & PyLong_MASK;
2347 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002348 }
2349 z->ob_digit[i] = carry;
2350 return long_normalize(z);
2351}
2352
2353/* Subtract the absolute values of two integers. */
2354
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002355static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002356x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357{
Christian Heimes90aa7642007-12-19 02:45:37 +00002358 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002359 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002360 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002361 int sign = 1;
2362 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002363
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364 /* Ensure a is the larger of the two: */
2365 if (size_a < size_b) {
2366 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002367 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002368 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002369 size_a = size_b;
2370 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002371 }
2372 else if (size_a == size_b) {
2373 /* Find highest digit where a and b differ: */
2374 i = size_a;
2375 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2376 ;
2377 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002378 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002379 if (a->ob_digit[i] < b->ob_digit[i]) {
2380 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002381 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382 }
2383 size_a = size_b = i+1;
2384 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002385 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002386 if (z == NULL)
2387 return NULL;
2388 for (i = 0; i < size_b; ++i) {
2389 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002390 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002391 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002392 z->ob_digit[i] = borrow & PyLong_MASK;
2393 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002394 borrow &= 1; /* Keep only one sign bit */
2395 }
2396 for (; i < size_a; ++i) {
2397 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002398 z->ob_digit[i] = borrow & PyLong_MASK;
2399 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002400 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002401 }
2402 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002403 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002404 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002405 return long_normalize(z);
2406}
2407
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002408static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002409long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002410{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002411 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002412
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002413 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002414
Christian Heimes90aa7642007-12-19 02:45:37 +00002415 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002416 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002417 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002418 return result;
2419 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002420 if (Py_SIZE(a) < 0) {
2421 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002422 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002423 if (z != NULL && Py_SIZE(z) != 0)
2424 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002425 }
2426 else
2427 z = x_sub(b, a);
2428 }
2429 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002430 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002431 z = x_sub(a, b);
2432 else
2433 z = x_add(a, b);
2434 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002435 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002436}
2437
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002438static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002439long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002440{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002441 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002442
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002443 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002444
Christian Heimes90aa7642007-12-19 02:45:37 +00002445 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002446 PyObject* r;
2447 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002448 return r;
2449 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002450 if (Py_SIZE(a) < 0) {
2451 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002452 z = x_sub(a, b);
2453 else
2454 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002455 if (z != NULL && Py_SIZE(z) != 0)
2456 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002457 }
2458 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002459 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002460 z = x_add(a, b);
2461 else
2462 z = x_sub(a, b);
2463 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002464 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002465}
2466
Tim Peters5af4e6c2002-08-12 02:31:19 +00002467/* Grade school multiplication, ignoring the signs.
2468 * Returns the absolute value of the product, or NULL if error.
2469 */
2470static PyLongObject *
2471x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002472{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002473 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002474 Py_ssize_t size_a = ABS(Py_SIZE(a));
2475 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002476 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002477
Tim Peters5af4e6c2002-08-12 02:31:19 +00002478 z = _PyLong_New(size_a + size_b);
2479 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002480 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002481
Christian Heimes90aa7642007-12-19 02:45:37 +00002482 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002483 if (a == b) {
2484 /* Efficient squaring per HAC, Algorithm 14.16:
2485 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2486 * Gives slightly less than a 2x speedup when a == b,
2487 * via exploiting that each entry in the multiplication
2488 * pyramid appears twice (except for the size_a squares).
2489 */
2490 for (i = 0; i < size_a; ++i) {
2491 twodigits carry;
2492 twodigits f = a->ob_digit[i];
2493 digit *pz = z->ob_digit + (i << 1);
2494 digit *pa = a->ob_digit + i + 1;
2495 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002496
Tim Peters0973b992004-08-29 22:16:50 +00002497 SIGCHECK({
2498 Py_DECREF(z);
2499 return NULL;
2500 })
2501
2502 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002503 *pz++ = (digit)(carry & PyLong_MASK);
2504 carry >>= PyLong_SHIFT;
2505 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002506
2507 /* Now f is added in twice in each column of the
2508 * pyramid it appears. Same as adding f<<1 once.
2509 */
2510 f <<= 1;
2511 while (pa < paend) {
2512 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002513 *pz++ = (digit)(carry & PyLong_MASK);
2514 carry >>= PyLong_SHIFT;
2515 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002516 }
2517 if (carry) {
2518 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002519 *pz++ = (digit)(carry & PyLong_MASK);
2520 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002521 }
2522 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002523 *pz += (digit)(carry & PyLong_MASK);
2524 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002525 }
Tim Peters0973b992004-08-29 22:16:50 +00002526 }
2527 else { /* a is not the same as b -- gradeschool long mult */
2528 for (i = 0; i < size_a; ++i) {
2529 twodigits carry = 0;
2530 twodigits f = a->ob_digit[i];
2531 digit *pz = z->ob_digit + i;
2532 digit *pb = b->ob_digit;
2533 digit *pbend = b->ob_digit + size_b;
2534
2535 SIGCHECK({
2536 Py_DECREF(z);
2537 return NULL;
2538 })
2539
2540 while (pb < pbend) {
2541 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002542 *pz++ = (digit)(carry & PyLong_MASK);
2543 carry >>= PyLong_SHIFT;
2544 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002545 }
2546 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002547 *pz += (digit)(carry & PyLong_MASK);
2548 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002549 }
2550 }
Tim Peters44121a62002-08-12 06:17:58 +00002551 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002552}
2553
2554/* A helper for Karatsuba multiplication (k_mul).
2555 Takes a long "n" and an integer "size" representing the place to
2556 split, and sets low and high such that abs(n) == (high << size) + low,
2557 viewing the shift as being by digits. The sign bit is ignored, and
2558 the return values are >= 0.
2559 Returns 0 on success, -1 on failure.
2560*/
2561static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002562kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002563{
2564 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002565 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002566 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002567
2568 size_lo = MIN(size_n, size);
2569 size_hi = size_n - size_lo;
2570
2571 if ((hi = _PyLong_New(size_hi)) == NULL)
2572 return -1;
2573 if ((lo = _PyLong_New(size_lo)) == NULL) {
2574 Py_DECREF(hi);
2575 return -1;
2576 }
2577
2578 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2579 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2580
2581 *high = long_normalize(hi);
2582 *low = long_normalize(lo);
2583 return 0;
2584}
2585
Tim Peters60004642002-08-12 22:01:34 +00002586static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2587
Tim Peters5af4e6c2002-08-12 02:31:19 +00002588/* Karatsuba multiplication. Ignores the input signs, and returns the
2589 * absolute value of the product (or NULL if error).
2590 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2591 */
2592static PyLongObject *
2593k_mul(PyLongObject *a, PyLongObject *b)
2594{
Christian Heimes90aa7642007-12-19 02:45:37 +00002595 Py_ssize_t asize = ABS(Py_SIZE(a));
2596 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002597 PyLongObject *ah = NULL;
2598 PyLongObject *al = NULL;
2599 PyLongObject *bh = NULL;
2600 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002601 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002602 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002603 Py_ssize_t shift; /* the number of digits we split off */
2604 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002605
Tim Peters5af4e6c2002-08-12 02:31:19 +00002606 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2607 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2608 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002609 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002610 * By picking X to be a power of 2, "*X" is just shifting, and it's
2611 * been reduced to 3 multiplies on numbers half the size.
2612 */
2613
Tim Petersfc07e562002-08-12 02:54:10 +00002614 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002615 * is largest.
2616 */
Tim Peters738eda72002-08-12 15:08:20 +00002617 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002618 t1 = a;
2619 a = b;
2620 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002621
2622 i = asize;
2623 asize = bsize;
2624 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002625 }
2626
2627 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002628 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2629 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002630 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002631 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002632 else
2633 return x_mul(a, b);
2634 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002635
Tim Peters60004642002-08-12 22:01:34 +00002636 /* If a is small compared to b, splitting on b gives a degenerate
2637 * case with ah==0, and Karatsuba may be (even much) less efficient
2638 * than "grade school" then. However, we can still win, by viewing
2639 * b as a string of "big digits", each of width a->ob_size. That
2640 * leads to a sequence of balanced calls to k_mul.
2641 */
2642 if (2 * asize <= bsize)
2643 return k_lopsided_mul(a, b);
2644
Tim Petersd6974a52002-08-13 20:37:51 +00002645 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002646 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002647 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002648 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002649
Tim Peters0973b992004-08-29 22:16:50 +00002650 if (a == b) {
2651 bh = ah;
2652 bl = al;
2653 Py_INCREF(bh);
2654 Py_INCREF(bl);
2655 }
2656 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002657
Tim Petersd64c1de2002-08-12 17:36:03 +00002658 /* The plan:
2659 * 1. Allocate result space (asize + bsize digits: that's always
2660 * enough).
2661 * 2. Compute ah*bh, and copy into result at 2*shift.
2662 * 3. Compute al*bl, and copy into result at 0. Note that this
2663 * can't overlap with #2.
2664 * 4. Subtract al*bl from the result, starting at shift. This may
2665 * underflow (borrow out of the high digit), but we don't care:
2666 * we're effectively doing unsigned arithmetic mod
2667 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2668 * borrows and carries out of the high digit can be ignored.
2669 * 5. Subtract ah*bh from the result, starting at shift.
2670 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2671 * at shift.
2672 */
2673
2674 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002675 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676 if (ret == NULL) goto fail;
2677#ifdef Py_DEBUG
2678 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002679 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002680#endif
Tim Peters44121a62002-08-12 06:17:58 +00002681
Tim Petersd64c1de2002-08-12 17:36:03 +00002682 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002683 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002684 assert(Py_SIZE(t1) >= 0);
2685 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002686 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002687 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002688
2689 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002690 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002691 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002692 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002693 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002694
Tim Petersd64c1de2002-08-12 17:36:03 +00002695 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002696 if ((t2 = k_mul(al, bl)) == NULL) {
2697 Py_DECREF(t1);
2698 goto fail;
2699 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002700 assert(Py_SIZE(t2) >= 0);
2701 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2702 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002703
2704 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002705 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002706 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002707 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002708
Tim Petersd64c1de2002-08-12 17:36:03 +00002709 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2710 * because it's fresher in cache.
2711 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002712 i = Py_SIZE(ret) - shift; /* # digits after shift */
2713 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002714 Py_DECREF(t2);
2715
Christian Heimes90aa7642007-12-19 02:45:37 +00002716 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002717 Py_DECREF(t1);
2718
Tim Petersd64c1de2002-08-12 17:36:03 +00002719 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002720 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2721 Py_DECREF(ah);
2722 Py_DECREF(al);
2723 ah = al = NULL;
2724
Tim Peters0973b992004-08-29 22:16:50 +00002725 if (a == b) {
2726 t2 = t1;
2727 Py_INCREF(t2);
2728 }
2729 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002730 Py_DECREF(t1);
2731 goto fail;
2732 }
2733 Py_DECREF(bh);
2734 Py_DECREF(bl);
2735 bh = bl = NULL;
2736
Tim Peters738eda72002-08-12 15:08:20 +00002737 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002738 Py_DECREF(t1);
2739 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002740 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002741 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002742
Tim Petersd6974a52002-08-13 20:37:51 +00002743 /* Add t3. It's not obvious why we can't run out of room here.
2744 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002745 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002746 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002747 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002748
Tim Peters5af4e6c2002-08-12 02:31:19 +00002749 return long_normalize(ret);
2750
2751 fail:
2752 Py_XDECREF(ret);
2753 Py_XDECREF(ah);
2754 Py_XDECREF(al);
2755 Py_XDECREF(bh);
2756 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002757 return NULL;
2758}
2759
Tim Petersd6974a52002-08-13 20:37:51 +00002760/* (*) Why adding t3 can't "run out of room" above.
2761
Tim Petersab86c2b2002-08-15 20:06:00 +00002762Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2763to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002764
Tim Petersab86c2b2002-08-15 20:06:00 +000027651. For any integer i, i = c(i/2) + f(i/2). In particular,
2766 bsize = c(bsize/2) + f(bsize/2).
27672. shift = f(bsize/2)
27683. asize <= bsize
27694. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2770 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002771
Tim Petersab86c2b2002-08-15 20:06:00 +00002772We allocated asize + bsize result digits, and add t3 into them at an offset
2773of shift. This leaves asize+bsize-shift allocated digit positions for t3
2774to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2775asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002776
Tim Petersab86c2b2002-08-15 20:06:00 +00002777bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2778at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002779
Tim Petersab86c2b2002-08-15 20:06:00 +00002780If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2781digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2782most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002783
Tim Petersab86c2b2002-08-15 20:06:00 +00002784The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002785
Tim Petersab86c2b2002-08-15 20:06:00 +00002786 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002787
Tim Petersab86c2b2002-08-15 20:06:00 +00002788and we have asize + c(bsize/2) available digit positions. We need to show
2789this is always enough. An instance of c(bsize/2) cancels out in both, so
2790the question reduces to whether asize digits is enough to hold
2791(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2792then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2793asize 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 +00002794digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002795asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002796c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2797is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2798bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002799
Tim Peters48d52c02002-08-14 17:07:32 +00002800Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2801clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2802ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002803*/
2804
Tim Peters60004642002-08-12 22:01:34 +00002805/* b has at least twice the digits of a, and a is big enough that Karatsuba
2806 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2807 * of slices, each with a->ob_size digits, and multiply the slices by a,
2808 * one at a time. This gives k_mul balanced inputs to work with, and is
2809 * also cache-friendly (we compute one double-width slice of the result
2810 * at a time, then move on, never bactracking except for the helpful
2811 * single-width slice overlap between successive partial sums).
2812 */
2813static PyLongObject *
2814k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2815{
Christian Heimes90aa7642007-12-19 02:45:37 +00002816 const Py_ssize_t asize = ABS(Py_SIZE(a));
2817 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002818 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002819 PyLongObject *ret;
2820 PyLongObject *bslice = NULL;
2821
2822 assert(asize > KARATSUBA_CUTOFF);
2823 assert(2 * asize <= bsize);
2824
2825 /* Allocate result space, and zero it out. */
2826 ret = _PyLong_New(asize + bsize);
2827 if (ret == NULL)
2828 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002829 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002830
2831 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002832 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002833 if (bslice == NULL)
2834 goto fail;
2835
2836 nbdone = 0;
2837 while (bsize > 0) {
2838 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002839 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002840
2841 /* Multiply the next slice of b by a. */
2842 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2843 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002844 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002845 product = k_mul(a, bslice);
2846 if (product == NULL)
2847 goto fail;
2848
2849 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002850 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2851 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002852 Py_DECREF(product);
2853
2854 bsize -= nbtouse;
2855 nbdone += nbtouse;
2856 }
2857
2858 Py_DECREF(bslice);
2859 return long_normalize(ret);
2860
2861 fail:
2862 Py_DECREF(ret);
2863 Py_XDECREF(bslice);
2864 return NULL;
2865}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002866
2867static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002868long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002869{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002870 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002871
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002872 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002873
Christian Heimes90aa7642007-12-19 02:45:37 +00002874 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002875 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002876 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002877 return r;
2878 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002879
Tim Petersd64c1de2002-08-12 17:36:03 +00002880 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002881 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002882 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002883 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002884 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002885}
2886
Guido van Rossume32e0141992-01-19 16:31:05 +00002887/* The / and % operators are now defined in terms of divmod().
2888 The expression a mod b has the value a - b*floor(a/b).
2889 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002890 |a| by |b|, with the sign of a. This is also expressed
2891 as a - b*trunc(a/b), if trunc truncates towards zero.
2892 Some examples:
2893 a b a rem b a mod b
2894 13 10 3 3
2895 -13 10 -3 7
2896 13 -10 3 -7
2897 -13 -10 -3 -3
2898 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002899 have different signs. We then subtract one from the 'div'
2900 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002901
Tim Peters47e52ee2004-08-30 02:44:38 +00002902/* Compute
2903 * *pdiv, *pmod = divmod(v, w)
2904 * NULL can be passed for pdiv or pmod, in which case that part of
2905 * the result is simply thrown away. The caller owns a reference to
2906 * each of these it requests (does not pass NULL for).
2907 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002908static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002909l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002910 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002911{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002912 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002913
Guido van Rossume32e0141992-01-19 16:31:05 +00002914 if (long_divrem(v, w, &div, &mod) < 0)
2915 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002916 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2917 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002918 PyLongObject *temp;
2919 PyLongObject *one;
2920 temp = (PyLongObject *) long_add(mod, w);
2921 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002922 mod = temp;
2923 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002924 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002925 return -1;
2926 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002927 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002928 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002929 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2930 Py_DECREF(mod);
2931 Py_DECREF(div);
2932 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002933 return -1;
2934 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002935 Py_DECREF(one);
2936 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002937 div = temp;
2938 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002939 if (pdiv != NULL)
2940 *pdiv = div;
2941 else
2942 Py_DECREF(div);
2943
2944 if (pmod != NULL)
2945 *pmod = mod;
2946 else
2947 Py_DECREF(mod);
2948
Guido van Rossume32e0141992-01-19 16:31:05 +00002949 return 0;
2950}
2951
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002952static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002953long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002954{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002955 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002956
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002957 CHECK_BINOP(a, b);
2958 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002959 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002960 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002961}
2962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002963static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002964long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002965{
Tim Peterse2a60002001-09-04 06:17:36 +00002966 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002967 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002968
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002969 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002970 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2971 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002972 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002973 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002974 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002975 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2976 but should really be set correctly after sucessful calls to
2977 _PyLong_AsScaledDouble() */
2978 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002979
2980 if (bd == 0.0) {
2981 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002982 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002983 return NULL;
2984 }
2985
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002986 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002987 ad /= bd; /* overflow/underflow impossible here */
2988 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002989 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002990 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002991 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002992 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002993 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002994 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002995 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002996 goto overflow;
2997 return PyFloat_FromDouble(ad);
2998
2999overflow:
3000 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003001 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00003002 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003003
Tim Peters20dab9f2001-09-04 05:31:47 +00003004}
3005
3006static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003007long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003008{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003009 PyLongObject *mod;
3010
3011 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003012
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003013 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003014 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003015 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003016}
3017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003018static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003019long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003020{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003021 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003022 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003023
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003024 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003025
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003026 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003027 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003028 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003029 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003030 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003031 PyTuple_SetItem(z, 0, (PyObject *) div);
3032 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003033 }
3034 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003035 Py_DECREF(div);
3036 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003037 }
3038 return z;
3039}
3040
Tim Peters47e52ee2004-08-30 02:44:38 +00003041/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003042static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003043long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003044{
Tim Peters47e52ee2004-08-30 02:44:38 +00003045 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3046 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003047
Tim Peters47e52ee2004-08-30 02:44:38 +00003048 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003049 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003050 PyLongObject *temp = NULL;
3051
3052 /* 5-ary values. If the exponent is large enough, table is
3053 * precomputed so that table[i] == a**i % c for i in range(32).
3054 */
3055 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3056 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3057
3058 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003059 CHECK_BINOP(v, w);
3060 a = (PyLongObject*)v; Py_INCREF(a);
3061 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003062 if (PyLong_Check(x)) {
3063 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003064 Py_INCREF(x);
3065 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003066 else if (x == Py_None)
3067 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003068 else {
3069 Py_DECREF(a);
3070 Py_DECREF(b);
3071 Py_INCREF(Py_NotImplemented);
3072 return Py_NotImplemented;
3073 }
Tim Peters4c483c42001-09-05 06:24:58 +00003074
Christian Heimes90aa7642007-12-19 02:45:37 +00003075 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003076 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003077 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003078 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003079 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003080 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003081 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003082 /* else return a float. This works because we know
3083 that this calls float_pow() which converts its
3084 arguments to double. */
3085 Py_DECREF(a);
3086 Py_DECREF(b);
3087 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003088 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003089 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003090
3091 if (c) {
3092 /* if modulus == 0:
3093 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003094 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003095 PyErr_SetString(PyExc_ValueError,
3096 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003097 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003098 }
3099
3100 /* if modulus < 0:
3101 negativeOutput = True
3102 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003103 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003104 negativeOutput = 1;
3105 temp = (PyLongObject *)_PyLong_Copy(c);
3106 if (temp == NULL)
3107 goto Error;
3108 Py_DECREF(c);
3109 c = temp;
3110 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003111 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003112 }
3113
3114 /* if modulus == 1:
3115 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003116 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003117 z = (PyLongObject *)PyLong_FromLong(0L);
3118 goto Done;
3119 }
3120
3121 /* if base < 0:
3122 base = base % modulus
3123 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003124 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003125 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003126 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003127 Py_DECREF(a);
3128 a = temp;
3129 temp = NULL;
3130 }
3131 }
3132
3133 /* At this point a, b, and c are guaranteed non-negative UNLESS
3134 c is NULL, in which case a may be negative. */
3135
3136 z = (PyLongObject *)PyLong_FromLong(1L);
3137 if (z == NULL)
3138 goto Error;
3139
3140 /* Perform a modular reduction, X = X % c, but leave X alone if c
3141 * is NULL.
3142 */
3143#define REDUCE(X) \
3144 if (c != NULL) { \
3145 if (l_divmod(X, c, NULL, &temp) < 0) \
3146 goto Error; \
3147 Py_XDECREF(X); \
3148 X = temp; \
3149 temp = NULL; \
3150 }
3151
3152 /* Multiply two values, then reduce the result:
3153 result = X*Y % c. If c is NULL, skip the mod. */
3154#define MULT(X, Y, result) \
3155{ \
3156 temp = (PyLongObject *)long_mul(X, Y); \
3157 if (temp == NULL) \
3158 goto Error; \
3159 Py_XDECREF(result); \
3160 result = temp; \
3161 temp = NULL; \
3162 REDUCE(result) \
3163}
3164
Christian Heimes90aa7642007-12-19 02:45:37 +00003165 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003166 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3167 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003168 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003169 digit bi = b->ob_digit[i];
3170
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003171 for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003172 MULT(z, z, z)
3173 if (bi & j)
3174 MULT(z, a, z)
3175 }
3176 }
3177 }
3178 else {
3179 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3180 Py_INCREF(z); /* still holds 1L */
3181 table[0] = z;
3182 for (i = 1; i < 32; ++i)
3183 MULT(table[i-1], a, table[i])
3184
Christian Heimes90aa7642007-12-19 02:45:37 +00003185 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003186 const digit bi = b->ob_digit[i];
3187
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003188 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003189 const int index = (bi >> j) & 0x1f;
3190 for (k = 0; k < 5; ++k)
3191 MULT(z, z, z)
3192 if (index)
3193 MULT(z, table[index], z)
3194 }
3195 }
3196 }
3197
Christian Heimes90aa7642007-12-19 02:45:37 +00003198 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003199 temp = (PyLongObject *)long_sub(z, c);
3200 if (temp == NULL)
3201 goto Error;
3202 Py_DECREF(z);
3203 z = temp;
3204 temp = NULL;
3205 }
3206 goto Done;
3207
3208 Error:
3209 if (z != NULL) {
3210 Py_DECREF(z);
3211 z = NULL;
3212 }
3213 /* fall through */
3214 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003215 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003216 for (i = 0; i < 32; ++i)
3217 Py_XDECREF(table[i]);
3218 }
Tim Petersde7990b2005-07-17 23:45:23 +00003219 Py_DECREF(a);
3220 Py_DECREF(b);
3221 Py_XDECREF(c);
3222 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003223 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003224}
3225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003226static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003227long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003228{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003229 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003230 PyLongObject *x;
3231 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003232 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003233 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003234 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003235 if (w == NULL)
3236 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003237 x = (PyLongObject *) long_add(v, w);
3238 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003239 if (x == NULL)
3240 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003241 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003242 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003243}
3244
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003245static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003246long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003247{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003248 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003249 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003250 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003251 z = (PyLongObject *)_PyLong_Copy(v);
3252 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003253 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003254 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003255}
3256
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003257static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003258long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003259{
Christian Heimes90aa7642007-12-19 02:45:37 +00003260 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003261 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003262 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003263 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003264}
3265
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003266static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003267long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003268{
Christian Heimes90aa7642007-12-19 02:45:37 +00003269 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003270}
3271
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003272static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003273long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003274{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003275 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003276 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003277 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003278 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003279
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003280 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003281
Christian Heimes90aa7642007-12-19 02:45:37 +00003282 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003283 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003284 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003285 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003286 if (a1 == NULL)
3287 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003288 a2 = (PyLongObject *) long_rshift(a1, b);
3289 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003290 if (a2 == NULL)
3291 goto rshift_error;
3292 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003293 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003294 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003295 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003296
Neil Schemenauerba872e22001-01-04 01:46:03 +00003297 shiftby = PyLong_AsLong((PyObject *)b);
3298 if (shiftby == -1L && PyErr_Occurred())
3299 goto rshift_error;
3300 if (shiftby < 0) {
3301 PyErr_SetString(PyExc_ValueError,
3302 "negative shift count");
3303 goto rshift_error;
3304 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003305 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003306 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003307 if (newsize <= 0)
3308 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003309 loshift = shiftby % PyLong_SHIFT;
3310 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003311 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003312 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003313 z = _PyLong_New(newsize);
3314 if (z == NULL)
3315 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003316 if (Py_SIZE(a) < 0)
3317 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003318 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3319 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3320 if (i+1 < newsize)
3321 z->ob_digit[i] |=
3322 (a->ob_digit[j+1] << hishift) & himask;
3323 }
3324 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003325 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003326rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003327 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003328
Guido van Rossumc6913e71991-11-19 20:26:46 +00003329}
3330
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003331static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003332long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003333{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003334 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003335 PyLongObject *a = (PyLongObject*)v;
3336 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003337 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003338 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003339 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003340 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003342 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003343
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003344 shiftby = PyLong_AsLong((PyObject *)b);
3345 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003346 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003347 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003348 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003349 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003350 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003351 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003352 PyErr_SetString(PyExc_ValueError,
3353 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003354 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003355 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003356 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3357 wordshift = (int)shiftby / PyLong_SHIFT;
3358 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003359
Christian Heimes90aa7642007-12-19 02:45:37 +00003360 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003361 newsize = oldsize + wordshift;
3362 if (remshift)
3363 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003364 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003365 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003366 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003367 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003368 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003369 for (i = 0; i < wordshift; i++)
3370 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003371 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003372 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003373 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003374 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3375 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003376 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003377 if (remshift)
3378 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003379 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003380 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003381 z = long_normalize(z);
3382lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003383 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003384}
3385
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003386
3387/* Bitwise and/xor/or operations */
3388
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003389static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003390long_bitwise(PyLongObject *a,
3391 int op, /* '&', '|', '^' */
3392 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003393{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003394 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003395 int negz;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003396 Py_ssize_t size_a, size_b, size_z;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003397 PyLongObject *z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003398 int i;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003399 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003400 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003401
Christian Heimes90aa7642007-12-19 02:45:37 +00003402 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003403 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003404 if (a == NULL)
3405 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003406 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003407 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003408 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003409 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003410 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003411 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003412 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003414 if (b == NULL) {
3415 Py_DECREF(a);
3416 return NULL;
3417 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003418 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003419 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003420 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003421 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003422 maskb = 0;
3423 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003424
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003425 negz = 0;
3426 switch (op) {
3427 case '^':
3428 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003429 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003430 negz = -1;
3431 }
3432 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003433 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003434 if (maska && maskb) {
3435 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003436 maska ^= PyLong_MASK;
3437 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003438 negz = -1;
3439 }
3440 break;
3441 case '|':
3442 if (maska || maskb) {
3443 op = '&';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003444 maska ^= PyLong_MASK;
3445 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003446 negz = -1;
3447 }
3448 break;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003449 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003450
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003451 /* JRH: The original logic here was to allocate the result value (z)
3452 as the longer of the two operands. However, there are some cases
3453 where the result is guaranteed to be shorter than that: AND of two
3454 positives, OR of two negatives: use the shorter number. AND with
3455 mixed signs: use the positive number. OR with mixed signs: use the
3456 negative number. After the transformations above, op will be '&'
3457 iff one of these cases applies, and mask will be non-0 for operands
3458 whose length should be ignored.
3459 */
3460
Christian Heimes90aa7642007-12-19 02:45:37 +00003461 size_a = Py_SIZE(a);
3462 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003463 size_z = op == '&'
3464 ? (maska
3465 ? size_b
3466 : (maskb ? size_a : MIN(size_a, size_b)))
3467 : MAX(size_a, size_b);
3468 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003469 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003470 Py_DECREF(a);
3471 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003472 return NULL;
3473 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003474
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003475 for (i = 0; i < size_z; ++i) {
3476 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3477 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3478 switch (op) {
3479 case '&': z->ob_digit[i] = diga & digb; break;
3480 case '|': z->ob_digit[i] = diga | digb; break;
3481 case '^': z->ob_digit[i] = diga ^ digb; break;
3482 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003483 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003484
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003485 Py_DECREF(a);
3486 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003487 z = long_normalize(z);
3488 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003489 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003490 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003491 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003492 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003493}
3494
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003495static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003496long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003497{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003498 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003499 CHECK_BINOP(a, b);
3500 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003501 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003502}
3503
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003504static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003505long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003506{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003507 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003508 CHECK_BINOP(a, b);
3509 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003510 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003511}
3512
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003513static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003514long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003515{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003516 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003517 CHECK_BINOP(a, b);
3518 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003519 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003520}
3521
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003522static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003523long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003524{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003525 if (PyLong_CheckExact(v))
3526 Py_INCREF(v);
3527 else
3528 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003529 return v;
3530}
3531
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003532static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003533long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003534{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003535 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003536 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003537 if (result == -1.0 && PyErr_Occurred())
3538 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003539 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003540}
3541
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003542static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003543long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003544
Tim Peters6d6c1a32001-08-02 04:15:00 +00003545static PyObject *
3546long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3547{
3548 PyObject *x = NULL;
3549 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003550 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003551
Guido van Rossumbef14172001-08-29 15:47:46 +00003552 if (type != &PyLong_Type)
3553 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003554 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003555 &x, &base))
3556 return NULL;
3557 if (x == NULL)
3558 return PyLong_FromLong(0L);
3559 if (base == -909)
3560 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003561 else if (PyUnicode_Check(x))
3562 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3563 PyUnicode_GET_SIZE(x),
3564 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003565 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003566 /* Since PyLong_FromString doesn't have a length parameter,
3567 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003568 char *string;
Christian Heimes90aa7642007-12-19 02:45:37 +00003569 int size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003570 if (PyByteArray_Check(x))
3571 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003572 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003573 string = PyBytes_AS_STRING(x);
Guido van Rossum4581ae52007-05-22 21:56:47 +00003574 if (strlen(string) != size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003575 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003576 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003577 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003578 "invalid literal for int() with base %d: %R",
3579 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003580 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003581 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003582 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003583 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003584 else {
3585 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003586 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003587 return NULL;
3588 }
3589}
3590
Guido van Rossumbef14172001-08-29 15:47:46 +00003591/* Wimpy, slow approach to tp_new calls for subtypes of long:
3592 first create a regular long from whatever arguments we got,
3593 then allocate a subtype instance and initialize it from
3594 the regular long. The regular long is then thrown away.
3595*/
3596static PyObject *
3597long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3598{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003599 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003600 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003601
3602 assert(PyType_IsSubtype(type, &PyLong_Type));
3603 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3604 if (tmp == NULL)
3605 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003606 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003607 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003608 if (n < 0)
3609 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003610 newobj = (PyLongObject *)type->tp_alloc(type, n);
3611 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003612 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003613 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003614 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003615 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003616 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003617 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003618 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003619 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003620 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003621}
3622
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003623static PyObject *
3624long_getnewargs(PyLongObject *v)
3625{
3626 return Py_BuildValue("(N)", _PyLong_Copy(v));
3627}
3628
Guido van Rossumb43daf72007-08-01 18:08:08 +00003629static PyObject *
3630long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003631 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003632}
3633
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003634static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003635long__format__(PyObject *self, PyObject *args)
3636{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003637 PyObject *format_spec;
3638
3639 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3640 return NULL;
3641 return _PyLong_FormatAdvanced(self,
3642 PyUnicode_AS_UNICODE(format_spec),
3643 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003644}
3645
Eric Smith8c663262007-08-25 02:26:07 +00003646static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003647long_round(PyObject *self, PyObject *args)
3648{
Mark Dickinson1124e712009-01-28 21:25:58 +00003649 PyObject *o_ndigits=NULL, *temp;
3650 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3651 int errcode;
3652 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003653
Mark Dickinson1124e712009-01-28 21:25:58 +00003654 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3655 the straightforward method is:
3656
3657 (1) divide by 10**n
3658 (2) round to nearest integer (round to even in case of tie)
3659 (3) multiply result by 10**n.
3660
3661 But the rounding step involves examining the fractional part of the
3662 quotient to see whether it's greater than 0.5 or not. Since we
3663 want to do the whole calculation in integer arithmetic, it's
3664 simpler to do:
3665
3666 (1) divide by (10**n)/2
3667 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3668 (3) multiply result by (10**n)/2.
3669
3670 Then all we need to know about the fractional part of the quotient
3671 arising in step (2) is whether it's zero or not.
3672
3673 Doing both a multiplication and division is wasteful, and is easily
3674 avoided if we just figure out how much to adjust the original input
3675 by to do the rounding.
3676
3677 Here's the whole algorithm expressed in Python.
3678
3679 def round(self, ndigits = None):
3680 """round(int, int) -> int"""
3681 if ndigits is None or ndigits >= 0:
3682 return self
3683 pow = 10**-ndigits >> 1
3684 q, r = divmod(self, pow)
3685 self -= r
3686 if (q & 1 != 0):
3687 if (q & 2 == r == 0):
3688 self -= pow
3689 else:
3690 self += pow
3691 return self
3692
3693 */
3694 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
3695 return NULL;
3696 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003697 return long_long(self);
3698
Mark Dickinson1124e712009-01-28 21:25:58 +00003699 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
3700 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003701 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00003702
3703 if (Py_SIZE(ndigits) >= 0) {
3704 Py_DECREF(ndigits);
3705 return long_long(self);
3706 }
3707
3708 Py_INCREF(self); /* to keep refcounting simple */
3709 /* we now own references to self, ndigits */
3710
3711 /* pow = 10 ** -ndigits >> 1 */
3712 pow = (PyLongObject *)PyLong_FromLong(10L);
3713 if (pow == NULL)
3714 goto error;
3715 temp = long_neg(ndigits);
3716 Py_DECREF(ndigits);
3717 ndigits = (PyLongObject *)temp;
3718 if (ndigits == NULL)
3719 goto error;
3720 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
3721 Py_DECREF(pow);
3722 pow = (PyLongObject *)temp;
3723 if (pow == NULL)
3724 goto error;
3725 assert(PyLong_Check(pow)); /* check long_pow returned a long */
3726 one = (PyLongObject *)PyLong_FromLong(1L);
3727 if (one == NULL)
3728 goto error;
3729 temp = long_rshift(pow, one);
3730 Py_DECREF(one);
3731 Py_DECREF(pow);
3732 pow = (PyLongObject *)temp;
3733 if (pow == NULL)
3734 goto error;
3735
3736 /* q, r = divmod(self, pow) */
3737 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
3738 if (errcode == -1)
3739 goto error;
3740
3741 /* self -= r */
3742 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003743 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00003744 self = temp;
3745 if (self == NULL)
3746 goto error;
3747
3748 /* get value of quotient modulo 4 */
3749 if (Py_SIZE(q) == 0)
3750 q_mod_4 = 0;
3751 else if (Py_SIZE(q) > 0)
3752 q_mod_4 = q->ob_digit[0] & 3;
3753 else
3754 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
3755
3756 if ((q_mod_4 & 1) == 1) {
3757 /* q is odd; round self up or down by adding or subtracting pow */
3758 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
3759 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
3760 else
3761 temp = (PyObject *)long_add((PyLongObject *)self, pow);
3762 Py_DECREF(self);
3763 self = temp;
3764 if (self == NULL)
3765 goto error;
3766 }
3767 Py_DECREF(q);
3768 Py_DECREF(r);
3769 Py_DECREF(pow);
3770 Py_DECREF(ndigits);
3771 return self;
3772
3773 error:
3774 Py_XDECREF(q);
3775 Py_XDECREF(r);
3776 Py_XDECREF(pow);
3777 Py_XDECREF(self);
3778 Py_XDECREF(ndigits);
3779 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003780}
3781
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003782static PyObject *
3783long_sizeof(PyLongObject *v)
3784{
3785 Py_ssize_t res;
3786
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00003787 res = sizeof(PyVarObject) + abs(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003788 return PyLong_FromSsize_t(res);
3789}
3790
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003791static const unsigned char BitLengthTable[32] = {
3792 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3793 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3794};
3795
3796static PyObject *
3797long_bit_length(PyLongObject *v)
3798{
3799 PyLongObject *result, *x, *y;
3800 Py_ssize_t ndigits, msd_bits = 0;
3801 digit msd;
3802
3803 assert(v != NULL);
3804 assert(PyLong_Check(v));
3805
3806 ndigits = ABS(Py_SIZE(v));
3807 if (ndigits == 0)
3808 return PyLong_FromLong(0);
3809
3810 msd = v->ob_digit[ndigits-1];
3811 while (msd >= 32) {
3812 msd_bits += 6;
3813 msd >>= 6;
3814 }
3815 msd_bits += (long)(BitLengthTable[msd]);
3816
3817 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3818 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3819
3820 /* expression above may overflow; use Python integers instead */
3821 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3822 if (result == NULL)
3823 return NULL;
3824 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3825 if (x == NULL)
3826 goto error;
3827 y = (PyLongObject *)long_mul(result, x);
3828 Py_DECREF(x);
3829 if (y == NULL)
3830 goto error;
3831 Py_DECREF(result);
3832 result = y;
3833
3834 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3835 if (x == NULL)
3836 goto error;
3837 y = (PyLongObject *)long_add(result, x);
3838 Py_DECREF(x);
3839 if (y == NULL)
3840 goto error;
3841 Py_DECREF(result);
3842 result = y;
3843
3844 return (PyObject *)result;
3845
3846error:
3847 Py_DECREF(result);
3848 return NULL;
3849}
3850
3851PyDoc_STRVAR(long_bit_length_doc,
3852"int.bit_length() -> int\n\
3853\n\
3854Number of bits necessary to represent self in binary.\n\
3855>>> bin(37)\n\
3856'0b100101'\n\
3857>>> (37).bit_length()\n\
38586");
3859
Christian Heimes53876d92008-04-19 00:31:39 +00003860#if 0
3861static PyObject *
3862long_is_finite(PyObject *v)
3863{
3864 Py_RETURN_TRUE;
3865}
3866#endif
3867
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003868static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003869 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3870 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003871 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3872 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003873#if 0
3874 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3875 "Returns always True."},
3876#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003877 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3878 "Truncating an Integral returns itself."},
3879 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3880 "Flooring an Integral returns itself."},
3881 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3882 "Ceiling of an Integral returns itself."},
3883 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00003884 "Rounding an Integral returns itself.\n"
3885 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003886 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003887 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003888 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3889 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003890 {NULL, NULL} /* sentinel */
3891};
3892
Guido van Rossumb43daf72007-08-01 18:08:08 +00003893static PyGetSetDef long_getset[] = {
3894 {"real",
3895 (getter)long_long, (setter)NULL,
3896 "the real part of a complex number",
3897 NULL},
3898 {"imag",
3899 (getter)long_getN, (setter)NULL,
3900 "the imaginary part of a complex number",
3901 (void*)0},
3902 {"numerator",
3903 (getter)long_long, (setter)NULL,
3904 "the numerator of a rational number in lowest terms",
3905 NULL},
3906 {"denominator",
3907 (getter)long_getN, (setter)NULL,
3908 "the denominator of a rational number in lowest terms",
3909 (void*)1},
3910 {NULL} /* Sentinel */
3911};
3912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003913PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003914"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003915\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003916Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003917point argument will be truncated towards zero (this does not include a\n\
3918string representation of a floating point number!) When converting a\n\
3919string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003920converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003921
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003922static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003923 (binaryfunc) long_add, /*nb_add*/
3924 (binaryfunc) long_sub, /*nb_subtract*/
3925 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003926 long_mod, /*nb_remainder*/
3927 long_divmod, /*nb_divmod*/
3928 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003929 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003930 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003931 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003932 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003933 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003934 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003935 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003936 long_and, /*nb_and*/
3937 long_xor, /*nb_xor*/
3938 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003939 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00003940 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003941 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003942 0, /* nb_inplace_add */
3943 0, /* nb_inplace_subtract */
3944 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003945 0, /* nb_inplace_remainder */
3946 0, /* nb_inplace_power */
3947 0, /* nb_inplace_lshift */
3948 0, /* nb_inplace_rshift */
3949 0, /* nb_inplace_and */
3950 0, /* nb_inplace_xor */
3951 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003952 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003953 long_true_divide, /* nb_true_divide */
3954 0, /* nb_inplace_floor_divide */
3955 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003956 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003957};
3958
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003959PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003960 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003961 "int", /* tp_name */
3962 /* See _PyLong_New for why this isn't
3963 sizeof(PyLongObject) - sizeof(digit) */
3964 sizeof(PyVarObject), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003965 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003966 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003967 0, /* tp_print */
3968 0, /* tp_getattr */
3969 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003970 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003971 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003972 &long_as_number, /* tp_as_number */
3973 0, /* tp_as_sequence */
3974 0, /* tp_as_mapping */
3975 (hashfunc)long_hash, /* tp_hash */
3976 0, /* tp_call */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003977 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003978 PyObject_GenericGetAttr, /* tp_getattro */
3979 0, /* tp_setattro */
3980 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003981 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3982 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003983 long_doc, /* tp_doc */
3984 0, /* tp_traverse */
3985 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003986 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003987 0, /* tp_weaklistoffset */
3988 0, /* tp_iter */
3989 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003990 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003991 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003992 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003993 0, /* tp_base */
3994 0, /* tp_dict */
3995 0, /* tp_descr_get */
3996 0, /* tp_descr_set */
3997 0, /* tp_dictoffset */
3998 0, /* tp_init */
3999 0, /* tp_alloc */
4000 long_new, /* tp_new */
Neil Schemenaueraa769ae2002-04-12 02:44:10 +00004001 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004002};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004003
4004int
4005_PyLong_Init(void)
4006{
4007#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004008 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004009 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004010
4011 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4012 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4013 if (Py_TYPE(v) == &PyLong_Type) {
4014 /* The element is already initialized, most likely
4015 * the Python interpreter was initialized before.
4016 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004017 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004018 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004019
Christian Heimes48aa4b12008-02-01 16:56:30 +00004020 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4021 _Py_NewReference(op);
4022 /* _Py_NewReference sets the ref count to 1 but
4023 * the ref count might be larger. Set the refcnt
4024 * to the original refcnt + 1 */
4025 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004026 assert(Py_SIZE(op) == size);
4027 assert(v->ob_digit[0] == abs(ival));
4028 }
4029 else {
4030 PyObject_INIT(v, &PyLong_Type);
4031 }
4032 Py_SIZE(v) = size;
4033 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004034 }
4035#endif
4036 return 1;
4037}
4038
4039void
4040PyLong_Fini(void)
4041{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004042 /* Integers are currently statically allocated. Py_DECREF is not
4043 needed, but Python must forget about the reference or multiple
4044 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004045#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004046 int i;
4047 PyLongObject *v = small_ints;
4048 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4049 _Py_DEC_REFTOTAL;
4050 _Py_ForgetReference((PyObject*)v);
4051 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004052#endif
4053}