blob: b758c40203a24dab86ece09c116d1ee07e19176d [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>
Mark Dickinson5a74bf62009-02-15 11:04:38 +00009#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000010
Guido van Rossumddefaf32007-01-14 03:31:43 +000011#ifndef NSMALLPOSINTS
12#define NSMALLPOSINTS 257
13#endif
14#ifndef NSMALLNEGINTS
15#define NSMALLNEGINTS 5
16#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000017
Mark Dickinsone4416742009-02-15 15:14:57 +000018/* convert a PyLong of size 1, 0 or -1 to an sdigit */
19#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
20 (Py_SIZE(x) == 0 ? (sdigit)0 : \
21 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000022#define ABS(x) ((x) < 0 ? -(x) : (x))
23
Guido van Rossumddefaf32007-01-14 03:31:43 +000024#if NSMALLNEGINTS + NSMALLPOSINTS > 0
25/* Small integers are preallocated in this array so that they
26 can be shared.
27 The integers that are preallocated are those in the range
28 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
29*/
30static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
31#ifdef COUNT_ALLOCS
32int quick_int_allocs, quick_neg_int_allocs;
33#endif
34
Guido van Rossum7eaf8222007-06-18 17:58:50 +000035static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000036get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000037{
38 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
39 Py_INCREF(v);
40#ifdef COUNT_ALLOCS
41 if (ival >= 0)
42 quick_int_allocs++;
43 else
44 quick_neg_int_allocs++;
45#endif
46 return v;
47}
48#define CHECK_SMALL_INT(ival) \
49 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
Mark Dickinson0d4785b2009-02-15 17:27:41 +000050 return get_small_int((sdigit)ival); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000051 } while(0)
52
Facundo Batista6e6f59b2008-07-24 18:57:11 +000053static PyLongObject *
54maybe_small_long(PyLongObject *v)
55{
56 if (v && ABS(Py_SIZE(v)) <= 1) {
Mark Dickinsone4416742009-02-15 15:14:57 +000057 sdigit ival = MEDIUM_VALUE(v);
Facundo Batista6e6f59b2008-07-24 18:57:11 +000058 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
59 Py_DECREF(v);
60 return (PyLongObject *)get_small_int(ival);
61 }
62 }
63 return v;
64}
Guido van Rossumddefaf32007-01-14 03:31:43 +000065#else
66#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000067#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000068#endif
69
Guido van Rossumddefaf32007-01-14 03:31:43 +000070/* If a freshly-allocated long is already shared, it must
71 be a small integer, so negating it must go to PyLong_FromLong */
72#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000073 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000074 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000075 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
76 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000077/* For long multiplication, use the O(N**2) school algorithm unless
78 * both operands contain more than KARATSUBA_CUTOFF digits (this
79 * being an internal Python long digit, in base BASE).
80 */
Tim Peters0973b992004-08-29 22:16:50 +000081#define KARATSUBA_CUTOFF 70
82#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000083
Tim Peters47e52ee2004-08-30 02:44:38 +000084/* For exponentiation, use the binary left-to-right algorithm
85 * unless the exponent contains more than FIVEARY_CUTOFF digits.
86 * In that case, do 5 bits at a time. The potential drawback is that
87 * a table of 2**5 intermediate results is computed.
88 */
89#define FIVEARY_CUTOFF 8
90
Tim Peters5af4e6c2002-08-12 02:31:19 +000091#undef MIN
92#undef MAX
93#define MAX(x, y) ((x) < (y) ? (y) : (x))
94#define MIN(x, y) ((x) > (y) ? (y) : (x))
95
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096#define SIGCHECK(PyTryBlock) \
Skip Montanarod581d772002-09-03 20:10:45 +000097 if (--_Py_Ticker < 0) { \
98 _Py_Ticker = _Py_CheckInterval; \
Thomas Wouters477c8d52006-05-27 19:21:47 +000099 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000100 }
101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Christian Heimes90aa7642007-12-19 02:45:37 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000116 return v;
117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
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;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
Mark Dickinsone4416742009-02-15 15:14:57 +0000134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
Guido van Rossumddefaf32007-01-14 03:31:43 +0000140 size*sizeof(digit));
141 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000142 PyErr_NoMemory();
143 return NULL;
144 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
151 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
154 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000155 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000156 if (i < 0)
157 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000158 if (i < 2) {
Mark Dickinsone4416742009-02-15 15:14:57 +0000159 sdigit ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000160 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000161 ival = -ival;
162 CHECK_SMALL_INT(ival);
163 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000164 result = _PyLong_New(i);
165 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000166 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000167 while (--i >= 0)
168 result->ob_digit[i] = src->ob_digit[i];
169 }
170 return (PyObject *)result;
171}
172
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000173/* Create a new long int object from a C long int */
174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000176PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Tim Petersce9de2f2001-06-14 04:56:19 +0000178 PyLongObject *v;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000179 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000180 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
181 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000182 int sign = 1;
183
184 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000185
186 if (ival < 0) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000187 /* negate: can't write this as abs_ival = -ival since that
188 invokes undefined behaviour when ival is LONG_MIN */
189 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000190 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000191 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Mark Dickinsond4624c32009-01-24 15:02:35 +0000196 /* Fast path for single-digit ints */
197 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000198 v = _PyLong_New(1);
199 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000200 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000201 v->ob_digit[0] = Py_SAFE_DOWNCAST(
202 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000203 }
204 return (PyObject*)v;
205 }
206
207 /* 2 digits */
Mark Dickinsond4624c32009-01-24 15:02:35 +0000208 if (!(abs_ival >> 2*PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000209 v = _PyLong_New(2);
210 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000211 Py_SIZE(v) = 2*sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000212 v->ob_digit[0] = Py_SAFE_DOWNCAST(
213 abs_ival & PyLong_MASK, unsigned long, digit);
214 v->ob_digit[1] = Py_SAFE_DOWNCAST(
215 abs_ival >> PyLong_SHIFT, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000216 }
217 return (PyObject*)v;
218 }
219
220 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000221 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000222 while (t) {
223 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000224 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000225 }
226 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000227 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000228 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000229 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000230 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000231 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000234 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000235 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000236 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Tim Petersce9de2f2001-06-14 04:56:19 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
248
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000249 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000250 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000255 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000256 }
257 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000258 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000259 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000260 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000261 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000264 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000265 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000278 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000279 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000280 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000281 return NULL;
282 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000283 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000284 PyErr_SetString(PyExc_ValueError,
285 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000286 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000287 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000297 if (v == NULL)
298 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000300 for (i = ndig; --i >= 0; ) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000303 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000304 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000305 }
306 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000307 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
322
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000323/* Get a C long int from a long int object.
324 Returns -1 and sets an error condition if overflow occurs. */
325
326long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000327PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000328{
Guido van Rossumf7531811998-05-26 14:33:37 +0000329 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000331 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000332 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000333 Py_ssize_t i;
334 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000335 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000336
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000337 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000338 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000339 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000340 return -1;
341 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000342
343 if (!PyLong_Check(vv)) {
344 PyNumberMethods *nb;
345 if ((nb = vv->ob_type->tp_as_number) == NULL ||
346 nb->nb_int == NULL) {
347 PyErr_SetString(PyExc_TypeError, "an integer is required");
348 return -1;
349 }
350 vv = (*nb->nb_int) (vv);
351 if (vv == NULL)
352 return -1;
353 do_decref = 1;
354 if (!PyLong_Check(vv)) {
355 Py_DECREF(vv);
356 PyErr_SetString(PyExc_TypeError,
357 "nb_int should return int object");
358 return -1;
359 }
360 }
361
Georg Brandl61c31b02007-02-26 14:46:30 +0000362 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000364 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000365
Georg Brandl61c31b02007-02-26 14:46:30 +0000366 switch (i) {
367 case -1:
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000368 res = -(sdigit)v->ob_digit[0];
Georg Brandl61c31b02007-02-26 14:46:30 +0000369 break;
370 case 0:
371 res = 0;
372 break;
373 case 1:
374 res = v->ob_digit[0];
375 break;
376 default:
377 sign = 1;
378 x = 0;
379 if (i < 0) {
380 sign = -1;
381 i = -(i);
382 }
383 while (--i >= 0) {
384 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
386 if ((x >> PyLong_SHIFT) != prev) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000387 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Georg Brandl61c31b02007-02-26 14:46:30 +0000388 goto exit;
389 }
390 }
391 /* Haven't lost any bits, but casting to long requires extra care
392 * (see comment above).
393 */
394 if (x <= (unsigned long)LONG_MAX) {
395 res = (long)x * sign;
396 }
397 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
398 res = LONG_MIN;
399 }
400 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000401 *overflow = Py_SIZE(v) > 0 ? 1 : -1;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000402 /* res is already set to -1 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000403 }
404 }
405 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000406 if (do_decref) {
407 Py_DECREF(vv);
408 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000409 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000410}
411
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000412long
413PyLong_AsLong(PyObject *obj)
414{
415 int overflow;
416 long result = PyLong_AsLongAndOverflow(obj, &overflow);
417 if (overflow) {
418 /* XXX: could be cute and give a different
419 message for overflow == -1 */
420 PyErr_SetString(PyExc_OverflowError,
421 "Python int too large to convert to C long");
422 }
423 return result;
424}
425
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000426/* Get a Py_ssize_t from a long int object.
427 Returns -1 and sets an error condition if overflow occurs. */
428
429Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000430PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431 register PyLongObject *v;
432 size_t x, prev;
433 Py_ssize_t i;
434 int sign;
435
436 if (vv == NULL || !PyLong_Check(vv)) {
437 PyErr_BadInternalCall();
438 return -1;
439 }
440 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000441 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000442 switch (i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000443 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +0000444 case 0: return 0;
445 case 1: return v->ob_digit[0];
446 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447 sign = 1;
448 x = 0;
449 if (i < 0) {
450 sign = -1;
451 i = -(i);
452 }
453 while (--i >= 0) {
454 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000455 x = (x << PyLong_SHIFT) + v->ob_digit[i];
456 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457 goto overflow;
458 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000459 /* Haven't lost any bits, but casting to a signed type requires
460 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000461 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462 if (x <= (size_t)PY_SSIZE_T_MAX) {
463 return (Py_ssize_t)x * sign;
464 }
465 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
466 return PY_SSIZE_T_MIN;
467 }
468 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000469
470 overflow:
471 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000472 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000473 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000474}
475
Guido van Rossumd8c80482002-08-13 00:24:58 +0000476/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000477 Returns -1 and sets an error condition if overflow occurs. */
478
479unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000480PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000481{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000483 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000484 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000485
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 if (vv == NULL || !PyLong_Check(vv)) {
487 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000488 return (unsigned long) -1;
489 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000491 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000492 x = 0;
493 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000495 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000496 return (unsigned long) -1;
497 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000498 switch (i) {
499 case 0: return 0;
500 case 1: return v->ob_digit[0];
501 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000502 while (--i >= 0) {
503 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000504 x = (x << PyLong_SHIFT) + v->ob_digit[i];
505 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000507 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000508 return (unsigned long) -1;
509 }
510 }
511 return x;
512}
513
514/* Get a C unsigned long int from a long int object.
515 Returns -1 and sets an error condition if overflow occurs. */
516
517size_t
518PyLong_AsSize_t(PyObject *vv)
519{
520 register PyLongObject *v;
521 size_t x, prev;
522 Py_ssize_t i;
523
524 if (vv == NULL || !PyLong_Check(vv)) {
525 PyErr_BadInternalCall();
526 return (unsigned long) -1;
527 }
528 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000529 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000530 x = 0;
531 if (i < 0) {
532 PyErr_SetString(PyExc_OverflowError,
533 "can't convert negative value to size_t");
534 return (size_t) -1;
535 }
536 switch (i) {
537 case 0: return 0;
538 case 1: return v->ob_digit[0];
539 }
540 while (--i >= 0) {
541 prev = x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000542 x = (x << PyLong_SHIFT) + v->ob_digit[i];
543 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000544 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000545 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000546 return (unsigned long) -1;
547 }
548 }
549 return x;
550}
551
Thomas Hellera4ea6032003-04-17 18:55:45 +0000552/* Get a C unsigned long int from a long int object, ignoring the high bits.
553 Returns -1 and sets an error condition if an error occurs. */
554
Guido van Rossumddefaf32007-01-14 03:31:43 +0000555static unsigned long
556_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000557{
558 register PyLongObject *v;
559 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000560 Py_ssize_t i;
561 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000562
563 if (vv == NULL || !PyLong_Check(vv)) {
564 PyErr_BadInternalCall();
565 return (unsigned long) -1;
566 }
567 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000568 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000569 switch (i) {
570 case 0: return 0;
571 case 1: return v->ob_digit[0];
572 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000573 sign = 1;
574 x = 0;
575 if (i < 0) {
576 sign = -1;
577 i = -i;
578 }
579 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000580 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000581 }
582 return x * sign;
583}
584
Guido van Rossumddefaf32007-01-14 03:31:43 +0000585unsigned long
586PyLong_AsUnsignedLongMask(register PyObject *op)
587{
588 PyNumberMethods *nb;
589 PyLongObject *lo;
590 unsigned long val;
591
592 if (op && PyLong_Check(op))
593 return _PyLong_AsUnsignedLongMask(op);
594
595 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
596 nb->nb_int == NULL) {
597 PyErr_SetString(PyExc_TypeError, "an integer is required");
598 return (unsigned long)-1;
599 }
600
601 lo = (PyLongObject*) (*nb->nb_int) (op);
602 if (lo == NULL)
603 return (unsigned long)-1;
604 if (PyLong_Check(lo)) {
605 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
606 Py_DECREF(lo);
607 if (PyErr_Occurred())
608 return (unsigned long)-1;
609 return val;
610 }
611 else
612 {
613 Py_DECREF(lo);
614 PyErr_SetString(PyExc_TypeError,
615 "nb_int should return int object");
616 return (unsigned long)-1;
617 }
618}
619
Tim Peters5b8132f2003-01-31 15:52:05 +0000620int
621_PyLong_Sign(PyObject *vv)
622{
623 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000624
625 assert(v != NULL);
626 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000627
Christian Heimes90aa7642007-12-19 02:45:37 +0000628 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000629}
630
Tim Petersbaefd9e2003-01-28 20:37:45 +0000631size_t
632_PyLong_NumBits(PyObject *vv)
633{
634 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000635 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000636 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000637
638 assert(v != NULL);
639 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000640 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000641 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
642 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000643 digit msd = v->ob_digit[ndigits - 1];
644
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000645 result = (ndigits - 1) * PyLong_SHIFT;
646 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000647 goto Overflow;
648 do {
649 ++result;
650 if (result == 0)
651 goto Overflow;
652 msd >>= 1;
653 } while (msd);
654 }
655 return result;
656
657Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000658 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000659 "to express in a platform size_t");
660 return (size_t)-1;
661}
662
Tim Peters2a9b3672001-06-11 21:23:58 +0000663PyObject *
664_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
665 int little_endian, int is_signed)
666{
667 const unsigned char* pstartbyte;/* LSB of bytes */
668 int incr; /* direction to move pstartbyte */
669 const unsigned char* pendbyte; /* MSB of bytes */
670 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000671 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000672 PyLongObject* v; /* result */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000673 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000674
675 if (n == 0)
676 return PyLong_FromLong(0L);
677
678 if (little_endian) {
679 pstartbyte = bytes;
680 pendbyte = bytes + n - 1;
681 incr = 1;
682 }
683 else {
684 pstartbyte = bytes + n - 1;
685 pendbyte = bytes;
686 incr = -1;
687 }
688
689 if (is_signed)
690 is_signed = *pendbyte >= 0x80;
691
692 /* Compute numsignificantbytes. This consists of finding the most
693 significant byte. Leading 0 bytes are insignficant if the number
694 is positive, and leading 0xff bytes if negative. */
695 {
696 size_t i;
697 const unsigned char* p = pendbyte;
698 const int pincr = -incr; /* search MSB to LSB */
699 const unsigned char insignficant = is_signed ? 0xff : 0x00;
700
701 for (i = 0; i < n; ++i, p += pincr) {
702 if (*p != insignficant)
703 break;
704 }
705 numsignificantbytes = n - i;
706 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
707 actually has 2 significant bytes. OTOH, 0xff0001 ==
708 -0x00ffff, so we wouldn't *need* to bump it there; but we
709 do for 0xffff = -0x0001. To be safe without bothering to
710 check every case, bump it regardless. */
711 if (is_signed && numsignificantbytes < n)
712 ++numsignificantbytes;
713 }
714
715 /* How many Python long digits do we need? We have
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000716 8*numsignificantbytes bits, and each Python long digit has
717 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
718 /* catch overflow before it happens */
719 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
720 PyErr_SetString(PyExc_OverflowError,
721 "byte array too long to convert to int");
722 return NULL;
723 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000724 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000725 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000726 if (v == NULL)
727 return NULL;
728
729 /* Copy the bits over. The tricky parts are computing 2's-comp on
730 the fly for signed numbers, and dealing with the mismatch between
731 8-bit bytes and (probably) 15-bit Python digits.*/
732 {
733 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000734 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000735 twodigits accum = 0; /* sliding register */
736 unsigned int accumbits = 0; /* number of bits in accum */
737 const unsigned char* p = pstartbyte;
738
739 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000740 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000741 /* Compute correction for 2's comp, if needed. */
742 if (is_signed) {
743 thisbyte = (0xff ^ thisbyte) + carry;
744 carry = thisbyte >> 8;
745 thisbyte &= 0xff;
746 }
747 /* Because we're going LSB to MSB, thisbyte is
748 more significant than what's already in accum,
749 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000750 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000751 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000752 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000753 /* There's enough to fill a Python digit. */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000754 assert(idigit < ndigits);
755 v->ob_digit[idigit] = (digit)(accum &
756 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000757 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000758 accum >>= PyLong_SHIFT;
759 accumbits -= PyLong_SHIFT;
760 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000761 }
762 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000763 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000764 if (accumbits) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000765 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 v->ob_digit[idigit] = (digit)accum;
767 ++idigit;
768 }
769 }
770
Christian Heimes90aa7642007-12-19 02:45:37 +0000771 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000772 return (PyObject *)long_normalize(v);
773}
774
775int
776_PyLong_AsByteArray(PyLongObject* v,
777 unsigned char* bytes, size_t n,
778 int little_endian, int is_signed)
779{
Mark Dickinson17e55872009-01-24 15:56:57 +0000780 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000781 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000782 twodigits accum; /* sliding register */
783 unsigned int accumbits; /* # bits in accum */
784 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000785 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000786 size_t j; /* # bytes filled */
787 unsigned char* p; /* pointer to next byte in bytes */
788 int pincr; /* direction to move p */
789
790 assert(v != NULL && PyLong_Check(v));
791
Christian Heimes90aa7642007-12-19 02:45:37 +0000792 if (Py_SIZE(v) < 0) {
793 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000794 if (!is_signed) {
Mark Dickinson21776072009-02-10 16:13:25 +0000795 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000796 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000797 return -1;
798 }
799 do_twos_comp = 1;
800 }
801 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000802 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000803 do_twos_comp = 0;
804 }
805
806 if (little_endian) {
807 p = bytes;
808 pincr = 1;
809 }
810 else {
811 p = bytes + n - 1;
812 pincr = -1;
813 }
814
Tim Peters898cf852001-06-13 20:50:08 +0000815 /* Copy over all the Python digits.
816 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000817 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000818 normalized. */
819 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000820 j = 0;
821 accum = 0;
822 accumbits = 0;
823 carry = do_twos_comp ? 1 : 0;
824 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000825 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000826 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000827 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
828 carry = thisdigit >> PyLong_SHIFT;
829 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000830 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000831 /* Because we're going LSB to MSB, thisdigit is more
832 significant than what's already in accum, so needs to be
833 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000834 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000835
Tim Petersede05092001-06-14 08:53:38 +0000836 /* The most-significant digit may be (probably is) at least
837 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000838 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000839 /* Count # of sign bits -- they needn't be stored,
840 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000841 * make sure at least one sign bit gets stored. */
842 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
843 thisdigit;
844 while (s != 0) {
845 s >>= 1;
846 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000847 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000848 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000849 else
850 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000851
Tim Peters2a9b3672001-06-11 21:23:58 +0000852 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000853 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000854 if (j >= n)
855 goto Overflow;
856 ++j;
857 *p = (unsigned char)(accum & 0xff);
858 p += pincr;
859 accumbits -= 8;
860 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000861 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000862 }
863
864 /* Store the straggler (if any). */
865 assert(accumbits < 8);
866 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000867 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000868 if (j >= n)
869 goto Overflow;
870 ++j;
871 if (do_twos_comp) {
872 /* Fill leading bits of the byte with sign bits
873 (appropriately pretending that the long had an
874 infinite supply of sign bits). */
875 accum |= (~(twodigits)0) << accumbits;
876 }
877 *p = (unsigned char)(accum & 0xff);
878 p += pincr;
879 }
Tim Peters05607ad2001-06-13 21:01:27 +0000880 else if (j == n && n > 0 && is_signed) {
881 /* The main loop filled the byte array exactly, so the code
882 just above didn't get to ensure there's a sign bit, and the
883 loop below wouldn't add one either. Make sure a sign bit
884 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000885 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000886 int sign_bit_set = msb >= 0x80;
887 assert(accumbits == 0);
888 if (sign_bit_set == do_twos_comp)
889 return 0;
890 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000891 goto Overflow;
892 }
Tim Peters05607ad2001-06-13 21:01:27 +0000893
894 /* Fill remaining bytes with copies of the sign bit. */
895 {
896 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
897 for ( ; j < n; ++j, p += pincr)
898 *p = signbyte;
899 }
900
Tim Peters2a9b3672001-06-11 21:23:58 +0000901 return 0;
902
903Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000904 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000905 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000906
Tim Peters2a9b3672001-06-11 21:23:58 +0000907}
908
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000909double
910_PyLong_AsScaledDouble(PyObject *vv, int *exponent)
911{
912/* NBITS_WANTED should be > the number of bits in a double's precision,
913 but small enough so that 2**NBITS_WANTED is within the normal double
914 range. nbitsneeded is set to 1 less than that because the most-significant
915 Python digit contains at least 1 significant bit, but we don't want to
916 bother counting them (catering to the worst case cheaply).
917
918 57 is one more than VAX-D double precision; I (Tim) don't know of a double
919 format with more precision than that; it's 1 larger so that we add in at
920 least one round bit to stand in for the ignored least-significant bits.
921*/
922#define NBITS_WANTED 57
923 PyLongObject *v;
924 double x;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000925 const double multiplier = (double)(1L << PyLong_SHIFT);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000926 Py_ssize_t i;
927 int sign;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000928 int nbitsneeded;
929
930 if (vv == NULL || !PyLong_Check(vv)) {
931 PyErr_BadInternalCall();
932 return -1;
933 }
934 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000935 i = Py_SIZE(v);
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000936 sign = 1;
937 if (i < 0) {
938 sign = -1;
939 i = -(i);
940 }
941 else if (i == 0) {
942 *exponent = 0;
943 return 0.0;
944 }
945 --i;
946 x = (double)v->ob_digit[i];
947 nbitsneeded = NBITS_WANTED - 1;
948 /* Invariant: i Python digits remain unaccounted for. */
949 while (i > 0 && nbitsneeded > 0) {
950 --i;
951 x = x * multiplier + (double)v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000952 nbitsneeded -= PyLong_SHIFT;
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000953 }
954 /* There are i digits we didn't shift in. Pretending they're all
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000955 zeroes, the true value is x * 2**(i*PyLong_SHIFT). */
Tim Petersa1c1b0f2001-09-04 02:50:49 +0000956 *exponent = i;
957 assert(x > 0.0);
958 return x * sign;
959#undef NBITS_WANTED
960}
961
Guido van Rossum09e6ad01997-02-14 22:54:21 +0000962/* Get a C double from a long int object. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000963
964double
Tim Peters9f688bf2000-07-07 15:53:28 +0000965PyLong_AsDouble(PyObject *vv)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000966{
Thomas Wouters553489a2006-02-01 21:32:04 +0000967 int e = -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000968 double x;
Tim Peters9fffa3e2001-09-04 05:14:19 +0000969
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000970 if (vv == NULL || !PyLong_Check(vv)) {
971 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000972 return -1;
973 }
Tim Peters9fffa3e2001-09-04 05:14:19 +0000974 x = _PyLong_AsScaledDouble(vv, &e);
975 if (x == -1.0 && PyErr_Occurred())
976 return -1.0;
Thomas Wouters553489a2006-02-01 21:32:04 +0000977 /* 'e' initialized to -1 to silence gcc-4.0.x, but it should be
978 set correctly after a successful _PyLong_AsScaledDouble() call */
979 assert(e >= 0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000980 if (e > INT_MAX / PyLong_SHIFT)
Tim Peters9fffa3e2001-09-04 05:14:19 +0000981 goto overflow;
982 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000983 x = ldexp(x, e * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +0000984 if (Py_OVERFLOWED(x))
Tim Peters9fffa3e2001-09-04 05:14:19 +0000985 goto overflow;
986 return x;
987
988overflow:
989 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000990 "Python int too large to convert to C double");
Tim Peters9fffa3e2001-09-04 05:14:19 +0000991 return -1.0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000992}
993
Guido van Rossum78694d91998-09-18 14:14:13 +0000994/* Create a new long (or int) object from a C pointer */
995
996PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000997PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000998{
Tim Peters70128a12001-06-16 08:48:40 +0000999#ifndef HAVE_LONG_LONG
1000# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1001#endif
1002#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001003# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001004#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +00001005 /* special-case null pointer */
1006 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +00001007 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001008 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +00001009
Guido van Rossum78694d91998-09-18 14:14:13 +00001010}
1011
1012/* Get a C pointer from a long object (or an int object in some cases) */
1013
1014void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001015PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001016{
1017 /* This function will allow int or long objects. If vv is neither,
1018 then the PyLong_AsLong*() functions will raise the exception:
1019 PyExc_SystemError, "bad argument to internal function"
1020 */
Tim Peters70128a12001-06-16 08:48:40 +00001021#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +00001022 long x;
1023
Guido van Rossumddefaf32007-01-14 03:31:43 +00001024 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001025 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001026 else
1027 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001028#else
Tim Peters70128a12001-06-16 08:48:40 +00001029
1030#ifndef HAVE_LONG_LONG
1031# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1032#endif
1033#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001034# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001035#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001036 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001037
Guido van Rossumddefaf32007-01-14 03:31:43 +00001038 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +00001039 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001040 else
1041 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001042
1043#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001044
1045 if (x == -1 && PyErr_Occurred())
1046 return NULL;
1047 return (void *)x;
1048}
1049
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001050#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001051
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001052/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001053 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001054 */
1055
Tim Peterscf37dfc2001-06-14 18:42:50 +00001056#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Tim Petersd1a7da62001-06-13 00:35:57 +00001057
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001058/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001059
1060PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001061PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001062{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001063 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +00001064 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001065 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1066 int ndigits = 0;
1067 int negative = 0;
1068
Guido van Rossumddefaf32007-01-14 03:31:43 +00001069 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +00001071 /* avoid signed overflow on negation; see comments
1072 in PyLong_FromLong above. */
1073 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001074 negative = 1;
1075 }
Christian Heimesdae2a892008-04-19 00:55:37 +00001076 else {
1077 abs_ival = (unsigned PY_LONG_LONG)ival;
1078 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079
1080 /* Count the number of Python digits.
1081 We used to pick 5 ("big enough for anything"), but that's a
1082 waste of time and space given that 5*15 = 75 bits are rarely
1083 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001084 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085 while (t) {
1086 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001087 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 }
1089 v = _PyLong_New(ndigits);
1090 if (v != NULL) {
1091 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001092 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001093 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001094 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001095 *p++ = (digit)(t & PyLong_MASK);
1096 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097 }
1098 }
1099 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001100}
1101
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001102/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001103
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001104PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001105PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001106{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001107 PyLongObject *v;
1108 unsigned PY_LONG_LONG t;
1109 int ndigits = 0;
1110
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001111 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001112 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001113 /* Count the number of Python digits. */
1114 t = (unsigned PY_LONG_LONG)ival;
1115 while (t) {
1116 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001117 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118 }
1119 v = _PyLong_New(ndigits);
1120 if (v != NULL) {
1121 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001122 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001124 *p++ = (digit)(ival & PyLong_MASK);
1125 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126 }
1127 }
1128 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001129}
1130
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131/* Create a new long int object from a C Py_ssize_t. */
1132
1133PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001134PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001136 PyLongObject *v;
1137 size_t abs_ival;
1138 size_t t; /* unsigned so >> doesn't propagate sign bit */
1139 int ndigits = 0;
1140 int negative = 0;
1141
1142 CHECK_SMALL_INT(ival);
1143 if (ival < 0) {
1144 /* avoid signed overflow when ival = SIZE_T_MIN */
1145 abs_ival = (size_t)(-1-ival)+1;
1146 negative = 1;
1147 }
1148 else {
1149 abs_ival = (size_t)ival;
1150 }
1151
1152 /* Count the number of Python digits. */
1153 t = abs_ival;
1154 while (t) {
1155 ++ndigits;
1156 t >>= PyLong_SHIFT;
1157 }
1158 v = _PyLong_New(ndigits);
1159 if (v != NULL) {
1160 digit *p = v->ob_digit;
1161 Py_SIZE(v) = negative ? -ndigits : ndigits;
1162 t = abs_ival;
1163 while (t) {
1164 *p++ = (digit)(t & PyLong_MASK);
1165 t >>= PyLong_SHIFT;
1166 }
1167 }
1168 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001169}
1170
1171/* Create a new long int object from a C size_t. */
1172
1173PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001174PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001176 PyLongObject *v;
1177 size_t t;
1178 int ndigits = 0;
1179
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001180 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001181 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001182 /* Count the number of Python digits. */
1183 t = ival;
1184 while (t) {
1185 ++ndigits;
1186 t >>= PyLong_SHIFT;
1187 }
1188 v = _PyLong_New(ndigits);
1189 if (v != NULL) {
1190 digit *p = v->ob_digit;
1191 Py_SIZE(v) = ndigits;
1192 while (ival) {
1193 *p++ = (digit)(ival & PyLong_MASK);
1194 ival >>= PyLong_SHIFT;
1195 }
1196 }
1197 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001198}
1199
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001200/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001201 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001203PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001204PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001205{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001206 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001207 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001208 int one = 1;
1209 int res;
1210
Tim Petersd38b1c72001-09-30 05:09:37 +00001211 if (vv == NULL) {
1212 PyErr_BadInternalCall();
1213 return -1;
1214 }
1215 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001216 PyNumberMethods *nb;
1217 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001218 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1219 nb->nb_int == NULL) {
1220 PyErr_SetString(PyExc_TypeError, "an integer is required");
1221 return -1;
1222 }
1223 io = (*nb->nb_int) (vv);
1224 if (io == NULL)
1225 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001226 if (PyLong_Check(io)) {
1227 bytes = PyLong_AsLongLong(io);
1228 Py_DECREF(io);
1229 return bytes;
1230 }
1231 Py_DECREF(io);
1232 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233 return -1;
1234 }
1235
Guido van Rossumddefaf32007-01-14 03:31:43 +00001236 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001237 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001238 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001239 case 0: return 0;
1240 case 1: return v->ob_digit[0];
1241 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001242 res = _PyLong_AsByteArray(
1243 (PyLongObject *)vv, (unsigned char *)&bytes,
1244 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001245
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001246 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001247 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001248 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001249 else
1250 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001251}
1252
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001253/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001254 Return -1 and set an error if overflow occurs. */
1255
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001256unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001257PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001258{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001259 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001260 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001261 int one = 1;
1262 int res;
1263
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001264 if (vv == NULL || !PyLong_Check(vv)) {
1265 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001266 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001267 }
1268
Guido van Rossumddefaf32007-01-14 03:31:43 +00001269 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001270 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001271 case 0: return 0;
1272 case 1: return v->ob_digit[0];
1273 }
1274
Tim Petersd1a7da62001-06-13 00:35:57 +00001275 res = _PyLong_AsByteArray(
1276 (PyLongObject *)vv, (unsigned char *)&bytes,
1277 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001278
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001279 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001280 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001281 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001282 else
1283 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001284}
Tim Petersd1a7da62001-06-13 00:35:57 +00001285
Thomas Hellera4ea6032003-04-17 18:55:45 +00001286/* Get a C unsigned long int from a long int object, ignoring the high bits.
1287 Returns -1 and sets an error condition if an error occurs. */
1288
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289static unsigned PY_LONG_LONG
1290_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001291{
1292 register PyLongObject *v;
1293 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001294 Py_ssize_t i;
1295 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001296
1297 if (vv == NULL || !PyLong_Check(vv)) {
1298 PyErr_BadInternalCall();
1299 return (unsigned long) -1;
1300 }
1301 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001302 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001303 case 0: return 0;
1304 case 1: return v->ob_digit[0];
1305 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001306 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001307 sign = 1;
1308 x = 0;
1309 if (i < 0) {
1310 sign = -1;
1311 i = -i;
1312 }
1313 while (--i >= 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001314 x = (x << PyLong_SHIFT) + v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001315 }
1316 return x * sign;
1317}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001318
1319unsigned PY_LONG_LONG
1320PyLong_AsUnsignedLongLongMask(register PyObject *op)
1321{
1322 PyNumberMethods *nb;
1323 PyLongObject *lo;
1324 unsigned PY_LONG_LONG val;
1325
1326 if (op && PyLong_Check(op))
1327 return _PyLong_AsUnsignedLongLongMask(op);
1328
1329 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1330 nb->nb_int == NULL) {
1331 PyErr_SetString(PyExc_TypeError, "an integer is required");
1332 return (unsigned PY_LONG_LONG)-1;
1333 }
1334
1335 lo = (PyLongObject*) (*nb->nb_int) (op);
1336 if (lo == NULL)
1337 return (unsigned PY_LONG_LONG)-1;
1338 if (PyLong_Check(lo)) {
1339 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1340 Py_DECREF(lo);
1341 if (PyErr_Occurred())
1342 return (unsigned PY_LONG_LONG)-1;
1343 return val;
1344 }
1345 else
1346 {
1347 Py_DECREF(lo);
1348 PyErr_SetString(PyExc_TypeError,
1349 "nb_int should return int object");
1350 return (unsigned PY_LONG_LONG)-1;
1351 }
1352}
Tim Petersd1a7da62001-06-13 00:35:57 +00001353#undef IS_LITTLE_ENDIAN
1354
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001355#endif /* HAVE_LONG_LONG */
1356
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001357#define CHECK_BINOP(v,w) \
1358 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001359 Py_INCREF(Py_NotImplemented); \
1360 return Py_NotImplemented; \
1361 }
1362
Tim Peters877a2122002-08-12 05:09:36 +00001363/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1364 * is modified in place, by adding y to it. Carries are propagated as far as
1365 * x[m-1], and the remaining carry (0 or 1) is returned.
1366 */
1367static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001368v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001369{
Mark Dickinson17e55872009-01-24 15:56:57 +00001370 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001371 digit carry = 0;
1372
1373 assert(m >= n);
1374 for (i = 0; i < n; ++i) {
1375 carry += x[i] + y[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 for (; carry && i < m; ++i) {
1381 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001382 x[i] = carry & PyLong_MASK;
1383 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001384 assert((carry & 1) == carry);
1385 }
1386 return carry;
1387}
1388
1389/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1390 * is modified in place, by subtracting y from it. Borrows are propagated as
1391 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1392 */
1393static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001394v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001395{
Mark Dickinson17e55872009-01-24 15:56:57 +00001396 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001397 digit borrow = 0;
1398
1399 assert(m >= n);
1400 for (i = 0; i < n; ++i) {
1401 borrow = x[i] - y[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; /* keep only 1 sign bit */
1405 }
1406 for (; borrow && i < m; ++i) {
1407 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001408 x[i] = borrow & PyLong_MASK;
1409 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001410 borrow &= 1;
1411 }
1412 return borrow;
1413}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001414
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001415/* Multiply by a single digit, ignoring the sign. */
1416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001417static PyLongObject *
Mark Dickinson5a74bf62009-02-15 11:04:38 +00001418mul1(PyLongObject *a, digit n)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001419{
Christian Heimes90aa7642007-12-19 02:45:37 +00001420 Py_ssize_t size_a = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001421 PyLongObject *z = _PyLong_New(size_a+1);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00001422 twodigits carry = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001423 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001424
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001425 if (z == NULL)
1426 return NULL;
1427 for (i = 0; i < size_a; ++i) {
1428 carry += (twodigits)a->ob_digit[i] * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001429 z->ob_digit[i] = (digit) (carry & PyLong_MASK);
1430 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001431 }
Guido van Rossum2095d241997-04-09 19:41:24 +00001432 z->ob_digit[i] = (digit) carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001433 return long_normalize(z);
1434}
1435
Tim Peters212e6142001-07-14 12:23:19 +00001436/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1437 in pout, and returning the remainder. pin and pout point at the LSD.
1438 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001439 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001440 immutable. */
1441
1442static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001444{
1445 twodigits rem = 0;
1446
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001447 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001448 pin += size;
1449 pout += size;
1450 while (--size >= 0) {
1451 digit hi;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001452 rem = (rem << PyLong_SHIFT) + *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001453 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001454 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001455 }
1456 return (digit)rem;
1457}
1458
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001459/* Divide a long integer by a digit, returning both the quotient
1460 (as function result) and the remainder (through *prem).
1461 The sign of a is ignored; n should not be zero. */
1462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001463static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001464divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001465{
Christian Heimes90aa7642007-12-19 02:45:37 +00001466 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001467 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001468
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001469 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001470 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001471 if (z == NULL)
1472 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001473 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001474 return long_normalize(z);
1475}
1476
1477/* Convert a long int object to a string, using a given conversion base.
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001478 Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001479 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001480
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001481PyObject *
1482_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001484 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001485 PyObject *str;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001486 Py_ssize_t i, j, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001487 Py_ssize_t size_a;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001488 Py_UNICODE *p;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001489 int bits;
1490 char sign = '\0';
Guido van Rossume32e0141992-01-19 16:31:05 +00001491
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001492 if (a == NULL || !PyLong_Check(a)) {
1493 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001494 return NULL;
1495 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001496 assert(base >= 2 && base <= 36);
Christian Heimes90aa7642007-12-19 02:45:37 +00001497 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001498
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499 /* Compute a rough upper bound for the length of the string */
1500 i = base;
1501 bits = 0;
1502 while (i > 1) {
1503 ++bits;
1504 i >>= 1;
1505 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00001506 i = 5;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001507 j = size_a*PyLong_SHIFT + bits-1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001508 sz = i + j / bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001509 if (j / PyLong_SHIFT < size_a || sz < i) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001510 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001511 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001512 return NULL;
1513 }
Walter Dörwald1ab83302007-05-18 17:15:44 +00001514 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001515 if (str == NULL)
1516 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001517 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001518 *p = '\0';
Christian Heimes90aa7642007-12-19 02:45:37 +00001519 if (Py_SIZE(a) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00001520 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001521
Christian Heimes90aa7642007-12-19 02:45:37 +00001522 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001523 *--p = '0';
1524 }
1525 else if ((base & (base - 1)) == 0) {
1526 /* JRH: special case for power-of-2 bases */
Tim Peters586b2e32001-07-15 09:11:14 +00001527 twodigits accum = 0;
1528 int accumbits = 0; /* # of bits in accum */
1529 int basebits = 1; /* # of bits in base-1 */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001530 i = base;
Tim Peters7d3a5112000-07-08 04:17:21 +00001531 while ((i >>= 1) > 1)
1532 ++basebits;
Tim Peters586b2e32001-07-15 09:11:14 +00001533
1534 for (i = 0; i < size_a; ++i) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00001535 accum |= (twodigits)a->ob_digit[i] << accumbits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001536 accumbits += PyLong_SHIFT;
Tim Peters586b2e32001-07-15 09:11:14 +00001537 assert(accumbits >= basebits);
1538 do {
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001539 char cdigit = (char)(accum & (base - 1));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001540 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001541 assert(p > PyUnicode_AS_UNICODE(str));
Martin v. Löwisa5854c22002-02-16 23:39:10 +00001542 *--p = cdigit;
Tim Peters586b2e32001-07-15 09:11:14 +00001543 accumbits -= basebits;
1544 accum >>= basebits;
1545 } while (i < size_a-1 ? accumbits >= basebits :
1546 accum > 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001548 }
1549 else {
Tim Petersfad225f2001-07-13 02:59:26 +00001550 /* Not 0, and base not a power of 2. Divide repeatedly by
1551 base, but for speed use the highest power of base that
1552 fits in a digit. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001553 Py_ssize_t size = size_a;
Tim Peters212e6142001-07-14 12:23:19 +00001554 digit *pin = a->ob_digit;
1555 PyLongObject *scratch;
1556 /* powbasw <- largest power of base that fits in a digit. */
Tim Petersfad225f2001-07-13 02:59:26 +00001557 digit powbase = base; /* powbase == base ** power */
1558 int power = 1;
1559 for (;;) {
Mark Dickinson134708a2009-02-25 20:33:49 +00001560 twodigits newpow = powbase * (twodigits)base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001561 if (newpow >> PyLong_SHIFT) /* doesn't fit in a digit */
Tim Petersfad225f2001-07-13 02:59:26 +00001562 break;
1563 powbase = (digit)newpow;
1564 ++power;
1565 }
Tim Peters212e6142001-07-14 12:23:19 +00001566
1567 /* Get a scratch area for repeated division. */
1568 scratch = _PyLong_New(size);
1569 if (scratch == NULL) {
1570 Py_DECREF(str);
1571 return NULL;
1572 }
1573
1574 /* Repeatedly divide by powbase. */
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001575 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001576 int ntostore = power;
Tim Peters212e6142001-07-14 12:23:19 +00001577 digit rem = inplace_divrem1(scratch->ob_digit,
1578 pin, size, powbase);
1579 pin = scratch->ob_digit; /* no need to use a again */
1580 if (pin[size - 1] == 0)
1581 --size;
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001582 SIGCHECK({
Tim Peters212e6142001-07-14 12:23:19 +00001583 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001584 Py_DECREF(str);
1585 return NULL;
1586 })
Tim Peters212e6142001-07-14 12:23:19 +00001587
1588 /* Break rem into digits. */
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001589 assert(ntostore > 0);
1590 do {
Tim Petersfad225f2001-07-13 02:59:26 +00001591 digit nextrem = (digit)(rem / base);
1592 char c = (char)(rem - nextrem * base);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001593 assert(p > PyUnicode_AS_UNICODE(str));
Raymond Hettinger3296e692005-06-29 23:29:56 +00001594 c += (c < 10) ? '0' : 'a'-10;
Tim Petersfad225f2001-07-13 02:59:26 +00001595 *--p = c;
1596 rem = nextrem;
Tim Petersc8a6b9b2001-07-14 11:01:28 +00001597 --ntostore;
1598 /* Termination is a bit delicate: must not
1599 store leading zeroes, so must get out if
Tim Peters212e6142001-07-14 12:23:19 +00001600 remaining quotient and rem are both 0. */
1601 } while (ntostore && (size || rem));
1602 } while (size != 0);
1603 Py_DECREF(scratch);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001604 }
1605
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001606 if (base == 16) {
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001607 *--p = 'x';
1608 *--p = '0';
1609 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001610 else if (base == 8) {
1611 *--p = 'o';
1612 *--p = '0';
1613 }
1614 else if (base == 2) {
1615 *--p = 'b';
1616 *--p = '0';
1617 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00001618 else if (base != 10) {
1619 *--p = '#';
1620 *--p = '0' + base%10;
1621 if (base > 10)
1622 *--p = '0' + base/10;
1623 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001624 if (sign)
1625 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001626 if (p != PyUnicode_AS_UNICODE(str)) {
1627 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001628 assert(p > q);
1629 do {
1630 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001631 q--;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001632 if (PyUnicode_Resize(&str, (Py_ssize_t) (q - PyUnicode_AS_UNICODE(str)))) {
1633 Py_DECREF(str);
1634 return NULL;
1635 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001636 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001637 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001638}
1639
Thomas Wouters477c8d52006-05-27 19:21:47 +00001640/* Table of digit values for 8-bit string -> integer conversion.
1641 * '0' maps to 0, ..., '9' maps to 9.
1642 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1643 * All other indices map to 37.
1644 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001645 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001647unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001648 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1649 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1650 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1651 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1652 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1653 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1657 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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};
1665
1666/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001667 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1668 * non-digit (which may be *str!). A normalized long is returned.
1669 * The point to this routine is that it takes time linear in the number of
1670 * string characters.
1671 */
1672static PyLongObject *
1673long_from_binary_base(char **str, int base)
1674{
1675 char *p = *str;
1676 char *start = p;
1677 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001678 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001679 PyLongObject *z;
1680 twodigits accum;
1681 int bits_in_accum;
1682 digit *pdigit;
1683
1684 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1685 n = base;
1686 for (bits_per_char = -1; n; ++bits_per_char)
1687 n >>= 1;
1688 /* n <- total # of bits needed, while setting p to end-of-string */
1689 n = 0;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001690 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001691 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001692 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001693 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1694 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001695 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001696 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001697 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001698 return NULL;
1699 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001700 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001701 z = _PyLong_New(n);
1702 if (z == NULL)
1703 return NULL;
1704 /* Read string from right, and fill in long from left; i.e.,
1705 * from least to most significant in both.
1706 */
1707 accum = 0;
1708 bits_in_accum = 0;
1709 pdigit = z->ob_digit;
1710 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001711 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001712 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001713 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001714 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001715 if (bits_in_accum >= PyLong_SHIFT) {
1716 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001717 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001718 accum >>= PyLong_SHIFT;
1719 bits_in_accum -= PyLong_SHIFT;
1720 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001721 }
1722 }
1723 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001724 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001725 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001726 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001727 }
1728 while (pdigit - z->ob_digit < n)
1729 *pdigit++ = 0;
1730 return long_normalize(z);
1731}
1732
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001733PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001734PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001735{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001736 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001737 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001738 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001739 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001740 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001741
Guido van Rossum472c04f1996-12-05 21:57:21 +00001742 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001743 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001744 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001745 return NULL;
1746 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001747 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001748 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749 if (*str == '+')
1750 ++str;
1751 else if (*str == '-') {
1752 ++str;
1753 sign = -1;
1754 }
1755 if (base == 0) {
1756 if (str[0] != '0')
1757 base = 10;
1758 else if (str[1] == 'x' || str[1] == 'X')
1759 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001760 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001761 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001762 else if (str[1] == 'b' || str[1] == 'B')
1763 base = 2;
1764 else {
1765 /* "old" (C-style) octal literal, now invalid.
1766 it might still be zero though */
1767 error_if_nonzero = 1;
1768 base = 10;
1769 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001770 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001771 if (str[0] == '0' &&
1772 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1773 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1774 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001776
Guido van Rossume6762971998-06-22 03:54:46 +00001777 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001778 if ((base & (base - 1)) == 0)
1779 z = long_from_binary_base(&str, base);
1780 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001781/***
1782Binary bases can be converted in time linear in the number of digits, because
1783Python's representation base is binary. Other bases (including decimal!) use
1784the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001785
Thomas Wouters477c8d52006-05-27 19:21:47 +00001786First some math: the largest integer that can be expressed in N base-B digits
1787is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1788case number of Python digits needed to hold it is the smallest integer n s.t.
1789
1790 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1791 BASE**n >= B**N [taking logs to base BASE]
1792 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1793
1794The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1795this quickly. A Python long with that much space is reserved near the start,
1796and the result is computed into it.
1797
1798The input string is actually treated as being in base base**i (i.e., i digits
1799are processed at a time), where two more static arrays hold:
1800
1801 convwidth_base[base] = the largest integer i such that base**i <= BASE
1802 convmultmax_base[base] = base ** convwidth_base[base]
1803
1804The first of these is the largest i such that i consecutive input digits
1805must fit in a single Python digit. The second is effectively the input
1806base we're really using.
1807
1808Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1809convmultmax_base[base], the result is "simply"
1810
1811 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1812
1813where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001814
1815Error analysis: as above, the number of Python digits `n` needed is worst-
1816case
1817
1818 n >= N * log(B)/log(BASE)
1819
1820where `N` is the number of input digits in base `B`. This is computed via
1821
1822 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1823
1824below. Two numeric concerns are how much space this can waste, and whether
1825the computed result can be too small. To be concrete, assume BASE = 2**15,
1826which is the default (and it's unlikely anyone changes that).
1827
1828Waste isn't a problem: provided the first input digit isn't 0, the difference
1829between the worst-case input with N digits and the smallest input with N
1830digits is about a factor of B, but B is small compared to BASE so at most
1831one allocated Python digit can remain unused on that count. If
1832N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1833and adding 1 returns a result 1 larger than necessary. However, that can't
1834happen: whenever B is a power of 2, long_from_binary_base() is called
1835instead, and it's impossible for B**i to be an integer power of 2**15 when
1836B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1837an exact integer when B is not a power of 2, since B**i has a prime factor
1838other than 2 in that case, but (2**15)**j's only prime factor is 2).
1839
1840The computed result can be too small if the true value of N*log(B)/log(BASE)
1841is a little bit larger than an exact integer, but due to roundoff errors (in
1842computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1843yields a numeric result a little less than that integer. Unfortunately, "how
1844close can a transcendental function get to an integer over some range?"
1845questions are generally theoretically intractable. Computer analysis via
1846continued fractions is practical: expand log(B)/log(BASE) via continued
1847fractions, giving a sequence i/j of "the best" rational approximations. Then
1848j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1849we can get very close to being in trouble, but very rarely. For example,
185076573 is a denominator in one of the continued-fraction approximations to
1851log(10)/log(2**15), and indeed:
1852
1853 >>> log(10)/log(2**15)*76573
1854 16958.000000654003
1855
1856is very close to an integer. If we were working with IEEE single-precision,
1857rounding errors could kill us. Finding worst cases in IEEE double-precision
1858requires better-than-double-precision log() functions, and Tim didn't bother.
1859Instead the code checks to see whether the allocated space is enough as each
1860new Python digit is added, and copies the whole thing to a larger long if not.
1861This should happen extremely rarely, and in fact I don't have a test case
1862that triggers it(!). Instead the code was tested by artificially allocating
1863just 1 digit at the start, so that the copying code was exercised for every
1864digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001865***/
1866 register twodigits c; /* current input character */
1867 Py_ssize_t size_z;
1868 int i;
1869 int convwidth;
1870 twodigits convmultmax, convmult;
1871 digit *pz, *pzstop;
1872 char* scan;
1873
1874 static double log_base_BASE[37] = {0.0e0,};
1875 static int convwidth_base[37] = {0,};
1876 static twodigits convmultmax_base[37] = {0,};
1877
1878 if (log_base_BASE[base] == 0.0) {
1879 twodigits convmax = base;
1880 int i = 1;
1881
1882 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001883 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001884 for (;;) {
1885 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001886 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001887 break;
1888 convmax = next;
1889 ++i;
1890 }
1891 convmultmax_base[base] = convmax;
1892 assert(i > 0);
1893 convwidth_base[base] = i;
1894 }
1895
1896 /* Find length of the string of numeric characters. */
1897 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001898 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899 ++scan;
1900
1901 /* Create a long object that can contain the largest possible
1902 * integer with this base and length. Note that there's no
1903 * need to initialize z->ob_digit -- no slot is read up before
1904 * being stored into.
1905 */
1906 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001907 /* Uncomment next line to test exceedingly rare copy code */
1908 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001909 assert(size_z > 0);
1910 z = _PyLong_New(size_z);
1911 if (z == NULL)
1912 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001913 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914
1915 /* `convwidth` consecutive input digits are treated as a single
1916 * digit in base `convmultmax`.
1917 */
1918 convwidth = convwidth_base[base];
1919 convmultmax = convmultmax_base[base];
1920
1921 /* Work ;-) */
1922 while (str < scan) {
1923 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001924 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001925 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1926 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00001927 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001928 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929 }
1930
1931 convmult = convmultmax;
1932 /* Calculate the shift only if we couldn't get
1933 * convwidth digits.
1934 */
1935 if (i != convwidth) {
1936 convmult = base;
1937 for ( ; i > 1; --i)
1938 convmult *= base;
1939 }
1940
1941 /* Multiply z by convmult, and add c. */
1942 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001943 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001944 for (; pz < pzstop; ++pz) {
1945 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001946 *pz = (digit)(c & PyLong_MASK);
1947 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948 }
1949 /* carry off the current end? */
1950 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001951 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001952 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001953 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001954 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001955 }
1956 else {
1957 PyLongObject *tmp;
1958 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001959 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001960 tmp = _PyLong_New(size_z + 1);
1961 if (tmp == NULL) {
1962 Py_DECREF(z);
1963 return NULL;
1964 }
1965 memcpy(tmp->ob_digit,
1966 z->ob_digit,
1967 sizeof(digit) * size_z);
1968 Py_DECREF(z);
1969 z = tmp;
1970 z->ob_digit[size_z] = (digit)c;
1971 ++size_z;
1972 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001973 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001974 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001975 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001976 if (z == NULL)
1977 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001978 if (error_if_nonzero) {
1979 /* reset the base to 0, else the exception message
1980 doesn't make too much sense */
1981 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001982 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001983 goto onError;
1984 /* there might still be other problems, therefore base
1985 remains zero here for the same reason */
1986 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001987 if (str == start)
1988 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001990 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001991 while (*str && isspace(Py_CHARMASK(*str)))
1992 str++;
1993 if (*str != '\0')
1994 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001995 if (pend)
1996 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00001997 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00001998 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00001999
2000 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002001 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002002 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002003 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002004 if (strobj == NULL)
2005 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002006 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002007 "invalid literal for int() with base %d: %R",
2008 base, strobj);
2009 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002010 return NULL;
2011}
2012
2013PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002014PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002015{
Walter Dörwald07e14762002-11-06 16:15:14 +00002016 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002017 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002018
Walter Dörwald07e14762002-11-06 16:15:14 +00002019 if (buffer == NULL)
2020 return NULL;
2021
2022 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2023 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002024 return NULL;
2025 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002026 result = PyLong_FromString(buffer, NULL, base);
2027 PyMem_FREE(buffer);
2028 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002029}
2030
Tim Peters9f688bf2000-07-07 15:53:28 +00002031/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002033 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002034static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002035
2036/* Long division with remainder, top-level routine */
2037
Guido van Rossume32e0141992-01-19 16:31:05 +00002038static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002039long_divrem(PyLongObject *a, PyLongObject *b,
2040 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002041{
Christian Heimes90aa7642007-12-19 02:45:37 +00002042 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002044
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002045 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002046 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002047 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002048 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049 }
2050 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002051 (size_a == size_b &&
2052 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002054 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002055 if (*pdiv == NULL)
2056 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002057 Py_INCREF(a);
2058 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002059 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002060 }
2061 if (size_b == 1) {
2062 digit rem = 0;
2063 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002064 if (z == NULL)
2065 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002066 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002067 if (*prem == NULL) {
2068 Py_DECREF(z);
2069 return -1;
2070 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002071 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002072 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002073 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002074 if (z == NULL)
2075 return -1;
2076 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002077 /* Set the signs.
2078 The quotient z has the sign of a*b;
2079 the remainder r has the sign of a,
2080 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002081 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002082 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002083 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002084 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002085 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002086 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002087}
2088
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002089/* Unsigned long division with remainder -- the algorithm */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002091static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002092x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002093{
Christian Heimes90aa7642007-12-19 02:45:37 +00002094 Py_ssize_t size_v = ABS(Py_SIZE(v1)), size_w = ABS(Py_SIZE(w1));
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002095 digit d = (digit) ((twodigits)PyLong_BASE / (w1->ob_digit[size_w-1] + 1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 PyLongObject *v = mul1(v1, d);
2097 PyLongObject *w = mul1(w1, d);
2098 PyLongObject *a;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002099 Py_ssize_t j, k;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002100
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002101 if (v == NULL || w == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 Py_XDECREF(v);
2103 Py_XDECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002104 return NULL;
2105 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002106
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002107 assert(size_v >= size_w && size_w > 1); /* Assert checks by div() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002108 assert(Py_REFCNT(v) == 1); /* Since v will be used as accumulator! */
2109 assert(size_w == ABS(Py_SIZE(w))); /* That's how d was calculated */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002110
Christian Heimes90aa7642007-12-19 02:45:37 +00002111 size_v = ABS(Py_SIZE(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +00002112 k = size_v - size_w;
2113 a = _PyLong_New(k + 1);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002114
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115 for (j = size_v; a != NULL && k >= 0; --j, --k) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002116 digit vj = (j >= size_v) ? 0 : v->ob_digit[j];
2117 twodigits q;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002118 stwodigits carry = 0;
Mark Dickinson17e55872009-01-24 15:56:57 +00002119 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002120
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002121 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 Py_DECREF(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002123 a = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002124 break;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002125 })
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002126 if (vj == w->ob_digit[size_w-1])
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002127 q = PyLong_MASK;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002128 else
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002129 q = (((twodigits)vj << PyLong_SHIFT) + v->ob_digit[j-1]) /
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 w->ob_digit[size_w-1];
Tim Peters5af4e6c2002-08-12 02:31:19 +00002131
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002132 while (w->ob_digit[size_w-2]*q >
2133 ((
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002134 ((twodigits)vj << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002135 + v->ob_digit[j-1]
2136 - q*w->ob_digit[size_w-1]
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002137 ) << PyLong_SHIFT)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002138 + v->ob_digit[j-2])
2139 --q;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002140
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002141 for (i = 0; i < size_w && i+k < size_v; ++i) {
2142 twodigits z = w->ob_digit[i] * q;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002143 digit zz = (digit) (z >> PyLong_SHIFT);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 carry += v->ob_digit[i+k] - z
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002145 + ((twodigits)zz << PyLong_SHIFT);
2146 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Mark Dickinsone4416742009-02-15 15:14:57 +00002147 carry = Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002148 carry, PyLong_SHIFT);
Tim Peters7d3a5112000-07-08 04:17:21 +00002149 carry -= zz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002150 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002151
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002152 if (i+k < size_v) {
2153 carry += v->ob_digit[i+k];
2154 v->ob_digit[i+k] = 0;
2155 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002156
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157 if (carry == 0)
Guido van Rossum2095d241997-04-09 19:41:24 +00002158 a->ob_digit[k] = (digit) q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002159 else {
2160 assert(carry == -1);
Guido van Rossum2095d241997-04-09 19:41:24 +00002161 a->ob_digit[k] = (digit) q-1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002162 carry = 0;
2163 for (i = 0; i < size_w && i+k < size_v; ++i) {
2164 carry += v->ob_digit[i+k] + w->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002165 v->ob_digit[i+k] = (digit)(carry & PyLong_MASK);
Tim Peters7d3a5112000-07-08 04:17:21 +00002166 carry = Py_ARITHMETIC_RIGHT_SHIFT(
Mark Dickinsone4416742009-02-15 15:14:57 +00002167 stwodigits,
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002168 carry, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002169 }
2170 }
2171 } /* for j, k */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002172
Guido van Rossumc206c761995-01-10 15:23:19 +00002173 if (a == NULL)
2174 *prem = NULL;
2175 else {
Guido van Rossumc6913e71991-11-19 20:26:46 +00002176 a = long_normalize(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002177 *prem = divrem1(v, d, &d);
2178 /* d receives the (unused) remainder */
2179 if (*prem == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002180 Py_DECREF(a);
Guido van Rossume32e0141992-01-19 16:31:05 +00002181 a = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00002182 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184 Py_DECREF(v);
2185 Py_DECREF(w);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002186 return a;
2187}
2188
2189/* Methods */
2190
2191static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002192long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002193{
Christian Heimes90aa7642007-12-19 02:45:37 +00002194 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002195}
2196
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002197static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002198long_repr(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002199{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002200 return _PyLong_Format(v, 10);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002201}
2202
2203static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002204long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002205{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002206 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002207
Christian Heimes90aa7642007-12-19 02:45:37 +00002208 if (Py_SIZE(a) != Py_SIZE(b)) {
2209 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002210 sign = 0;
2211 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002212 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002213 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002214 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002215 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002216 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2217 ;
2218 if (i < 0)
2219 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002220 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002221 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002222 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002223 sign = -sign;
2224 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002225 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002226 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002227}
2228
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002229#define TEST_COND(cond) \
2230 ((cond) ? Py_True : Py_False)
2231
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002232static PyObject *
2233long_richcompare(PyObject *self, PyObject *other, int op)
2234{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002235 int result;
2236 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002237 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002238 if (self == other)
2239 result = 0;
2240 else
2241 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2242 /* Convert the return value to a Boolean */
2243 switch (op) {
2244 case Py_EQ:
2245 v = TEST_COND(result == 0);
2246 break;
2247 case Py_NE:
2248 v = TEST_COND(result != 0);
2249 break;
2250 case Py_LE:
2251 v = TEST_COND(result <= 0);
2252 break;
2253 case Py_GE:
2254 v = TEST_COND(result >= 0);
2255 break;
2256 case Py_LT:
2257 v = TEST_COND(result == -1);
2258 break;
2259 case Py_GT:
2260 v = TEST_COND(result == 1);
2261 break;
2262 default:
2263 PyErr_BadArgument();
2264 return NULL;
2265 }
2266 Py_INCREF(v);
2267 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002268}
2269
Guido van Rossum9bfef441993-03-29 10:43:31 +00002270static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002271long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002272{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002273 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002274 Py_ssize_t i;
2275 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002276
2277 /* This is designed so that Python ints and longs with the
2278 same value hash to the same value, otherwise comparisons
2279 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002280 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002281 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002282 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002283 case 0: return 0;
2284 case 1: return v->ob_digit[0];
2285 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002286 sign = 1;
2287 x = 0;
2288 if (i < 0) {
2289 sign = -1;
2290 i = -(i);
2291 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002292 /* The following loop produces a C unsigned long x such that x is
2293 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002294 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002295 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002296 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002297 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002298 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002299 /* If the addition above overflowed we compensate by
2300 incrementing. This preserves the value modulo
2301 ULONG_MAX. */
2302 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002303 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002304 }
2305 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002306 if (x == (unsigned long)-1)
2307 x = (unsigned long)-2;
2308 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002309}
2310
2311
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002312/* Add the absolute values of two long integers. */
2313
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002314static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002315x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002316{
Christian Heimes90aa7642007-12-19 02:45:37 +00002317 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002318 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002319 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002320 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002321
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002322 /* Ensure a is the larger of the two: */
2323 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002325 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002326 size_a = size_b;
2327 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002328 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002329 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330 if (z == NULL)
2331 return NULL;
2332 for (i = 0; i < size_b; ++i) {
2333 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002334 z->ob_digit[i] = carry & PyLong_MASK;
2335 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002336 }
2337 for (; i < size_a; ++i) {
2338 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002339 z->ob_digit[i] = carry & PyLong_MASK;
2340 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002341 }
2342 z->ob_digit[i] = carry;
2343 return long_normalize(z);
2344}
2345
2346/* Subtract the absolute values of two integers. */
2347
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002348static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002349x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002350{
Christian Heimes90aa7642007-12-19 02:45:37 +00002351 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002352 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002353 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002354 int sign = 1;
2355 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002356
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357 /* Ensure a is the larger of the two: */
2358 if (size_a < size_b) {
2359 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002360 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002361 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362 size_a = size_b;
2363 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364 }
2365 else if (size_a == size_b) {
2366 /* Find highest digit where a and b differ: */
2367 i = size_a;
2368 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2369 ;
2370 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002371 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002372 if (a->ob_digit[i] < b->ob_digit[i]) {
2373 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002374 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375 }
2376 size_a = size_b = i+1;
2377 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002378 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002379 if (z == NULL)
2380 return NULL;
2381 for (i = 0; i < size_b; ++i) {
2382 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002383 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002384 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002385 z->ob_digit[i] = borrow & PyLong_MASK;
2386 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002387 borrow &= 1; /* Keep only one sign bit */
2388 }
2389 for (; i < size_a; ++i) {
2390 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002391 z->ob_digit[i] = borrow & PyLong_MASK;
2392 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002393 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002394 }
2395 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002396 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002397 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002398 return long_normalize(z);
2399}
2400
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002401static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002402long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002403{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002404 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002405
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002406 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002407
Christian Heimes90aa7642007-12-19 02:45:37 +00002408 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002409 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002410 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002411 return result;
2412 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002413 if (Py_SIZE(a) < 0) {
2414 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002415 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002416 if (z != NULL && Py_SIZE(z) != 0)
2417 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002418 }
2419 else
2420 z = x_sub(b, a);
2421 }
2422 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002423 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002424 z = x_sub(a, b);
2425 else
2426 z = x_add(a, b);
2427 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002428 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002429}
2430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002431static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002432long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002433{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002434 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002435
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002436 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002437
Christian Heimes90aa7642007-12-19 02:45:37 +00002438 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002439 PyObject* r;
2440 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002441 return r;
2442 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002443 if (Py_SIZE(a) < 0) {
2444 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002445 z = x_sub(a, b);
2446 else
2447 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002448 if (z != NULL && Py_SIZE(z) != 0)
2449 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002450 }
2451 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002452 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002453 z = x_add(a, b);
2454 else
2455 z = x_sub(a, b);
2456 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002457 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002458}
2459
Tim Peters5af4e6c2002-08-12 02:31:19 +00002460/* Grade school multiplication, ignoring the signs.
2461 * Returns the absolute value of the product, or NULL if error.
2462 */
2463static PyLongObject *
2464x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002465{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002466 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002467 Py_ssize_t size_a = ABS(Py_SIZE(a));
2468 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002469 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002470
Tim Peters5af4e6c2002-08-12 02:31:19 +00002471 z = _PyLong_New(size_a + size_b);
2472 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002473 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474
Christian Heimes90aa7642007-12-19 02:45:37 +00002475 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002476 if (a == b) {
2477 /* Efficient squaring per HAC, Algorithm 14.16:
2478 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2479 * Gives slightly less than a 2x speedup when a == b,
2480 * via exploiting that each entry in the multiplication
2481 * pyramid appears twice (except for the size_a squares).
2482 */
2483 for (i = 0; i < size_a; ++i) {
2484 twodigits carry;
2485 twodigits f = a->ob_digit[i];
2486 digit *pz = z->ob_digit + (i << 1);
2487 digit *pa = a->ob_digit + i + 1;
2488 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002489
Tim Peters0973b992004-08-29 22:16:50 +00002490 SIGCHECK({
2491 Py_DECREF(z);
2492 return NULL;
2493 })
2494
2495 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002496 *pz++ = (digit)(carry & PyLong_MASK);
2497 carry >>= PyLong_SHIFT;
2498 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002499
2500 /* Now f is added in twice in each column of the
2501 * pyramid it appears. Same as adding f<<1 once.
2502 */
2503 f <<= 1;
2504 while (pa < paend) {
2505 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002506 *pz++ = (digit)(carry & PyLong_MASK);
2507 carry >>= PyLong_SHIFT;
2508 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002509 }
2510 if (carry) {
2511 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002512 *pz++ = (digit)(carry & PyLong_MASK);
2513 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002514 }
2515 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002516 *pz += (digit)(carry & PyLong_MASK);
2517 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002518 }
Tim Peters0973b992004-08-29 22:16:50 +00002519 }
2520 else { /* a is not the same as b -- gradeschool long mult */
2521 for (i = 0; i < size_a; ++i) {
2522 twodigits carry = 0;
2523 twodigits f = a->ob_digit[i];
2524 digit *pz = z->ob_digit + i;
2525 digit *pb = b->ob_digit;
2526 digit *pbend = b->ob_digit + size_b;
2527
2528 SIGCHECK({
2529 Py_DECREF(z);
2530 return NULL;
2531 })
2532
2533 while (pb < pbend) {
2534 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002535 *pz++ = (digit)(carry & PyLong_MASK);
2536 carry >>= PyLong_SHIFT;
2537 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002538 }
2539 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002540 *pz += (digit)(carry & PyLong_MASK);
2541 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002542 }
2543 }
Tim Peters44121a62002-08-12 06:17:58 +00002544 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002545}
2546
2547/* A helper for Karatsuba multiplication (k_mul).
2548 Takes a long "n" and an integer "size" representing the place to
2549 split, and sets low and high such that abs(n) == (high << size) + low,
2550 viewing the shift as being by digits. The sign bit is ignored, and
2551 the return values are >= 0.
2552 Returns 0 on success, -1 on failure.
2553*/
2554static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002555kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002556{
2557 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002558 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002559 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002560
2561 size_lo = MIN(size_n, size);
2562 size_hi = size_n - size_lo;
2563
2564 if ((hi = _PyLong_New(size_hi)) == NULL)
2565 return -1;
2566 if ((lo = _PyLong_New(size_lo)) == NULL) {
2567 Py_DECREF(hi);
2568 return -1;
2569 }
2570
2571 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2572 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2573
2574 *high = long_normalize(hi);
2575 *low = long_normalize(lo);
2576 return 0;
2577}
2578
Tim Peters60004642002-08-12 22:01:34 +00002579static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2580
Tim Peters5af4e6c2002-08-12 02:31:19 +00002581/* Karatsuba multiplication. Ignores the input signs, and returns the
2582 * absolute value of the product (or NULL if error).
2583 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2584 */
2585static PyLongObject *
2586k_mul(PyLongObject *a, PyLongObject *b)
2587{
Christian Heimes90aa7642007-12-19 02:45:37 +00002588 Py_ssize_t asize = ABS(Py_SIZE(a));
2589 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002590 PyLongObject *ah = NULL;
2591 PyLongObject *al = NULL;
2592 PyLongObject *bh = NULL;
2593 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002594 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002595 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002596 Py_ssize_t shift; /* the number of digits we split off */
2597 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002598
Tim Peters5af4e6c2002-08-12 02:31:19 +00002599 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2600 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2601 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002602 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002603 * By picking X to be a power of 2, "*X" is just shifting, and it's
2604 * been reduced to 3 multiplies on numbers half the size.
2605 */
2606
Tim Petersfc07e562002-08-12 02:54:10 +00002607 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002608 * is largest.
2609 */
Tim Peters738eda72002-08-12 15:08:20 +00002610 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002611 t1 = a;
2612 a = b;
2613 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002614
2615 i = asize;
2616 asize = bsize;
2617 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002618 }
2619
2620 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002621 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2622 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002623 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002624 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002625 else
2626 return x_mul(a, b);
2627 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002628
Tim Peters60004642002-08-12 22:01:34 +00002629 /* If a is small compared to b, splitting on b gives a degenerate
2630 * case with ah==0, and Karatsuba may be (even much) less efficient
2631 * than "grade school" then. However, we can still win, by viewing
2632 * b as a string of "big digits", each of width a->ob_size. That
2633 * leads to a sequence of balanced calls to k_mul.
2634 */
2635 if (2 * asize <= bsize)
2636 return k_lopsided_mul(a, b);
2637
Tim Petersd6974a52002-08-13 20:37:51 +00002638 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002639 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002640 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002641 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002642
Tim Peters0973b992004-08-29 22:16:50 +00002643 if (a == b) {
2644 bh = ah;
2645 bl = al;
2646 Py_INCREF(bh);
2647 Py_INCREF(bl);
2648 }
2649 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002650
Tim Petersd64c1de2002-08-12 17:36:03 +00002651 /* The plan:
2652 * 1. Allocate result space (asize + bsize digits: that's always
2653 * enough).
2654 * 2. Compute ah*bh, and copy into result at 2*shift.
2655 * 3. Compute al*bl, and copy into result at 0. Note that this
2656 * can't overlap with #2.
2657 * 4. Subtract al*bl from the result, starting at shift. This may
2658 * underflow (borrow out of the high digit), but we don't care:
2659 * we're effectively doing unsigned arithmetic mod
2660 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2661 * borrows and carries out of the high digit can be ignored.
2662 * 5. Subtract ah*bh from the result, starting at shift.
2663 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2664 * at shift.
2665 */
2666
2667 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002668 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002669 if (ret == NULL) goto fail;
2670#ifdef Py_DEBUG
2671 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002672 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002673#endif
Tim Peters44121a62002-08-12 06:17:58 +00002674
Tim Petersd64c1de2002-08-12 17:36:03 +00002675 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002676 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002677 assert(Py_SIZE(t1) >= 0);
2678 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002679 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002680 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002681
2682 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002683 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002684 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002685 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002686 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002687
Tim Petersd64c1de2002-08-12 17:36:03 +00002688 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002689 if ((t2 = k_mul(al, bl)) == NULL) {
2690 Py_DECREF(t1);
2691 goto fail;
2692 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002693 assert(Py_SIZE(t2) >= 0);
2694 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2695 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002696
2697 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002698 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002699 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002700 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002701
Tim Petersd64c1de2002-08-12 17:36:03 +00002702 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2703 * because it's fresher in cache.
2704 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002705 i = Py_SIZE(ret) - shift; /* # digits after shift */
2706 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002707 Py_DECREF(t2);
2708
Christian Heimes90aa7642007-12-19 02:45:37 +00002709 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002710 Py_DECREF(t1);
2711
Tim Petersd64c1de2002-08-12 17:36:03 +00002712 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002713 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2714 Py_DECREF(ah);
2715 Py_DECREF(al);
2716 ah = al = NULL;
2717
Tim Peters0973b992004-08-29 22:16:50 +00002718 if (a == b) {
2719 t2 = t1;
2720 Py_INCREF(t2);
2721 }
2722 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002723 Py_DECREF(t1);
2724 goto fail;
2725 }
2726 Py_DECREF(bh);
2727 Py_DECREF(bl);
2728 bh = bl = NULL;
2729
Tim Peters738eda72002-08-12 15:08:20 +00002730 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002731 Py_DECREF(t1);
2732 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002733 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002734 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002735
Tim Petersd6974a52002-08-13 20:37:51 +00002736 /* Add t3. It's not obvious why we can't run out of room here.
2737 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002738 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002739 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002740 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002741
Tim Peters5af4e6c2002-08-12 02:31:19 +00002742 return long_normalize(ret);
2743
2744 fail:
2745 Py_XDECREF(ret);
2746 Py_XDECREF(ah);
2747 Py_XDECREF(al);
2748 Py_XDECREF(bh);
2749 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002750 return NULL;
2751}
2752
Tim Petersd6974a52002-08-13 20:37:51 +00002753/* (*) Why adding t3 can't "run out of room" above.
2754
Tim Petersab86c2b2002-08-15 20:06:00 +00002755Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2756to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002757
Tim Petersab86c2b2002-08-15 20:06:00 +000027581. For any integer i, i = c(i/2) + f(i/2). In particular,
2759 bsize = c(bsize/2) + f(bsize/2).
27602. shift = f(bsize/2)
27613. asize <= bsize
27624. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2763 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002764
Tim Petersab86c2b2002-08-15 20:06:00 +00002765We allocated asize + bsize result digits, and add t3 into them at an offset
2766of shift. This leaves asize+bsize-shift allocated digit positions for t3
2767to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2768asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002769
Tim Petersab86c2b2002-08-15 20:06:00 +00002770bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2771at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002772
Tim Petersab86c2b2002-08-15 20:06:00 +00002773If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2774digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2775most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002776
Tim Petersab86c2b2002-08-15 20:06:00 +00002777The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002778
Tim Petersab86c2b2002-08-15 20:06:00 +00002779 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002780
Tim Petersab86c2b2002-08-15 20:06:00 +00002781and we have asize + c(bsize/2) available digit positions. We need to show
2782this is always enough. An instance of c(bsize/2) cancels out in both, so
2783the question reduces to whether asize digits is enough to hold
2784(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2785then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2786asize 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 +00002787digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002788asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002789c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2790is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2791bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002792
Tim Peters48d52c02002-08-14 17:07:32 +00002793Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2794clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2795ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002796*/
2797
Tim Peters60004642002-08-12 22:01:34 +00002798/* b has at least twice the digits of a, and a is big enough that Karatsuba
2799 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2800 * of slices, each with a->ob_size digits, and multiply the slices by a,
2801 * one at a time. This gives k_mul balanced inputs to work with, and is
2802 * also cache-friendly (we compute one double-width slice of the result
2803 * at a time, then move on, never bactracking except for the helpful
2804 * single-width slice overlap between successive partial sums).
2805 */
2806static PyLongObject *
2807k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2808{
Christian Heimes90aa7642007-12-19 02:45:37 +00002809 const Py_ssize_t asize = ABS(Py_SIZE(a));
2810 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002811 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002812 PyLongObject *ret;
2813 PyLongObject *bslice = NULL;
2814
2815 assert(asize > KARATSUBA_CUTOFF);
2816 assert(2 * asize <= bsize);
2817
2818 /* Allocate result space, and zero it out. */
2819 ret = _PyLong_New(asize + bsize);
2820 if (ret == NULL)
2821 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002822 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002823
2824 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00002825 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00002826 if (bslice == NULL)
2827 goto fail;
2828
2829 nbdone = 0;
2830 while (bsize > 0) {
2831 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002832 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00002833
2834 /* Multiply the next slice of b by a. */
2835 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
2836 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00002837 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00002838 product = k_mul(a, bslice);
2839 if (product == NULL)
2840 goto fail;
2841
2842 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002843 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
2844 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00002845 Py_DECREF(product);
2846
2847 bsize -= nbtouse;
2848 nbdone += nbtouse;
2849 }
2850
2851 Py_DECREF(bslice);
2852 return long_normalize(ret);
2853
2854 fail:
2855 Py_DECREF(ret);
2856 Py_XDECREF(bslice);
2857 return NULL;
2858}
Tim Peters5af4e6c2002-08-12 02:31:19 +00002859
2860static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002861long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002862{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002863 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002864
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002865 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002866
Christian Heimes90aa7642007-12-19 02:45:37 +00002867 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002868 PyObject *r;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002869 r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002870 return r;
2871 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00002872
Tim Petersd64c1de2002-08-12 17:36:03 +00002873 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00002874 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002875 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002876 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00002877 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002878}
2879
Guido van Rossume32e0141992-01-19 16:31:05 +00002880/* The / and % operators are now defined in terms of divmod().
2881 The expression a mod b has the value a - b*floor(a/b).
2882 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002883 |a| by |b|, with the sign of a. This is also expressed
2884 as a - b*trunc(a/b), if trunc truncates towards zero.
2885 Some examples:
2886 a b a rem b a mod b
2887 13 10 3 3
2888 -13 10 -3 7
2889 13 -10 3 -7
2890 -13 -10 -3 -3
2891 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002892 have different signs. We then subtract one from the 'div'
2893 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002894
Tim Peters47e52ee2004-08-30 02:44:38 +00002895/* Compute
2896 * *pdiv, *pmod = divmod(v, w)
2897 * NULL can be passed for pdiv or pmod, in which case that part of
2898 * the result is simply thrown away. The caller owns a reference to
2899 * each of these it requests (does not pass NULL for).
2900 */
Guido van Rossume32e0141992-01-19 16:31:05 +00002901static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00002902l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00002903 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00002904{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002905 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002906
Guido van Rossume32e0141992-01-19 16:31:05 +00002907 if (long_divrem(v, w, &div, &mod) < 0)
2908 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00002909 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
2910 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002911 PyLongObject *temp;
2912 PyLongObject *one;
2913 temp = (PyLongObject *) long_add(mod, w);
2914 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00002915 mod = temp;
2916 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002917 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002918 return -1;
2919 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002920 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00002921 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002922 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
2923 Py_DECREF(mod);
2924 Py_DECREF(div);
2925 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00002926 return -1;
2927 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002928 Py_DECREF(one);
2929 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00002930 div = temp;
2931 }
Tim Peters47e52ee2004-08-30 02:44:38 +00002932 if (pdiv != NULL)
2933 *pdiv = div;
2934 else
2935 Py_DECREF(div);
2936
2937 if (pmod != NULL)
2938 *pmod = mod;
2939 else
2940 Py_DECREF(mod);
2941
Guido van Rossume32e0141992-01-19 16:31:05 +00002942 return 0;
2943}
2944
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002945static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002946long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00002947{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002948 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002949
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002950 CHECK_BINOP(a, b);
2951 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00002952 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002953 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00002954}
2955
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002956static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002957long_true_divide(PyObject *a, PyObject *b)
Tim Peters20dab9f2001-09-04 05:31:47 +00002958{
Tim Peterse2a60002001-09-04 06:17:36 +00002959 double ad, bd;
Thomas Wouters553489a2006-02-01 21:32:04 +00002960 int failed, aexp = -1, bexp = -1;
Tim Peterse2a60002001-09-04 06:17:36 +00002961
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002962 CHECK_BINOP(a, b);
Tim Peterse2a60002001-09-04 06:17:36 +00002963 ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp);
2964 bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp);
Tim Peters6f97e492001-11-04 23:09:40 +00002965 failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred();
Tim Peters6f97e492001-11-04 23:09:40 +00002966 if (failed)
Tim Peterse2a60002001-09-04 06:17:36 +00002967 return NULL;
Thomas Wouters553489a2006-02-01 21:32:04 +00002968 /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x,
2969 but should really be set correctly after sucessful calls to
2970 _PyLong_AsScaledDouble() */
2971 assert(aexp >= 0 && bexp >= 0);
Tim Peterse2a60002001-09-04 06:17:36 +00002972
2973 if (bd == 0.0) {
2974 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002975 "int division or modulo by zero");
Tim Peterse2a60002001-09-04 06:17:36 +00002976 return NULL;
2977 }
2978
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002979 /* True value is very close to ad/bd * 2**(PyLong_SHIFT*(aexp-bexp)) */
Tim Peterse2a60002001-09-04 06:17:36 +00002980 ad /= bd; /* overflow/underflow impossible here */
2981 aexp -= bexp;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002982 if (aexp > INT_MAX / PyLong_SHIFT)
Tim Peterse2a60002001-09-04 06:17:36 +00002983 goto overflow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002984 else if (aexp < -(INT_MAX / PyLong_SHIFT))
Tim Peterse56ed9b2001-09-06 21:59:14 +00002985 return PyFloat_FromDouble(0.0); /* underflow to 0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002986 errno = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002987 ad = ldexp(ad, aexp * PyLong_SHIFT);
Tim Peters57f282a2001-09-05 05:38:10 +00002988 if (Py_OVERFLOWED(ad)) /* ignore underflow to 0.0 */
Tim Peterse2a60002001-09-04 06:17:36 +00002989 goto overflow;
2990 return PyFloat_FromDouble(ad);
2991
2992overflow:
2993 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002994 "int/int too large for a float");
Tim Peterse2a60002001-09-04 06:17:36 +00002995 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996
Tim Peters20dab9f2001-09-04 05:31:47 +00002997}
2998
2999static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003000long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003001{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003002 PyLongObject *mod;
3003
3004 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003005
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003006 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003007 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003008 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003009}
3010
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003011static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003012long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003013{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003014 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003015 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003016
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003017 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003018
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003019 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003020 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003021 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003022 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003023 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003024 PyTuple_SetItem(z, 0, (PyObject *) div);
3025 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003026 }
3027 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003028 Py_DECREF(div);
3029 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003030 }
3031 return z;
3032}
3033
Tim Peters47e52ee2004-08-30 02:44:38 +00003034/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003035static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003036long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003037{
Tim Peters47e52ee2004-08-30 02:44:38 +00003038 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3039 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003040
Tim Peters47e52ee2004-08-30 02:44:38 +00003041 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003042 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003043 PyLongObject *temp = NULL;
3044
3045 /* 5-ary values. If the exponent is large enough, table is
3046 * precomputed so that table[i] == a**i % c for i in range(32).
3047 */
3048 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3049 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3050
3051 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003052 CHECK_BINOP(v, w);
3053 a = (PyLongObject*)v; Py_INCREF(a);
3054 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003055 if (PyLong_Check(x)) {
3056 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003057 Py_INCREF(x);
3058 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003059 else if (x == Py_None)
3060 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003061 else {
3062 Py_DECREF(a);
3063 Py_DECREF(b);
3064 Py_INCREF(Py_NotImplemented);
3065 return Py_NotImplemented;
3066 }
Tim Peters4c483c42001-09-05 06:24:58 +00003067
Christian Heimes90aa7642007-12-19 02:45:37 +00003068 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003069 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003070 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003071 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003072 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003073 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003074 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003075 /* else return a float. This works because we know
3076 that this calls float_pow() which converts its
3077 arguments to double. */
3078 Py_DECREF(a);
3079 Py_DECREF(b);
3080 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003081 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003082 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003083
3084 if (c) {
3085 /* if modulus == 0:
3086 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003087 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003088 PyErr_SetString(PyExc_ValueError,
3089 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003090 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003091 }
3092
3093 /* if modulus < 0:
3094 negativeOutput = True
3095 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003096 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003097 negativeOutput = 1;
3098 temp = (PyLongObject *)_PyLong_Copy(c);
3099 if (temp == NULL)
3100 goto Error;
3101 Py_DECREF(c);
3102 c = temp;
3103 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003104 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003105 }
3106
3107 /* if modulus == 1:
3108 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003109 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003110 z = (PyLongObject *)PyLong_FromLong(0L);
3111 goto Done;
3112 }
3113
3114 /* if base < 0:
3115 base = base % modulus
3116 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003117 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003118 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003119 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003120 Py_DECREF(a);
3121 a = temp;
3122 temp = NULL;
3123 }
3124 }
3125
3126 /* At this point a, b, and c are guaranteed non-negative UNLESS
3127 c is NULL, in which case a may be negative. */
3128
3129 z = (PyLongObject *)PyLong_FromLong(1L);
3130 if (z == NULL)
3131 goto Error;
3132
3133 /* Perform a modular reduction, X = X % c, but leave X alone if c
3134 * is NULL.
3135 */
3136#define REDUCE(X) \
3137 if (c != NULL) { \
3138 if (l_divmod(X, c, NULL, &temp) < 0) \
3139 goto Error; \
3140 Py_XDECREF(X); \
3141 X = temp; \
3142 temp = NULL; \
3143 }
3144
3145 /* Multiply two values, then reduce the result:
3146 result = X*Y % c. If c is NULL, skip the mod. */
3147#define MULT(X, Y, result) \
3148{ \
3149 temp = (PyLongObject *)long_mul(X, Y); \
3150 if (temp == NULL) \
3151 goto Error; \
3152 Py_XDECREF(result); \
3153 result = temp; \
3154 temp = NULL; \
3155 REDUCE(result) \
3156}
3157
Christian Heimes90aa7642007-12-19 02:45:37 +00003158 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003159 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3160 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003161 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003162 digit bi = b->ob_digit[i];
3163
Mark Dickinsone4416742009-02-15 15:14:57 +00003164 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003165 MULT(z, z, z)
3166 if (bi & j)
3167 MULT(z, a, z)
3168 }
3169 }
3170 }
3171 else {
3172 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3173 Py_INCREF(z); /* still holds 1L */
3174 table[0] = z;
3175 for (i = 1; i < 32; ++i)
3176 MULT(table[i-1], a, table[i])
3177
Christian Heimes90aa7642007-12-19 02:45:37 +00003178 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003179 const digit bi = b->ob_digit[i];
3180
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003181 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003182 const int index = (bi >> j) & 0x1f;
3183 for (k = 0; k < 5; ++k)
3184 MULT(z, z, z)
3185 if (index)
3186 MULT(z, table[index], z)
3187 }
3188 }
3189 }
3190
Christian Heimes90aa7642007-12-19 02:45:37 +00003191 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003192 temp = (PyLongObject *)long_sub(z, c);
3193 if (temp == NULL)
3194 goto Error;
3195 Py_DECREF(z);
3196 z = temp;
3197 temp = NULL;
3198 }
3199 goto Done;
3200
3201 Error:
3202 if (z != NULL) {
3203 Py_DECREF(z);
3204 z = NULL;
3205 }
3206 /* fall through */
3207 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003208 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003209 for (i = 0; i < 32; ++i)
3210 Py_XDECREF(table[i]);
3211 }
Tim Petersde7990b2005-07-17 23:45:23 +00003212 Py_DECREF(a);
3213 Py_DECREF(b);
3214 Py_XDECREF(c);
3215 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003216 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003217}
3218
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003219static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003220long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003221{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003222 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003223 PyLongObject *x;
3224 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003225 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003226 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003227 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003228 if (w == NULL)
3229 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003230 x = (PyLongObject *) long_add(v, w);
3231 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003232 if (x == NULL)
3233 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003234 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003235 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003236}
3237
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003238static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003239long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003240{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003241 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003242 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003243 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003244 z = (PyLongObject *)_PyLong_Copy(v);
3245 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003246 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003247 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003248}
3249
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003250static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003251long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003252{
Christian Heimes90aa7642007-12-19 02:45:37 +00003253 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003254 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003255 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003256 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003257}
3258
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003259static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003260long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003261{
Christian Heimes90aa7642007-12-19 02:45:37 +00003262 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003263}
3264
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003265static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003266long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003267{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003268 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003269 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003270 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003271 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003272
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003273 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003274
Christian Heimes90aa7642007-12-19 02:45:37 +00003275 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003276 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003277 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003278 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003279 if (a1 == NULL)
3280 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003281 a2 = (PyLongObject *) long_rshift(a1, b);
3282 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003283 if (a2 == NULL)
3284 goto rshift_error;
3285 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003286 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003287 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003288 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003289
Neil Schemenauerba872e22001-01-04 01:46:03 +00003290 shiftby = PyLong_AsLong((PyObject *)b);
3291 if (shiftby == -1L && PyErr_Occurred())
3292 goto rshift_error;
3293 if (shiftby < 0) {
3294 PyErr_SetString(PyExc_ValueError,
3295 "negative shift count");
3296 goto rshift_error;
3297 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003298 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003299 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003300 if (newsize <= 0)
3301 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003302 loshift = shiftby % PyLong_SHIFT;
3303 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003304 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003305 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003306 z = _PyLong_New(newsize);
3307 if (z == NULL)
3308 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003309 if (Py_SIZE(a) < 0)
3310 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003311 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3312 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3313 if (i+1 < newsize)
3314 z->ob_digit[i] |=
3315 (a->ob_digit[j+1] << hishift) & himask;
3316 }
3317 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003318 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003319rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003320 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003321
Guido van Rossumc6913e71991-11-19 20:26:46 +00003322}
3323
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003324static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003325long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003326{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003327 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003328 PyLongObject *a = (PyLongObject*)v;
3329 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003330 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003331 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003332 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003333 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003334
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003335 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003336
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003337 shiftby = PyLong_AsLong((PyObject *)b);
3338 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003339 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003340 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003341 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003342 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003343 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003344 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003345 PyErr_SetString(PyExc_ValueError,
3346 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003347 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003348 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003349 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3350 wordshift = (int)shiftby / PyLong_SHIFT;
3351 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003352
Christian Heimes90aa7642007-12-19 02:45:37 +00003353 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003354 newsize = oldsize + wordshift;
3355 if (remshift)
3356 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003357 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003358 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003359 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003360 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003361 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003362 for (i = 0; i < wordshift; i++)
3363 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003364 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003365 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003366 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003367 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3368 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003369 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003370 if (remshift)
3371 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003372 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003373 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003374 z = long_normalize(z);
3375lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003376 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003377}
3378
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003379
3380/* Bitwise and/xor/or operations */
3381
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003382static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003383long_bitwise(PyLongObject *a,
3384 int op, /* '&', '|', '^' */
3385 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003386{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003387 digit maska, maskb; /* 0 or PyLong_MASK */
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003388 int negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003389 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003390 PyLongObject *z;
Guido van Rossum8b27d921992-03-27 17:27:05 +00003391 digit diga, digb;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003392 PyObject *v;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003393
Christian Heimes90aa7642007-12-19 02:45:37 +00003394 if (Py_SIZE(a) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003395 a = (PyLongObject *) long_invert(a);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003396 if (a == NULL)
3397 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003398 maska = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003399 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003400 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003401 Py_INCREF(a);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003402 maska = 0;
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003403 }
Christian Heimes90aa7642007-12-19 02:45:37 +00003404 if (Py_SIZE(b) < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003405 b = (PyLongObject *) long_invert(b);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003406 if (b == NULL) {
3407 Py_DECREF(a);
3408 return NULL;
3409 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003410 maskb = PyLong_MASK;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003411 }
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003412 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413 Py_INCREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003414 maskb = 0;
3415 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003416
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003417 negz = 0;
3418 switch (op) {
3419 case '^':
3420 if (maska != maskb) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003421 maska ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003422 negz = -1;
3423 }
3424 break;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003425 case '&':
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003426 if (maska && maskb) {
3427 op = '|';
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003428 maska ^= PyLong_MASK;
3429 maskb ^= PyLong_MASK;
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003430 negz = -1;
3431 }
3432 break;
3433 case '|':
3434 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;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003441 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003442
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003443 /* JRH: The original logic here was to allocate the result value (z)
3444 as the longer of the two operands. However, there are some cases
3445 where the result is guaranteed to be shorter than that: AND of two
3446 positives, OR of two negatives: use the shorter number. AND with
3447 mixed signs: use the positive number. OR with mixed signs: use the
3448 negative number. After the transformations above, op will be '&'
3449 iff one of these cases applies, and mask will be non-0 for operands
3450 whose length should be ignored.
3451 */
3452
Christian Heimes90aa7642007-12-19 02:45:37 +00003453 size_a = Py_SIZE(a);
3454 size_b = Py_SIZE(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003455 size_z = op == '&'
3456 ? (maska
3457 ? size_b
3458 : (maskb ? size_a : MIN(size_a, size_b)))
3459 : MAX(size_a, size_b);
3460 z = _PyLong_New(size_z);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003461 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003462 Py_DECREF(a);
3463 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003464 return NULL;
3465 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003466
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003467 for (i = 0; i < size_z; ++i) {
3468 diga = (i < size_a ? a->ob_digit[i] : 0) ^ maska;
3469 digb = (i < size_b ? b->ob_digit[i] : 0) ^ maskb;
3470 switch (op) {
3471 case '&': z->ob_digit[i] = diga & digb; break;
3472 case '|': z->ob_digit[i] = diga | digb; break;
3473 case '^': z->ob_digit[i] = diga ^ digb; break;
3474 }
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003475 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003476
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003477 Py_DECREF(a);
3478 Py_DECREF(b);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003479 z = long_normalize(z);
3480 if (negz == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003481 return (PyObject *) maybe_small_long(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003482 v = long_invert(z);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003483 Py_DECREF(z);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003484 return v;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003485}
3486
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003487static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003488long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003489{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003490 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003491 CHECK_BINOP(a, b);
3492 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003493 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003494}
3495
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003496static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003497long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003498{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003499 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003500 CHECK_BINOP(a, b);
3501 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003502 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003503}
3504
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003505static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003506long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003507{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003508 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003509 CHECK_BINOP(a, b);
3510 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003511 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003512}
3513
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003514static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003515long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003516{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003517 if (PyLong_CheckExact(v))
3518 Py_INCREF(v);
3519 else
3520 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003521 return v;
3522}
3523
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003524static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003525long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003526{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003527 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003528 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003529 if (result == -1.0 && PyErr_Occurred())
3530 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003531 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003532}
3533
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003534static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003535long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003536
Tim Peters6d6c1a32001-08-02 04:15:00 +00003537static PyObject *
3538long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3539{
3540 PyObject *x = NULL;
3541 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003542 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003543
Guido van Rossumbef14172001-08-29 15:47:46 +00003544 if (type != &PyLong_Type)
3545 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003546 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003547 &x, &base))
3548 return NULL;
3549 if (x == NULL)
3550 return PyLong_FromLong(0L);
3551 if (base == -909)
3552 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003553 else if (PyUnicode_Check(x))
3554 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3555 PyUnicode_GET_SIZE(x),
3556 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003557 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003558 /* Since PyLong_FromString doesn't have a length parameter,
3559 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003560 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003561 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00003562 if (PyByteArray_Check(x))
3563 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003564 else
Christian Heimes72b710a2008-05-26 13:28:38 +00003565 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003566 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00003567 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00003568 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00003569 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00003570 "invalid literal for int() with base %d: %R",
3571 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00003572 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003573 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00003574 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00003575 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00003576 else {
3577 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003578 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003579 return NULL;
3580 }
3581}
3582
Guido van Rossumbef14172001-08-29 15:47:46 +00003583/* Wimpy, slow approach to tp_new calls for subtypes of long:
3584 first create a regular long from whatever arguments we got,
3585 then allocate a subtype instance and initialize it from
3586 the regular long. The regular long is then thrown away.
3587*/
3588static PyObject *
3589long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3590{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003591 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003592 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00003593
3594 assert(PyType_IsSubtype(type, &PyLong_Type));
3595 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
3596 if (tmp == NULL)
3597 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00003598 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00003599 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003600 if (n < 0)
3601 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003602 newobj = (PyLongObject *)type->tp_alloc(type, n);
3603 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00003604 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003605 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00003606 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003607 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00003608 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00003609 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003610 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00003611 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003612 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00003613}
3614
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003615static PyObject *
3616long_getnewargs(PyLongObject *v)
3617{
3618 return Py_BuildValue("(N)", _PyLong_Copy(v));
3619}
3620
Guido van Rossumb43daf72007-08-01 18:08:08 +00003621static PyObject *
3622long_getN(PyLongObject *v, void *context) {
Christian Heimesc36625b2008-01-04 13:33:00 +00003623 return PyLong_FromLong((Py_intptr_t)context);
Guido van Rossumb43daf72007-08-01 18:08:08 +00003624}
3625
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003626static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00003627long__format__(PyObject *self, PyObject *args)
3628{
Eric Smith4a7d76d2008-05-30 18:10:19 +00003629 PyObject *format_spec;
3630
3631 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
3632 return NULL;
3633 return _PyLong_FormatAdvanced(self,
3634 PyUnicode_AS_UNICODE(format_spec),
3635 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00003636}
3637
Eric Smith8c663262007-08-25 02:26:07 +00003638static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003639long_round(PyObject *self, PyObject *args)
3640{
Mark Dickinson1124e712009-01-28 21:25:58 +00003641 PyObject *o_ndigits=NULL, *temp;
3642 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
3643 int errcode;
3644 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003645
Mark Dickinson1124e712009-01-28 21:25:58 +00003646 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
3647 the straightforward method is:
3648
3649 (1) divide by 10**n
3650 (2) round to nearest integer (round to even in case of tie)
3651 (3) multiply result by 10**n.
3652
3653 But the rounding step involves examining the fractional part of the
3654 quotient to see whether it's greater than 0.5 or not. Since we
3655 want to do the whole calculation in integer arithmetic, it's
3656 simpler to do:
3657
3658 (1) divide by (10**n)/2
3659 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
3660 (3) multiply result by (10**n)/2.
3661
3662 Then all we need to know about the fractional part of the quotient
3663 arising in step (2) is whether it's zero or not.
3664
3665 Doing both a multiplication and division is wasteful, and is easily
3666 avoided if we just figure out how much to adjust the original input
3667 by to do the rounding.
3668
3669 Here's the whole algorithm expressed in Python.
3670
3671 def round(self, ndigits = None):
3672 """round(int, int) -> int"""
3673 if ndigits is None or ndigits >= 0:
3674 return self
3675 pow = 10**-ndigits >> 1
3676 q, r = divmod(self, pow)
3677 self -= r
3678 if (q & 1 != 0):
3679 if (q & 2 == r == 0):
3680 self -= pow
3681 else:
3682 self += pow
3683 return self
3684
3685 */
3686 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
3687 return NULL;
3688 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003689 return long_long(self);
3690
Mark Dickinson1124e712009-01-28 21:25:58 +00003691 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
3692 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003693 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00003694
3695 if (Py_SIZE(ndigits) >= 0) {
3696 Py_DECREF(ndigits);
3697 return long_long(self);
3698 }
3699
3700 Py_INCREF(self); /* to keep refcounting simple */
3701 /* we now own references to self, ndigits */
3702
3703 /* pow = 10 ** -ndigits >> 1 */
3704 pow = (PyLongObject *)PyLong_FromLong(10L);
3705 if (pow == NULL)
3706 goto error;
3707 temp = long_neg(ndigits);
3708 Py_DECREF(ndigits);
3709 ndigits = (PyLongObject *)temp;
3710 if (ndigits == NULL)
3711 goto error;
3712 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
3713 Py_DECREF(pow);
3714 pow = (PyLongObject *)temp;
3715 if (pow == NULL)
3716 goto error;
3717 assert(PyLong_Check(pow)); /* check long_pow returned a long */
3718 one = (PyLongObject *)PyLong_FromLong(1L);
3719 if (one == NULL)
3720 goto error;
3721 temp = long_rshift(pow, one);
3722 Py_DECREF(one);
3723 Py_DECREF(pow);
3724 pow = (PyLongObject *)temp;
3725 if (pow == NULL)
3726 goto error;
3727
3728 /* q, r = divmod(self, pow) */
3729 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
3730 if (errcode == -1)
3731 goto error;
3732
3733 /* self -= r */
3734 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003735 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00003736 self = temp;
3737 if (self == NULL)
3738 goto error;
3739
3740 /* get value of quotient modulo 4 */
3741 if (Py_SIZE(q) == 0)
3742 q_mod_4 = 0;
3743 else if (Py_SIZE(q) > 0)
3744 q_mod_4 = q->ob_digit[0] & 3;
3745 else
3746 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
3747
3748 if ((q_mod_4 & 1) == 1) {
3749 /* q is odd; round self up or down by adding or subtracting pow */
3750 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
3751 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
3752 else
3753 temp = (PyObject *)long_add((PyLongObject *)self, pow);
3754 Py_DECREF(self);
3755 self = temp;
3756 if (self == NULL)
3757 goto error;
3758 }
3759 Py_DECREF(q);
3760 Py_DECREF(r);
3761 Py_DECREF(pow);
3762 Py_DECREF(ndigits);
3763 return self;
3764
3765 error:
3766 Py_XDECREF(q);
3767 Py_XDECREF(r);
3768 Py_XDECREF(pow);
3769 Py_XDECREF(self);
3770 Py_XDECREF(ndigits);
3771 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003772}
3773
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003774static PyObject *
3775long_sizeof(PyLongObject *v)
3776{
3777 Py_ssize_t res;
3778
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003779 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003780 return PyLong_FromSsize_t(res);
3781}
3782
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003783static const unsigned char BitLengthTable[32] = {
3784 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
3785 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
3786};
3787
3788static PyObject *
3789long_bit_length(PyLongObject *v)
3790{
3791 PyLongObject *result, *x, *y;
3792 Py_ssize_t ndigits, msd_bits = 0;
3793 digit msd;
3794
3795 assert(v != NULL);
3796 assert(PyLong_Check(v));
3797
3798 ndigits = ABS(Py_SIZE(v));
3799 if (ndigits == 0)
3800 return PyLong_FromLong(0);
3801
3802 msd = v->ob_digit[ndigits-1];
3803 while (msd >= 32) {
3804 msd_bits += 6;
3805 msd >>= 6;
3806 }
3807 msd_bits += (long)(BitLengthTable[msd]);
3808
3809 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
3810 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
3811
3812 /* expression above may overflow; use Python integers instead */
3813 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
3814 if (result == NULL)
3815 return NULL;
3816 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
3817 if (x == NULL)
3818 goto error;
3819 y = (PyLongObject *)long_mul(result, x);
3820 Py_DECREF(x);
3821 if (y == NULL)
3822 goto error;
3823 Py_DECREF(result);
3824 result = y;
3825
3826 x = (PyLongObject *)PyLong_FromLong(msd_bits);
3827 if (x == NULL)
3828 goto error;
3829 y = (PyLongObject *)long_add(result, x);
3830 Py_DECREF(x);
3831 if (y == NULL)
3832 goto error;
3833 Py_DECREF(result);
3834 result = y;
3835
3836 return (PyObject *)result;
3837
3838error:
3839 Py_DECREF(result);
3840 return NULL;
3841}
3842
3843PyDoc_STRVAR(long_bit_length_doc,
3844"int.bit_length() -> int\n\
3845\n\
3846Number of bits necessary to represent self in binary.\n\
3847>>> bin(37)\n\
3848'0b100101'\n\
3849>>> (37).bit_length()\n\
38506");
3851
Christian Heimes53876d92008-04-19 00:31:39 +00003852#if 0
3853static PyObject *
3854long_is_finite(PyObject *v)
3855{
3856 Py_RETURN_TRUE;
3857}
3858#endif
3859
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003860static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00003861 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
3862 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00003863 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
3864 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00003865#if 0
3866 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
3867 "Returns always True."},
3868#endif
Guido van Rossum2fa33db2007-08-23 22:07:24 +00003869 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
3870 "Truncating an Integral returns itself."},
3871 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
3872 "Flooring an Integral returns itself."},
3873 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
3874 "Ceiling of an Integral returns itself."},
3875 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00003876 "Rounding an Integral returns itself.\n"
3877 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003878 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00003879 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00003880 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
3881 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003882 {NULL, NULL} /* sentinel */
3883};
3884
Guido van Rossumb43daf72007-08-01 18:08:08 +00003885static PyGetSetDef long_getset[] = {
3886 {"real",
3887 (getter)long_long, (setter)NULL,
3888 "the real part of a complex number",
3889 NULL},
3890 {"imag",
3891 (getter)long_getN, (setter)NULL,
3892 "the imaginary part of a complex number",
3893 (void*)0},
3894 {"numerator",
3895 (getter)long_long, (setter)NULL,
3896 "the numerator of a rational number in lowest terms",
3897 NULL},
3898 {"denominator",
3899 (getter)long_getN, (setter)NULL,
3900 "the denominator of a rational number in lowest terms",
3901 (void*)1},
3902 {NULL} /* Sentinel */
3903};
3904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003905PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00003906"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003907\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00003908Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00003909point argument will be truncated towards zero (this does not include a\n\
3910string representation of a floating point number!) When converting a\n\
3911string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003912converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00003913
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003914static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00003915 (binaryfunc) long_add, /*nb_add*/
3916 (binaryfunc) long_sub, /*nb_subtract*/
3917 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003918 long_mod, /*nb_remainder*/
3919 long_divmod, /*nb_divmod*/
3920 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003921 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003922 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003923 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00003924 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003925 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003926 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00003927 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003928 long_and, /*nb_and*/
3929 long_xor, /*nb_xor*/
3930 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00003931 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00003932 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003933 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00003934 0, /* nb_inplace_add */
3935 0, /* nb_inplace_subtract */
3936 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00003937 0, /* nb_inplace_remainder */
3938 0, /* nb_inplace_power */
3939 0, /* nb_inplace_lshift */
3940 0, /* nb_inplace_rshift */
3941 0, /* nb_inplace_and */
3942 0, /* nb_inplace_xor */
3943 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003944 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00003945 long_true_divide, /* nb_true_divide */
3946 0, /* nb_inplace_floor_divide */
3947 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00003948 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003949};
3950
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003951PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003952 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003953 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003954 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003955 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003956 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003957 0, /* tp_print */
3958 0, /* tp_getattr */
3959 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00003960 0, /* tp_reserved */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003961 long_repr, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003962 &long_as_number, /* tp_as_number */
3963 0, /* tp_as_sequence */
3964 0, /* tp_as_mapping */
3965 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003966 0, /* tp_call */
3967 long_repr, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003968 PyObject_GenericGetAttr, /* tp_getattro */
3969 0, /* tp_setattro */
3970 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00003971 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
3972 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003973 long_doc, /* tp_doc */
3974 0, /* tp_traverse */
3975 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00003976 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003977 0, /* tp_weaklistoffset */
3978 0, /* tp_iter */
3979 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003980 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003981 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00003982 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003983 0, /* tp_base */
3984 0, /* tp_dict */
3985 0, /* tp_descr_get */
3986 0, /* tp_descr_set */
3987 0, /* tp_dictoffset */
3988 0, /* tp_init */
3989 0, /* tp_alloc */
3990 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00003991 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003992};
Guido van Rossumddefaf32007-01-14 03:31:43 +00003993
3994int
3995_PyLong_Init(void)
3996{
3997#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00003998 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003999 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004000
4001 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4002 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4003 if (Py_TYPE(v) == &PyLong_Type) {
4004 /* The element is already initialized, most likely
4005 * the Python interpreter was initialized before.
4006 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004007 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004008 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004009
Christian Heimes48aa4b12008-02-01 16:56:30 +00004010 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4011 _Py_NewReference(op);
4012 /* _Py_NewReference sets the ref count to 1 but
4013 * the ref count might be larger. Set the refcnt
4014 * to the original refcnt + 1 */
4015 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004016 assert(Py_SIZE(op) == size);
4017 assert(v->ob_digit[0] == abs(ival));
4018 }
4019 else {
4020 PyObject_INIT(v, &PyLong_Type);
4021 }
4022 Py_SIZE(v) = size;
4023 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004024 }
4025#endif
4026 return 1;
4027}
4028
4029void
4030PyLong_Fini(void)
4031{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004032 /* Integers are currently statically allocated. Py_DECREF is not
4033 needed, but Python must forget about the reference or multiple
4034 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004035#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004036 int i;
4037 PyLongObject *v = small_ints;
4038 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4039 _Py_DEC_REFTOTAL;
4040 _Py_ForgetReference((PyObject*)v);
4041 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004042#endif
4043}