blob: db7a91c556768dd59d9c7e4819e6d02ba2dbaa96 [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"
Mark Dickinsonbd792642009-03-18 20:06:12 +00007#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Guido van Rossumddefaf32007-01-14 03:31:43 +000013#ifndef NSMALLPOSINTS
14#define NSMALLPOSINTS 257
15#endif
16#ifndef NSMALLNEGINTS
17#define NSMALLNEGINTS 5
18#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000019
Mark Dickinsone4416742009-02-15 15:14:57 +000020/* convert a PyLong of size 1, 0 or -1 to an sdigit */
21#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
22 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
34int quick_int_allocs, quick_neg_int_allocs;
35#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
40 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
42#ifdef COUNT_ALLOCS
43 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
47#endif
48 return v;
49}
50#define CHECK_SMALL_INT(ival) \
51 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
Mark Dickinson0d4785b2009-02-15 17:27:41 +000052 return get_small_int((sdigit)ival); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000053 } while(0)
54
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055static PyLongObject *
56maybe_small_long(PyLongObject *v)
57{
58 if (v && ABS(Py_SIZE(v)) <= 1) {
Mark Dickinsone4416742009-02-15 15:14:57 +000059 sdigit ival = MEDIUM_VALUE(v);
Facundo Batista6e6f59b2008-07-24 18:57:11 +000060 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
66}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Guido van Rossumddefaf32007-01-14 03:31:43 +000072/* If a freshly-allocated long is already shared, it must
73 be a small integer, so negating it must go to PyLong_FromLong */
74#define NEGATE(x) \
Christian Heimes90aa7642007-12-19 02:45:37 +000075 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
Christian Heimes217cfd12007-12-02 14:31:20 +000076 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
Guido van Rossumddefaf32007-01-14 03:31:43 +000077 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
78 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000079/* For long multiplication, use the O(N**2) school algorithm unless
80 * both operands contain more than KARATSUBA_CUTOFF digits (this
81 * being an internal Python long digit, in base BASE).
82 */
Tim Peters0973b992004-08-29 22:16:50 +000083#define KARATSUBA_CUTOFF 70
84#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000085
Tim Peters47e52ee2004-08-30 02:44:38 +000086/* For exponentiation, use the binary left-to-right algorithm
87 * unless the exponent contains more than FIVEARY_CUTOFF digits.
88 * In that case, do 5 bits at a time. The potential drawback is that
89 * a table of 2**5 intermediate results is computed.
90 */
91#define FIVEARY_CUTOFF 8
92
Tim Peters5af4e6c2002-08-12 02:31:19 +000093#undef MIN
94#undef MAX
95#define MAX(x, y) ((x) < (y) ? (y) : (x))
96#define MIN(x, y) ((x) > (y) ? (y) : (x))
97
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098#define SIGCHECK(PyTryBlock) \
Antoine Pitrou074e5ed2009-11-10 19:50:40 +000099 if (PyErr_CheckSignals()) PyTryBlock \
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000100
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000101/* Normalize (remove leading zeros from) a long int object.
102 Doesn't attempt to free the storage--in most cases, due to the nature
103 of the algorithms used, this could save at most be one word anyway. */
104
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000106long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000107{
Christian Heimes90aa7642007-12-19 02:45:37 +0000108 Py_ssize_t j = ABS(Py_SIZE(v));
Martin v. Löwis18e16552006-02-15 17:27:45 +0000109 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000110
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000111 while (i > 0 && v->ob_digit[i-1] == 0)
112 --i;
113 if (i != j)
Christian Heimes90aa7642007-12-19 02:45:37 +0000114 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115 return v;
116}
117
118/* Allocate a new long int object with size digits.
119 Return NULL and set exception if we run out of memory. */
120
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000121#define MAX_LONG_DIGITS \
122 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
123
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000124PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000125_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000126{
Guido van Rossumddefaf32007-01-14 03:31:43 +0000127 PyLongObject *result;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000128 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
129 sizeof(digit)*size. Previous incarnations of this code used
130 sizeof(PyVarObject) instead of the offsetof, but this risks being
131 incorrect in the presence of padding between the PyVarObject header
132 and the digits. */
Mark Dickinsone4416742009-02-15 15:14:57 +0000133 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000134 PyErr_SetString(PyExc_OverflowError,
135 "too many digits in integer");
136 return NULL;
137 }
138 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
Guido van Rossumddefaf32007-01-14 03:31:43 +0000139 size*sizeof(digit));
140 if (!result) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000141 PyErr_NoMemory();
142 return NULL;
143 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000144 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000145}
146
Tim Peters64b5ce32001-09-10 20:52:51 +0000147PyObject *
148_PyLong_Copy(PyLongObject *src)
149{
150 PyLongObject *result;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000151 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000152
153 assert(src != NULL);
Christian Heimes90aa7642007-12-19 02:45:37 +0000154 i = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000155 if (i < 0)
156 i = -(i);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000157 if (i < 2) {
Mark Dickinsone4416742009-02-15 15:14:57 +0000158 sdigit ival = src->ob_digit[0];
Christian Heimes90aa7642007-12-19 02:45:37 +0000159 if (Py_SIZE(src) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000160 ival = -ival;
161 CHECK_SMALL_INT(ival);
162 }
Tim Peters64b5ce32001-09-10 20:52:51 +0000163 result = _PyLong_New(i);
164 if (result != NULL) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000165 Py_SIZE(result) = Py_SIZE(src);
Tim Peters64b5ce32001-09-10 20:52:51 +0000166 while (--i >= 0)
167 result->ob_digit[i] = src->ob_digit[i];
168 }
169 return (PyObject *)result;
170}
171
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000172/* Create a new long int object from a C long int */
173
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000174PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000175PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000176{
Tim Petersce9de2f2001-06-14 04:56:19 +0000177 PyLongObject *v;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000178 unsigned long abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000179 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
180 int ndigits = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181 int sign = 1;
182
183 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000184
185 if (ival < 0) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000186 /* negate: can't write this as abs_ival = -ival since that
187 invokes undefined behaviour when ival is LONG_MIN */
188 abs_ival = 0U-(unsigned long)ival;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000189 sign = -1;
Tim Petersce9de2f2001-06-14 04:56:19 +0000190 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000191 else {
192 abs_ival = (unsigned long)ival;
193 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000194
Mark Dickinsond4624c32009-01-24 15:02:35 +0000195 /* Fast path for single-digit ints */
196 if (!(abs_ival >> PyLong_SHIFT)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000197 v = _PyLong_New(1);
198 if (v) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000199 Py_SIZE(v) = sign;
Mark Dickinsond4624c32009-01-24 15:02:35 +0000200 v->ob_digit[0] = Py_SAFE_DOWNCAST(
201 abs_ival, unsigned long, digit);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000202 }
203 return (PyObject*)v;
204 }
205
Mark Dickinson249b8982009-04-27 19:41:00 +0000206#if PyLong_SHIFT==15
Guido van Rossumddefaf32007-01-14 03:31:43 +0000207 /* 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 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000219#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000220
221 /* Larger numbers: loop to determine number of digits */
Christian Heimesdae2a892008-04-19 00:55:37 +0000222 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000223 while (t) {
224 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000225 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000226 }
227 v = _PyLong_New(ndigits);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000228 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000229 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000230 Py_SIZE(v) = ndigits*sign;
Christian Heimesdae2a892008-04-19 00:55:37 +0000231 t = abs_ival;
Tim Petersce9de2f2001-06-14 04:56:19 +0000232 while (t) {
Mark Dickinsond4624c32009-01-24 15:02:35 +0000233 *p++ = Py_SAFE_DOWNCAST(
234 t & PyLong_MASK, unsigned long, digit);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000235 t >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000236 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000237 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000238 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000239}
240
Guido van Rossum53756b11997-01-03 17:14:46 +0000241/* Create a new long int object from a C unsigned long int */
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000244PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000245{
Tim Petersce9de2f2001-06-14 04:56:19 +0000246 PyLongObject *v;
247 unsigned long t;
248 int ndigits = 0;
249
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000250 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000251 return PyLong_FromLong(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000252 /* Count the number of Python digits. */
253 t = (unsigned long)ival;
254 while (t) {
255 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000256 t >>= PyLong_SHIFT;
Tim Petersce9de2f2001-06-14 04:56:19 +0000257 }
258 v = _PyLong_New(ndigits);
Guido van Rossum53756b11997-01-03 17:14:46 +0000259 if (v != NULL) {
Tim Petersce9de2f2001-06-14 04:56:19 +0000260 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +0000261 Py_SIZE(v) = ndigits;
Tim Petersce9de2f2001-06-14 04:56:19 +0000262 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000263 *p++ = (digit)(ival & PyLong_MASK);
264 ival >>= PyLong_SHIFT;
Guido van Rossum53756b11997-01-03 17:14:46 +0000265 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000266 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000267 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000268}
269
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000270/* Create a new long int object from a C double */
271
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000274{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275 PyLongObject *v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276 double frac;
277 int i, ndig, expo, neg;
278 neg = 0;
Tim Peters39dce292000-08-15 03:34:48 +0000279 if (Py_IS_INFINITY(dval)) {
Guido van Rossum1a23c241999-09-27 17:11:52 +0000280 PyErr_SetString(PyExc_OverflowError,
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000281 "cannot convert float infinity to integer");
Guido van Rossum1a23c241999-09-27 17:11:52 +0000282 return NULL;
283 }
Christian Heimesa34706f2008-01-04 03:06:10 +0000284 if (Py_IS_NAN(dval)) {
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000285 PyErr_SetString(PyExc_ValueError,
286 "cannot convert float NaN to integer");
Christian Heimes386cd1e2008-01-15 02:01:20 +0000287 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +0000288 }
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000289 if (dval < 0.0) {
290 neg = 1;
291 dval = -dval;
292 }
293 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
294 if (expo <= 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 return PyLong_FromLong(0L);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000296 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000297 v = _PyLong_New(ndig);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000298 if (v == NULL)
299 return NULL;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000300 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000301 for (i = ndig; --i >= 0; ) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000302 digit bits = (digit)frac;
303 v->ob_digit[i] = bits;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000304 frac = frac - (double)bits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000305 frac = ldexp(frac, PyLong_SHIFT);
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000306 }
307 if (neg)
Christian Heimes90aa7642007-12-19 02:45:37 +0000308 Py_SIZE(v) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000310}
311
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
313 * anything about what happens when a signed integer operation overflows,
314 * and some compilers think they're doing you a favor by being "clever"
315 * then. The bit pattern for the largest postive signed long is
316 * (unsigned long)LONG_MAX, and for the smallest negative signed long
317 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
318 * However, some other compilers warn about applying unary minus to an
319 * unsigned operand. Hence the weird "0-".
320 */
321#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
322#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
323
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000324/* Get a C long int from a long int object.
325 Returns -1 and sets an error condition if overflow occurs. */
326
327long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000328PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000329{
Guido van Rossumf7531811998-05-26 14:33:37 +0000330 /* This version by Tim Peters */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000331 register PyLongObject *v;
Guido van Rossumf7531811998-05-26 14:33:37 +0000332 unsigned long x, prev;
Georg Brandl61c31b02007-02-26 14:46:30 +0000333 long res;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000334 Py_ssize_t i;
335 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000336 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000337
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000338 *overflow = 0;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000339 if (vv == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340 PyErr_BadInternalCall();
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000341 return -1;
342 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000343
344 if (!PyLong_Check(vv)) {
345 PyNumberMethods *nb;
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000346 nb = vv->ob_type->tp_as_number;
347 if (nb == NULL || nb->nb_int == NULL) {
348 PyErr_SetString(PyExc_TypeError,
349 "an integer is required");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000350 return -1;
351 }
352 vv = (*nb->nb_int) (vv);
353 if (vv == NULL)
354 return -1;
355 do_decref = 1;
356 if (!PyLong_Check(vv)) {
357 Py_DECREF(vv);
358 PyErr_SetString(PyExc_TypeError,
359 "nb_int should return int object");
360 return -1;
361 }
362 }
363
Georg Brandl61c31b02007-02-26 14:46:30 +0000364 res = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000366 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000367
Georg Brandl61c31b02007-02-26 14:46:30 +0000368 switch (i) {
369 case -1:
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000370 res = -(sdigit)v->ob_digit[0];
Georg Brandl61c31b02007-02-26 14:46:30 +0000371 break;
372 case 0:
373 res = 0;
374 break;
375 case 1:
376 res = v->ob_digit[0];
377 break;
378 default:
379 sign = 1;
380 x = 0;
381 if (i < 0) {
382 sign = -1;
383 i = -(i);
384 }
385 while (--i >= 0) {
386 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000387 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000388 if ((x >> PyLong_SHIFT) != prev) {
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000389 *overflow = sign;
Georg Brandl61c31b02007-02-26 14:46:30 +0000390 goto exit;
391 }
392 }
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000393 /* Haven't lost any bits, but casting to long requires extra
394 * care (see comment above).
395 */
Georg Brandl61c31b02007-02-26 14:46:30 +0000396 if (x <= (unsigned long)LONG_MAX) {
397 res = (long)x * sign;
398 }
399 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
400 res = LONG_MIN;
401 }
402 else {
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000403 *overflow = sign;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000404 /* res is already set to -1 */
Mark Dickinson309aa2d2009-12-21 12:37:06 +0000405 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000406 }
407 exit:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000408 if (do_decref) {
409 Py_DECREF(vv);
410 }
Georg Brandl61c31b02007-02-26 14:46:30 +0000411 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000412}
413
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000414long
415PyLong_AsLong(PyObject *obj)
416{
417 int overflow;
418 long result = PyLong_AsLongAndOverflow(obj, &overflow);
419 if (overflow) {
420 /* XXX: could be cute and give a different
421 message for overflow == -1 */
422 PyErr_SetString(PyExc_OverflowError,
423 "Python int too large to convert to C long");
424 }
425 return result;
426}
427
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000428/* Get a Py_ssize_t from a long int object.
429 Returns -1 and sets an error condition if overflow occurs. */
430
431Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000432PyLong_AsSsize_t(PyObject *vv) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000433 register PyLongObject *v;
434 size_t x, prev;
435 Py_ssize_t i;
436 int sign;
437
438 if (vv == NULL || !PyLong_Check(vv)) {
439 PyErr_BadInternalCall();
440 return -1;
441 }
442 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000443 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000444 switch (i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +0000445 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +0000446 case 0: return 0;
447 case 1: return v->ob_digit[0];
448 }
Martin v. Löwis18e16552006-02-15 17:27:45 +0000449 sign = 1;
450 x = 0;
451 if (i < 0) {
452 sign = -1;
453 i = -(i);
454 }
455 while (--i >= 0) {
456 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000457 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000458 if ((x >> PyLong_SHIFT) != prev)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000459 goto overflow;
460 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000461 /* Haven't lost any bits, but casting to a signed type requires
462 * extra care (see comment above).
Martin v. Löwis18e16552006-02-15 17:27:45 +0000463 */
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464 if (x <= (size_t)PY_SSIZE_T_MAX) {
465 return (Py_ssize_t)x * sign;
466 }
467 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
468 return PY_SSIZE_T_MIN;
469 }
470 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000471
472 overflow:
473 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000474 "Python int too large to convert to C ssize_t");
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000475 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476}
477
Guido van Rossumd8c80482002-08-13 00:24:58 +0000478/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000479 Returns -1 and sets an error condition if overflow occurs. */
480
481unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000482PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000483{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 register PyLongObject *v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000485 unsigned long x, prev;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000486 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000487
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 if (vv == NULL || !PyLong_Check(vv)) {
489 PyErr_BadInternalCall();
Guido van Rossum53756b11997-01-03 17:14:46 +0000490 return (unsigned long) -1;
491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000493 i = Py_SIZE(v);
Guido van Rossum53756b11997-01-03 17:14:46 +0000494 x = 0;
495 if (i < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000497 "can't convert negative value to unsigned int");
Guido van Rossum53756b11997-01-03 17:14:46 +0000498 return (unsigned long) -1;
499 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000500 switch (i) {
501 case 0: return 0;
502 case 1: return v->ob_digit[0];
503 }
Guido van Rossum53756b11997-01-03 17:14:46 +0000504 while (--i >= 0) {
505 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000506 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000507 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000509 "python int too large to convert to C unsigned long");
Guido van Rossumddefaf32007-01-14 03:31:43 +0000510 return (unsigned long) -1;
511 }
512 }
513 return x;
514}
515
516/* Get a C unsigned long int from a long int object.
517 Returns -1 and sets an error condition if overflow occurs. */
518
519size_t
520PyLong_AsSize_t(PyObject *vv)
521{
522 register PyLongObject *v;
523 size_t x, prev;
524 Py_ssize_t i;
525
526 if (vv == NULL || !PyLong_Check(vv)) {
527 PyErr_BadInternalCall();
528 return (unsigned long) -1;
529 }
530 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000531 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000532 x = 0;
533 if (i < 0) {
534 PyErr_SetString(PyExc_OverflowError,
535 "can't convert negative value to size_t");
536 return (size_t) -1;
537 }
538 switch (i) {
539 case 0: return 0;
540 case 1: return v->ob_digit[0];
541 }
542 while (--i >= 0) {
543 prev = x;
Mark Dickinson24f57852009-09-28 17:54:52 +0000544 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000545 if ((x >> PyLong_SHIFT) != prev) {
Guido van Rossumddefaf32007-01-14 03:31:43 +0000546 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum523d4f92007-01-15 00:31:49 +0000547 "Python int too large to convert to C size_t");
Guido van Rossum53756b11997-01-03 17:14:46 +0000548 return (unsigned long) -1;
549 }
550 }
551 return x;
552}
553
Thomas Hellera4ea6032003-04-17 18:55:45 +0000554/* Get a C unsigned long int from a long int object, ignoring the high bits.
555 Returns -1 and sets an error condition if an error occurs. */
556
Guido van Rossumddefaf32007-01-14 03:31:43 +0000557static unsigned long
558_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000559{
560 register PyLongObject *v;
561 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000562 Py_ssize_t i;
563 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000564
565 if (vv == NULL || !PyLong_Check(vv)) {
566 PyErr_BadInternalCall();
567 return (unsigned long) -1;
568 }
569 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +0000570 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000571 switch (i) {
572 case 0: return 0;
573 case 1: return v->ob_digit[0];
574 }
Thomas Hellera4ea6032003-04-17 18:55:45 +0000575 sign = 1;
576 x = 0;
577 if (i < 0) {
578 sign = -1;
579 i = -i;
580 }
581 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +0000582 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +0000583 }
584 return x * sign;
585}
586
Guido van Rossumddefaf32007-01-14 03:31:43 +0000587unsigned long
588PyLong_AsUnsignedLongMask(register PyObject *op)
589{
590 PyNumberMethods *nb;
591 PyLongObject *lo;
592 unsigned long val;
593
594 if (op && PyLong_Check(op))
595 return _PyLong_AsUnsignedLongMask(op);
596
597 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
598 nb->nb_int == NULL) {
599 PyErr_SetString(PyExc_TypeError, "an integer is required");
600 return (unsigned long)-1;
601 }
602
603 lo = (PyLongObject*) (*nb->nb_int) (op);
604 if (lo == NULL)
605 return (unsigned long)-1;
606 if (PyLong_Check(lo)) {
607 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
608 Py_DECREF(lo);
609 if (PyErr_Occurred())
610 return (unsigned long)-1;
611 return val;
612 }
613 else
614 {
615 Py_DECREF(lo);
616 PyErr_SetString(PyExc_TypeError,
617 "nb_int should return int object");
618 return (unsigned long)-1;
619 }
620}
621
Tim Peters5b8132f2003-01-31 15:52:05 +0000622int
623_PyLong_Sign(PyObject *vv)
624{
625 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000626
627 assert(v != NULL);
628 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000629
Christian Heimes90aa7642007-12-19 02:45:37 +0000630 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000631}
632
Tim Petersbaefd9e2003-01-28 20:37:45 +0000633size_t
634_PyLong_NumBits(PyObject *vv)
635{
636 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000637 size_t result = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000638 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000639
640 assert(v != NULL);
641 assert(PyLong_Check(v));
Christian Heimes90aa7642007-12-19 02:45:37 +0000642 ndigits = ABS(Py_SIZE(v));
Tim Petersbaefd9e2003-01-28 20:37:45 +0000643 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
644 if (ndigits > 0) {
Tim Petersbaefd9e2003-01-28 20:37:45 +0000645 digit msd = v->ob_digit[ndigits - 1];
646
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000647 result = (ndigits - 1) * PyLong_SHIFT;
648 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
Tim Petersbaefd9e2003-01-28 20:37:45 +0000649 goto Overflow;
650 do {
651 ++result;
652 if (result == 0)
653 goto Overflow;
654 msd >>= 1;
655 } while (msd);
656 }
657 return result;
658
659Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000660 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
Tim Petersbaefd9e2003-01-28 20:37:45 +0000661 "to express in a platform size_t");
662 return (size_t)-1;
663}
664
Tim Peters2a9b3672001-06-11 21:23:58 +0000665PyObject *
666_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
667 int little_endian, int is_signed)
668{
669 const unsigned char* pstartbyte;/* LSB of bytes */
670 int incr; /* direction to move pstartbyte */
671 const unsigned char* pendbyte; /* MSB of bytes */
672 size_t numsignificantbytes; /* number of bytes that matter */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000673 Py_ssize_t ndigits; /* number of Python long digits */
Tim Peters2a9b3672001-06-11 21:23:58 +0000674 PyLongObject* v; /* result */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000675 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000676
677 if (n == 0)
678 return PyLong_FromLong(0L);
679
680 if (little_endian) {
681 pstartbyte = bytes;
682 pendbyte = bytes + n - 1;
683 incr = 1;
684 }
685 else {
686 pstartbyte = bytes + n - 1;
687 pendbyte = bytes;
688 incr = -1;
689 }
690
691 if (is_signed)
692 is_signed = *pendbyte >= 0x80;
693
694 /* Compute numsignificantbytes. This consists of finding the most
695 significant byte. Leading 0 bytes are insignficant if the number
696 is positive, and leading 0xff bytes if negative. */
697 {
698 size_t i;
699 const unsigned char* p = pendbyte;
700 const int pincr = -incr; /* search MSB to LSB */
701 const unsigned char insignficant = is_signed ? 0xff : 0x00;
702
703 for (i = 0; i < n; ++i, p += pincr) {
704 if (*p != insignficant)
705 break;
706 }
707 numsignificantbytes = n - i;
708 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
709 actually has 2 significant bytes. OTOH, 0xff0001 ==
710 -0x00ffff, so we wouldn't *need* to bump it there; but we
711 do for 0xffff = -0x0001. To be safe without bothering to
712 check every case, bump it regardless. */
713 if (is_signed && numsignificantbytes < n)
714 ++numsignificantbytes;
715 }
716
717 /* How many Python long digits do we need? We have
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000718 8*numsignificantbytes bits, and each Python long digit has
719 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
720 /* catch overflow before it happens */
721 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
722 PyErr_SetString(PyExc_OverflowError,
723 "byte array too long to convert to int");
724 return NULL;
725 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000726 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000727 v = _PyLong_New(ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000728 if (v == NULL)
729 return NULL;
730
731 /* Copy the bits over. The tricky parts are computing 2's-comp on
732 the fly for signed numbers, and dealing with the mismatch between
733 8-bit bytes and (probably) 15-bit Python digits.*/
734 {
735 size_t i;
Tim Petersf251d062001-06-13 21:09:15 +0000736 twodigits carry = 1; /* for 2's-comp calculation */
Tim Peters2a9b3672001-06-11 21:23:58 +0000737 twodigits accum = 0; /* sliding register */
738 unsigned int accumbits = 0; /* number of bits in accum */
739 const unsigned char* p = pstartbyte;
740
741 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
Tim Peters8bc84b42001-06-12 19:17:03 +0000742 twodigits thisbyte = *p;
Tim Peters2a9b3672001-06-11 21:23:58 +0000743 /* Compute correction for 2's comp, if needed. */
744 if (is_signed) {
745 thisbyte = (0xff ^ thisbyte) + carry;
746 carry = thisbyte >> 8;
747 thisbyte &= 0xff;
748 }
749 /* Because we're going LSB to MSB, thisbyte is
750 more significant than what's already in accum,
751 so needs to be prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000752 accum |= (twodigits)thisbyte << accumbits;
Tim Peters2a9b3672001-06-11 21:23:58 +0000753 accumbits += 8;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000754 if (accumbits >= PyLong_SHIFT) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000755 /* There's enough to fill a Python digit. */
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000756 assert(idigit < ndigits);
757 v->ob_digit[idigit] = (digit)(accum &
758 PyLong_MASK);
Tim Peters2a9b3672001-06-11 21:23:58 +0000759 ++idigit;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000760 accum >>= PyLong_SHIFT;
761 accumbits -= PyLong_SHIFT;
762 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000763 }
764 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000765 assert(accumbits < PyLong_SHIFT);
Tim Peters2a9b3672001-06-11 21:23:58 +0000766 if (accumbits) {
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000767 assert(idigit < ndigits);
Tim Peters2a9b3672001-06-11 21:23:58 +0000768 v->ob_digit[idigit] = (digit)accum;
769 ++idigit;
770 }
771 }
772
Christian Heimes90aa7642007-12-19 02:45:37 +0000773 Py_SIZE(v) = is_signed ? -idigit : idigit;
Tim Peters2a9b3672001-06-11 21:23:58 +0000774 return (PyObject *)long_normalize(v);
775}
776
777int
778_PyLong_AsByteArray(PyLongObject* v,
779 unsigned char* bytes, size_t n,
780 int little_endian, int is_signed)
781{
Mark Dickinson17e55872009-01-24 15:56:57 +0000782 Py_ssize_t i; /* index into v->ob_digit */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000783 Py_ssize_t ndigits; /* |v->ob_size| */
Tim Peters2a9b3672001-06-11 21:23:58 +0000784 twodigits accum; /* sliding register */
785 unsigned int accumbits; /* # bits in accum */
786 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
Mark Dickinson1e2d8702009-01-25 22:25:06 +0000787 digit carry; /* for computing 2's-comp */
Tim Peters2a9b3672001-06-11 21:23:58 +0000788 size_t j; /* # bytes filled */
789 unsigned char* p; /* pointer to next byte in bytes */
790 int pincr; /* direction to move p */
791
792 assert(v != NULL && PyLong_Check(v));
793
Christian Heimes90aa7642007-12-19 02:45:37 +0000794 if (Py_SIZE(v) < 0) {
795 ndigits = -(Py_SIZE(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000796 if (!is_signed) {
Mark Dickinson21776072009-02-10 16:13:25 +0000797 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +0000798 "can't convert negative int to unsigned");
Tim Peters2a9b3672001-06-11 21:23:58 +0000799 return -1;
800 }
801 do_twos_comp = 1;
802 }
803 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000804 ndigits = Py_SIZE(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000805 do_twos_comp = 0;
806 }
807
808 if (little_endian) {
809 p = bytes;
810 pincr = 1;
811 }
812 else {
813 p = bytes + n - 1;
814 pincr = -1;
815 }
816
Tim Peters898cf852001-06-13 20:50:08 +0000817 /* Copy over all the Python digits.
818 It's crucial that every Python digit except for the MSD contribute
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000819 exactly PyLong_SHIFT bits to the total, so first assert that the long is
Tim Peters898cf852001-06-13 20:50:08 +0000820 normalized. */
821 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
Tim Peters2a9b3672001-06-11 21:23:58 +0000822 j = 0;
823 accum = 0;
824 accumbits = 0;
825 carry = do_twos_comp ? 1 : 0;
826 for (i = 0; i < ndigits; ++i) {
Mark Dickinson17e55872009-01-24 15:56:57 +0000827 digit thisdigit = v->ob_digit[i];
Tim Peters2a9b3672001-06-11 21:23:58 +0000828 if (do_twos_comp) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000829 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
830 carry = thisdigit >> PyLong_SHIFT;
831 thisdigit &= PyLong_MASK;
Tim Peters2a9b3672001-06-11 21:23:58 +0000832 }
Tim Peters8bc84b42001-06-12 19:17:03 +0000833 /* Because we're going LSB to MSB, thisdigit is more
834 significant than what's already in accum, so needs to be
835 prepended to accum. */
Mark Dickinson17e55872009-01-24 15:56:57 +0000836 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000837
Tim Petersede05092001-06-14 08:53:38 +0000838 /* The most-significant digit may be (probably is) at least
839 partly empty. */
Tim Peters8bc84b42001-06-12 19:17:03 +0000840 if (i == ndigits - 1) {
Tim Petersede05092001-06-14 08:53:38 +0000841 /* Count # of sign bits -- they needn't be stored,
842 * although for signed conversion we need later to
Mark Dickinson17e55872009-01-24 15:56:57 +0000843 * make sure at least one sign bit gets stored. */
844 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
845 thisdigit;
846 while (s != 0) {
847 s >>= 1;
848 accumbits++;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000849 }
Tim Peters7a3bfc32001-06-12 01:22:22 +0000850 }
Mark Dickinson17e55872009-01-24 15:56:57 +0000851 else
852 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000853
Tim Peters2a9b3672001-06-11 21:23:58 +0000854 /* Store as many bytes as possible. */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000855 while (accumbits >= 8) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000856 if (j >= n)
857 goto Overflow;
858 ++j;
859 *p = (unsigned char)(accum & 0xff);
860 p += pincr;
861 accumbits -= 8;
862 accum >>= 8;
Tim Peters7a3bfc32001-06-12 01:22:22 +0000863 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000864 }
865
866 /* Store the straggler (if any). */
867 assert(accumbits < 8);
868 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
Tim Peters7a3bfc32001-06-12 01:22:22 +0000869 if (accumbits > 0) {
Tim Peters2a9b3672001-06-11 21:23:58 +0000870 if (j >= n)
871 goto Overflow;
872 ++j;
873 if (do_twos_comp) {
874 /* Fill leading bits of the byte with sign bits
875 (appropriately pretending that the long had an
876 infinite supply of sign bits). */
877 accum |= (~(twodigits)0) << accumbits;
878 }
879 *p = (unsigned char)(accum & 0xff);
880 p += pincr;
881 }
Tim Peters05607ad2001-06-13 21:01:27 +0000882 else if (j == n && n > 0 && is_signed) {
883 /* The main loop filled the byte array exactly, so the code
884 just above didn't get to ensure there's a sign bit, and the
885 loop below wouldn't add one either. Make sure a sign bit
886 exists. */
Tim Peters2a9b3672001-06-11 21:23:58 +0000887 unsigned char msb = *(p - pincr);
Tim Peters05607ad2001-06-13 21:01:27 +0000888 int sign_bit_set = msb >= 0x80;
889 assert(accumbits == 0);
890 if (sign_bit_set == do_twos_comp)
891 return 0;
892 else
Tim Peters2a9b3672001-06-11 21:23:58 +0000893 goto Overflow;
894 }
Tim Peters05607ad2001-06-13 21:01:27 +0000895
896 /* Fill remaining bytes with copies of the sign bit. */
897 {
898 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
899 for ( ; j < n; ++j, p += pincr)
900 *p = signbyte;
901 }
902
Tim Peters2a9b3672001-06-11 21:23:58 +0000903 return 0;
904
905Overflow:
Guido van Rossumddefaf32007-01-14 03:31:43 +0000906 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
Tim Peters2a9b3672001-06-11 21:23:58 +0000907 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000908
Tim Peters2a9b3672001-06-11 21:23:58 +0000909}
910
Guido van Rossum78694d91998-09-18 14:14:13 +0000911/* Create a new long (or int) object from a C pointer */
912
913PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000914PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000915{
Tim Peters70128a12001-06-16 08:48:40 +0000916#ifndef HAVE_LONG_LONG
917# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
918#endif
919#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000920# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000921#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000922 /* special-case null pointer */
923 if (!p)
Christian Heimes217cfd12007-12-02 14:31:20 +0000924 return PyLong_FromLong(0);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000925 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000926
Guido van Rossum78694d91998-09-18 14:14:13 +0000927}
928
929/* Get a C pointer from a long object (or an int object in some cases) */
930
931void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000932PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000933{
934 /* This function will allow int or long objects. If vv is neither,
935 then the PyLong_AsLong*() functions will raise the exception:
936 PyExc_SystemError, "bad argument to internal function"
937 */
Tim Peters70128a12001-06-16 08:48:40 +0000938#if SIZEOF_VOID_P <= SIZEOF_LONG
Guido van Rossum78694d91998-09-18 14:14:13 +0000939 long x;
940
Guido van Rossumddefaf32007-01-14 03:31:43 +0000941 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000942 x = PyLong_AsLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000943 else
944 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000945#else
Tim Peters70128a12001-06-16 08:48:40 +0000946
947#ifndef HAVE_LONG_LONG
948# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
949#endif
950#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000951# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000952#endif
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000953 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000954
Guido van Rossumddefaf32007-01-14 03:31:43 +0000955 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
Guido van Rossum78694d91998-09-18 14:14:13 +0000956 x = PyLong_AsLongLong(vv);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000957 else
958 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000959
960#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000961
962 if (x == -1 && PyErr_Occurred())
963 return NULL;
964 return (void *)x;
965}
966
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000967#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000968
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000969/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000970 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000971 */
972
Tim Peterscf37dfc2001-06-14 18:42:50 +0000973#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson93f562c2010-01-30 10:30:15 +0000974#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000975
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000976/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000977
978PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000979PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000980{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000981 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +0000982 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000983 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
984 int ndigits = 0;
985 int negative = 0;
986
Guido van Rossumddefaf32007-01-14 03:31:43 +0000987 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000988 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +0000989 /* avoid signed overflow on negation; see comments
990 in PyLong_FromLong above. */
991 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992 negative = 1;
993 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000994 else {
995 abs_ival = (unsigned PY_LONG_LONG)ival;
996 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000997
998 /* Count the number of Python digits.
999 We used to pick 5 ("big enough for anything"), but that's a
1000 waste of time and space given that 5*15 = 75 bits are rarely
1001 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001002 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001003 while (t) {
1004 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001005 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001006 }
1007 v = _PyLong_New(ndigits);
1008 if (v != NULL) {
1009 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001010 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001011 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001013 *p++ = (digit)(t & PyLong_MASK);
1014 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015 }
1016 }
1017 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001018}
1019
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001020/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001021
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001022PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001024{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001025 PyLongObject *v;
1026 unsigned PY_LONG_LONG t;
1027 int ndigits = 0;
1028
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001029 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001030 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001031 /* Count the number of Python digits. */
1032 t = (unsigned PY_LONG_LONG)ival;
1033 while (t) {
1034 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001035 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036 }
1037 v = _PyLong_New(ndigits);
1038 if (v != NULL) {
1039 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001040 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001042 *p++ = (digit)(ival & PyLong_MASK);
1043 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044 }
1045 }
1046 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001047}
1048
Martin v. Löwis18e16552006-02-15 17:27:45 +00001049/* Create a new long int object from a C Py_ssize_t. */
1050
1051PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001052PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001053{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001054 PyLongObject *v;
1055 size_t abs_ival;
1056 size_t t; /* unsigned so >> doesn't propagate sign bit */
1057 int ndigits = 0;
1058 int negative = 0;
1059
1060 CHECK_SMALL_INT(ival);
1061 if (ival < 0) {
1062 /* avoid signed overflow when ival = SIZE_T_MIN */
1063 abs_ival = (size_t)(-1-ival)+1;
1064 negative = 1;
1065 }
1066 else {
1067 abs_ival = (size_t)ival;
1068 }
1069
1070 /* Count the number of Python digits. */
1071 t = abs_ival;
1072 while (t) {
1073 ++ndigits;
1074 t >>= PyLong_SHIFT;
1075 }
1076 v = _PyLong_New(ndigits);
1077 if (v != NULL) {
1078 digit *p = v->ob_digit;
1079 Py_SIZE(v) = negative ? -ndigits : ndigits;
1080 t = abs_ival;
1081 while (t) {
1082 *p++ = (digit)(t & PyLong_MASK);
1083 t >>= PyLong_SHIFT;
1084 }
1085 }
1086 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001087}
1088
1089/* Create a new long int object from a C size_t. */
1090
1091PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001092PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001094 PyLongObject *v;
1095 size_t t;
1096 int ndigits = 0;
1097
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001098 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001099 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001100 /* Count the number of Python digits. */
1101 t = ival;
1102 while (t) {
1103 ++ndigits;
1104 t >>= PyLong_SHIFT;
1105 }
1106 v = _PyLong_New(ndigits);
1107 if (v != NULL) {
1108 digit *p = v->ob_digit;
1109 Py_SIZE(v) = ndigits;
1110 while (ival) {
1111 *p++ = (digit)(ival & PyLong_MASK);
1112 ival >>= PyLong_SHIFT;
1113 }
1114 }
1115 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001116}
1117
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001118/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001119 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001121PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001122PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001123{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001124 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001125 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001126 int one = 1;
1127 int res;
1128
Tim Petersd38b1c72001-09-30 05:09:37 +00001129 if (vv == NULL) {
1130 PyErr_BadInternalCall();
1131 return -1;
1132 }
1133 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001134 PyNumberMethods *nb;
1135 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001136 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1137 nb->nb_int == NULL) {
1138 PyErr_SetString(PyExc_TypeError, "an integer is required");
1139 return -1;
1140 }
1141 io = (*nb->nb_int) (vv);
1142 if (io == NULL)
1143 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001144 if (PyLong_Check(io)) {
1145 bytes = PyLong_AsLongLong(io);
1146 Py_DECREF(io);
1147 return bytes;
1148 }
1149 Py_DECREF(io);
1150 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001151 return -1;
1152 }
1153
Guido van Rossumddefaf32007-01-14 03:31:43 +00001154 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001155 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001156 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001157 case 0: return 0;
1158 case 1: return v->ob_digit[0];
1159 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001160 res = _PyLong_AsByteArray(
1161 (PyLongObject *)vv, (unsigned char *)&bytes,
1162 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001163
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001164 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001165 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001166 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001167 else
1168 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169}
1170
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001171/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001172 Return -1 and set an error if overflow occurs. */
1173
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001174unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001175PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001176{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001177 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001178 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001179 int one = 1;
1180 int res;
1181
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001182 if (vv == NULL || !PyLong_Check(vv)) {
1183 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001185 }
1186
Guido van Rossumddefaf32007-01-14 03:31:43 +00001187 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001188 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001189 case 0: return 0;
1190 case 1: return v->ob_digit[0];
1191 }
1192
Tim Petersd1a7da62001-06-13 00:35:57 +00001193 res = _PyLong_AsByteArray(
1194 (PyLongObject *)vv, (unsigned char *)&bytes,
1195 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001197 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001198 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001199 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001200 else
1201 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001202}
Tim Petersd1a7da62001-06-13 00:35:57 +00001203
Thomas Hellera4ea6032003-04-17 18:55:45 +00001204/* Get a C unsigned long int from a long int object, ignoring the high bits.
1205 Returns -1 and sets an error condition if an error occurs. */
1206
Guido van Rossumddefaf32007-01-14 03:31:43 +00001207static unsigned PY_LONG_LONG
1208_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001209{
1210 register PyLongObject *v;
1211 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001212 Py_ssize_t i;
1213 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001214
1215 if (vv == NULL || !PyLong_Check(vv)) {
1216 PyErr_BadInternalCall();
1217 return (unsigned long) -1;
1218 }
1219 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001220 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001221 case 0: return 0;
1222 case 1: return v->ob_digit[0];
1223 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001224 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225 sign = 1;
1226 x = 0;
1227 if (i < 0) {
1228 sign = -1;
1229 i = -i;
1230 }
1231 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +00001232 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233 }
1234 return x * sign;
1235}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001236
1237unsigned PY_LONG_LONG
1238PyLong_AsUnsignedLongLongMask(register PyObject *op)
1239{
1240 PyNumberMethods *nb;
1241 PyLongObject *lo;
1242 unsigned PY_LONG_LONG val;
1243
1244 if (op && PyLong_Check(op))
1245 return _PyLong_AsUnsignedLongLongMask(op);
1246
1247 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1248 nb->nb_int == NULL) {
1249 PyErr_SetString(PyExc_TypeError, "an integer is required");
1250 return (unsigned PY_LONG_LONG)-1;
1251 }
1252
1253 lo = (PyLongObject*) (*nb->nb_int) (op);
1254 if (lo == NULL)
1255 return (unsigned PY_LONG_LONG)-1;
1256 if (PyLong_Check(lo)) {
1257 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1258 Py_DECREF(lo);
1259 if (PyErr_Occurred())
1260 return (unsigned PY_LONG_LONG)-1;
1261 return val;
1262 }
1263 else
1264 {
1265 Py_DECREF(lo);
1266 PyErr_SetString(PyExc_TypeError,
1267 "nb_int should return int object");
1268 return (unsigned PY_LONG_LONG)-1;
1269 }
1270}
Tim Petersd1a7da62001-06-13 00:35:57 +00001271#undef IS_LITTLE_ENDIAN
1272
Mark Dickinson93f562c2010-01-30 10:30:15 +00001273/* Get a C long long int from a Python long or Python int object.
1274 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1275 on the sign of the result. Otherwise *overflow is 0.
1276
1277 For other errors (e.g., type error), returns -1 and sets an error
1278 condition.
1279*/
1280
1281PY_LONG_LONG
1282PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1283{
1284 /* This version by Tim Peters */
1285 register PyLongObject *v;
1286 unsigned PY_LONG_LONG x, prev;
1287 PY_LONG_LONG res;
1288 Py_ssize_t i;
1289 int sign;
1290 int do_decref = 0; /* if nb_int was called */
1291
1292 *overflow = 0;
1293 if (vv == NULL) {
1294 PyErr_BadInternalCall();
1295 return -1;
1296 }
1297
1298 if (!PyLong_Check(vv)) {
1299 PyNumberMethods *nb;
1300 nb = vv->ob_type->tp_as_number;
1301 if (nb == NULL || nb->nb_int == NULL) {
1302 PyErr_SetString(PyExc_TypeError,
1303 "an integer is required");
1304 return -1;
1305 }
1306 vv = (*nb->nb_int) (vv);
1307 if (vv == NULL)
1308 return -1;
1309 do_decref = 1;
1310 if (!PyLong_Check(vv)) {
1311 Py_DECREF(vv);
1312 PyErr_SetString(PyExc_TypeError,
1313 "nb_int should return int object");
1314 return -1;
1315 }
1316 }
1317
1318 res = -1;
1319 v = (PyLongObject *)vv;
1320 i = Py_SIZE(v);
1321
1322 switch (i) {
1323 case -1:
1324 res = -(sdigit)v->ob_digit[0];
1325 break;
1326 case 0:
1327 res = 0;
1328 break;
1329 case 1:
1330 res = v->ob_digit[0];
1331 break;
1332 default:
1333 sign = 1;
1334 x = 0;
1335 if (i < 0) {
1336 sign = -1;
1337 i = -(i);
1338 }
1339 while (--i >= 0) {
1340 prev = x;
1341 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1342 if ((x >> PyLong_SHIFT) != prev) {
1343 *overflow = sign;
1344 goto exit;
1345 }
1346 }
1347 /* Haven't lost any bits, but casting to long requires extra
1348 * care (see comment above).
1349 */
1350 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1351 res = (PY_LONG_LONG)x * sign;
1352 }
1353 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1354 res = PY_LLONG_MIN;
1355 }
1356 else {
1357 *overflow = sign;
1358 /* res is already set to -1 */
1359 }
1360 }
1361 exit:
1362 if (do_decref) {
1363 Py_DECREF(vv);
1364 }
1365 return res;
1366}
1367
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001368#endif /* HAVE_LONG_LONG */
1369
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001370#define CHECK_BINOP(v,w) \
1371 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001372 Py_INCREF(Py_NotImplemented); \
1373 return Py_NotImplemented; \
1374 }
1375
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001376/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1377 2**k if d is nonzero, else 0. */
1378
1379static const unsigned char BitLengthTable[32] = {
1380 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1381 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1382};
1383
1384static int
1385bits_in_digit(digit d)
1386{
1387 int d_bits = 0;
1388 while (d >= 32) {
1389 d_bits += 6;
1390 d >>= 6;
1391 }
1392 d_bits += (int)BitLengthTable[d];
1393 return d_bits;
1394}
1395
Tim Peters877a2122002-08-12 05:09:36 +00001396/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1397 * is modified in place, by adding y to it. Carries are propagated as far as
1398 * x[m-1], and the remaining carry (0 or 1) is returned.
1399 */
1400static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001401v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001402{
Mark Dickinson17e55872009-01-24 15:56:57 +00001403 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001404 digit carry = 0;
1405
1406 assert(m >= n);
1407 for (i = 0; i < n; ++i) {
1408 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001409 x[i] = carry & PyLong_MASK;
1410 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001411 assert((carry & 1) == carry);
1412 }
1413 for (; carry && i < m; ++i) {
1414 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001415 x[i] = carry & PyLong_MASK;
1416 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001417 assert((carry & 1) == carry);
1418 }
1419 return carry;
1420}
1421
1422/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1423 * is modified in place, by subtracting y from it. Borrows are propagated as
1424 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1425 */
1426static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001427v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001428{
Mark Dickinson17e55872009-01-24 15:56:57 +00001429 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001430 digit borrow = 0;
1431
1432 assert(m >= n);
1433 for (i = 0; i < n; ++i) {
1434 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001435 x[i] = borrow & PyLong_MASK;
1436 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001437 borrow &= 1; /* keep only 1 sign bit */
1438 }
1439 for (; borrow && i < m; ++i) {
1440 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001441 x[i] = borrow & PyLong_MASK;
1442 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001443 borrow &= 1;
1444 }
1445 return borrow;
1446}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001447
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001448/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1449 * result in z[0:m], and return the d bits shifted out of the top.
1450 */
1451static digit
1452v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001453{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001454 Py_ssize_t i;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001455 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001456
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001457 assert(0 <= d && d < PyLong_SHIFT);
1458 for (i=0; i < m; i++) {
1459 twodigits acc = (twodigits)a[i] << d | carry;
1460 z[i] = (digit)acc & PyLong_MASK;
1461 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001462 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001463 return carry;
1464}
1465
1466/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1467 * result in z[0:m], and return the d bits shifted out of the bottom.
1468 */
1469static digit
1470v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1471{
1472 Py_ssize_t i;
1473 digit carry = 0;
1474 digit mask = ((digit)1 << d) - 1U;
1475
1476 assert(0 <= d && d < PyLong_SHIFT);
1477 for (i=m; i-- > 0;) {
1478 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1479 carry = (digit)acc & mask;
1480 z[i] = (digit)(acc >> d);
1481 }
1482 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001483}
1484
Tim Peters212e6142001-07-14 12:23:19 +00001485/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1486 in pout, and returning the remainder. pin and pout point at the LSD.
1487 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001488 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001489 immutable. */
1490
1491static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001492inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001493{
1494 twodigits rem = 0;
1495
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001496 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001497 pin += size;
1498 pout += size;
1499 while (--size >= 0) {
1500 digit hi;
Mark Dickinson24f57852009-09-28 17:54:52 +00001501 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001502 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001503 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001504 }
1505 return (digit)rem;
1506}
1507
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001508/* Divide a long integer by a digit, returning both the quotient
1509 (as function result) and the remainder (through *prem).
1510 The sign of a is ignored; n should not be zero. */
1511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001512static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001513divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001514{
Christian Heimes90aa7642007-12-19 02:45:37 +00001515 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001516 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001517
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001518 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001519 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001520 if (z == NULL)
1521 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001522 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001523 return long_normalize(z);
1524}
1525
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001526/* Convert a long integer to a base 10 string. Returns a new non-shared
1527 string. (Return value is non-shared so that callers can modify the
1528 returned value if necessary.) */
1529
1530static PyObject *
1531long_to_decimal_string(PyObject *aa)
1532{
1533 PyLongObject *scratch, *a;
1534 PyObject *str;
1535 Py_ssize_t size, strlen, size_a, i, j;
1536 digit *pout, *pin, rem, tenpow;
1537 Py_UNICODE *p;
1538 int negative;
1539
1540 a = (PyLongObject *)aa;
1541 if (a == NULL || !PyLong_Check(a)) {
1542 PyErr_BadInternalCall();
1543 return NULL;
1544 }
1545 size_a = ABS(Py_SIZE(a));
1546 negative = Py_SIZE(a) < 0;
1547
1548 /* quick and dirty upper bound for the number of digits
1549 required to express a in base _PyLong_DECIMAL_BASE:
1550
1551 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1552
1553 But log2(a) < size_a * PyLong_SHIFT, and
1554 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1555 > 3 * _PyLong_DECIMAL_SHIFT
1556 */
1557 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1558 PyErr_SetString(PyExc_OverflowError,
1559 "long is too large to format");
1560 return NULL;
1561 }
1562 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1563 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1564 scratch = _PyLong_New(size);
1565 if (scratch == NULL)
1566 return NULL;
1567
1568 /* convert array of base _PyLong_BASE digits in pin to an array of
1569 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1570 Volume 2 (3rd edn), section 4.4, Method 1b). */
1571 pin = a->ob_digit;
1572 pout = scratch->ob_digit;
1573 size = 0;
1574 for (i = size_a; --i >= 0; ) {
1575 digit hi = pin[i];
1576 for (j = 0; j < size; j++) {
1577 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson741984d2009-09-21 16:18:27 +00001578 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1579 pout[j] = (digit)(z - (twodigits)hi *
1580 _PyLong_DECIMAL_BASE);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001581 }
1582 while (hi) {
1583 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1584 hi /= _PyLong_DECIMAL_BASE;
1585 }
1586 /* check for keyboard interrupt */
1587 SIGCHECK({
1588 Py_DECREF(scratch);
1589 return NULL;
1590 })
1591 }
1592 /* pout should have at least one digit, so that the case when a = 0
1593 works correctly */
1594 if (size == 0)
1595 pout[size++] = 0;
1596
1597 /* calculate exact length of output string, and allocate */
1598 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1599 tenpow = 10;
1600 rem = pout[size-1];
1601 while (rem >= tenpow) {
1602 tenpow *= 10;
1603 strlen++;
1604 }
1605 str = PyUnicode_FromUnicode(NULL, strlen);
1606 if (str == NULL) {
1607 Py_DECREF(scratch);
1608 return NULL;
1609 }
1610
1611 /* fill the string right-to-left */
1612 p = PyUnicode_AS_UNICODE(str) + strlen;
1613 *p = '\0';
1614 /* pout[0] through pout[size-2] contribute exactly
1615 _PyLong_DECIMAL_SHIFT digits each */
1616 for (i=0; i < size - 1; i++) {
1617 rem = pout[i];
1618 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1619 *--p = '0' + rem % 10;
1620 rem /= 10;
1621 }
1622 }
1623 /* pout[size-1]: always produce at least one decimal digit */
1624 rem = pout[i];
1625 do {
1626 *--p = '0' + rem % 10;
1627 rem /= 10;
1628 } while (rem != 0);
1629
1630 /* and sign */
1631 if (negative)
1632 *--p = '-';
1633
1634 /* check we've counted correctly */
1635 assert(p == PyUnicode_AS_UNICODE(str));
1636 Py_DECREF(scratch);
1637 return (PyObject *)str;
1638}
1639
Mark Dickinsoncd068122009-09-18 14:53:08 +00001640/* Convert a long int object to a string, using a given conversion base,
1641 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001642 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001643
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001644PyObject *
1645_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001646{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001647 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001648 PyObject *str;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001649 Py_ssize_t i, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001650 Py_ssize_t size_a;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001651 Py_UNICODE *p, sign = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001652 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001653
Mark Dickinsoncd068122009-09-18 14:53:08 +00001654 assert(base == 2 || base == 8 || base == 10 || base == 16);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001655 if (base == 10)
1656 return long_to_decimal_string((PyObject *)a);
1657
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001658 if (a == NULL || !PyLong_Check(a)) {
1659 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001660 return NULL;
1661 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001662 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001663
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001664 /* Compute a rough upper bound for the length of the string */
Mark Dickinsoncd068122009-09-18 14:53:08 +00001665 switch (base) {
1666 case 16:
1667 bits = 4;
1668 break;
1669 case 8:
1670 bits = 3;
1671 break;
1672 case 2:
1673 bits = 1;
1674 break;
1675 default:
1676 assert(0); /* shouldn't ever get here */
1677 bits = 0; /* to silence gcc warning */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001678 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001679 /* compute length of output string: allow 2 characters for prefix and
1680 1 for possible '-' sign. */
1681 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001682 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001683 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001684 return NULL;
1685 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001686 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1687 is safe from overflow */
1688 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001689 assert(sz >= 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001690 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001691 if (str == NULL)
1692 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001693 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001694 *p = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001695 if (Py_SIZE(a) < 0)
1696 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001697
Christian Heimes90aa7642007-12-19 02:45:37 +00001698 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001699 *--p = '0';
1700 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001701 else {
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001702 /* JRH: special case for power-of-2 bases */
1703 twodigits accum = 0;
1704 int accumbits = 0; /* # of bits in accum */
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001705 for (i = 0; i < size_a; ++i) {
1706 accum |= (twodigits)a->ob_digit[i] << accumbits;
1707 accumbits += PyLong_SHIFT;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001708 assert(accumbits >= bits);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001709 do {
Mark Dickinson1f7e18c2009-09-24 18:31:17 +00001710 Py_UNICODE cdigit;
1711 cdigit = (Py_UNICODE)(accum & (base - 1));
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001712 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1713 assert(p > PyUnicode_AS_UNICODE(str));
1714 *--p = cdigit;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001715 accumbits -= bits;
1716 accum >>= bits;
1717 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001718 }
1719 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001720
Mark Dickinsoncd068122009-09-18 14:53:08 +00001721 if (base == 16)
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001722 *--p = 'x';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001723 else if (base == 8)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001724 *--p = 'o';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001725 else /* (base == 2) */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001726 *--p = 'b';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001727 *--p = '0';
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001728 if (sign)
1729 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001730 if (p != PyUnicode_AS_UNICODE(str)) {
1731 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001732 assert(p > q);
1733 do {
1734 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001735 q--;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001736 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1737 PyUnicode_AS_UNICODE(str)))) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001738 Py_DECREF(str);
1739 return NULL;
1740 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001741 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001742 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001743}
1744
Thomas Wouters477c8d52006-05-27 19:21:47 +00001745/* Table of digit values for 8-bit string -> integer conversion.
1746 * '0' maps to 0, ..., '9' maps to 9.
1747 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1748 * All other indices map to 37.
1749 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001750 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001751 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001752unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001753 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1754 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1755 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1756 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1757 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1758 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1759 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1760 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1761 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1762 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1763 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1764 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1765 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1766 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1767 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1768 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1769};
1770
1771/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001772 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1773 * non-digit (which may be *str!). A normalized long is returned.
1774 * The point to this routine is that it takes time linear in the number of
1775 * string characters.
1776 */
1777static PyLongObject *
1778long_from_binary_base(char **str, int base)
1779{
1780 char *p = *str;
1781 char *start = p;
1782 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001783 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001784 PyLongObject *z;
1785 twodigits accum;
1786 int bits_in_accum;
1787 digit *pdigit;
1788
1789 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1790 n = base;
1791 for (bits_per_char = -1; n; ++bits_per_char)
1792 n >>= 1;
1793 /* n <- total # of bits needed, while setting p to end-of-string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001794 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001795 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001796 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001797 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1798 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001799 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001800 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001801 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001802 return NULL;
1803 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001804 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001805 z = _PyLong_New(n);
1806 if (z == NULL)
1807 return NULL;
1808 /* Read string from right, and fill in long from left; i.e.,
1809 * from least to most significant in both.
1810 */
1811 accum = 0;
1812 bits_in_accum = 0;
1813 pdigit = z->ob_digit;
1814 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001815 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001816 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001817 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001818 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001819 if (bits_in_accum >= PyLong_SHIFT) {
1820 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001821 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001822 accum >>= PyLong_SHIFT;
1823 bits_in_accum -= PyLong_SHIFT;
1824 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001825 }
1826 }
1827 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001828 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001829 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001830 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001831 }
1832 while (pdigit - z->ob_digit < n)
1833 *pdigit++ = 0;
1834 return long_normalize(z);
1835}
1836
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001837PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001838PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001839{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001840 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001841 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001842 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001843 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001844 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001845
Guido van Rossum472c04f1996-12-05 21:57:21 +00001846 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001847 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001848 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001849 return NULL;
1850 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001851 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001852 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001853 if (*str == '+')
1854 ++str;
1855 else if (*str == '-') {
1856 ++str;
1857 sign = -1;
1858 }
1859 if (base == 0) {
1860 if (str[0] != '0')
1861 base = 10;
1862 else if (str[1] == 'x' || str[1] == 'X')
1863 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001864 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001865 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001866 else if (str[1] == 'b' || str[1] == 'B')
1867 base = 2;
1868 else {
1869 /* "old" (C-style) octal literal, now invalid.
1870 it might still be zero though */
1871 error_if_nonzero = 1;
1872 base = 10;
1873 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001874 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001875 if (str[0] == '0' &&
1876 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1877 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1878 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001879 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001880
Guido van Rossume6762971998-06-22 03:54:46 +00001881 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001882 if ((base & (base - 1)) == 0)
1883 z = long_from_binary_base(&str, base);
1884 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001885/***
1886Binary bases can be converted in time linear in the number of digits, because
1887Python's representation base is binary. Other bases (including decimal!) use
1888the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001889
Thomas Wouters477c8d52006-05-27 19:21:47 +00001890First some math: the largest integer that can be expressed in N base-B digits
1891is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1892case number of Python digits needed to hold it is the smallest integer n s.t.
1893
1894 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1895 BASE**n >= B**N [taking logs to base BASE]
1896 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1897
1898The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1899this quickly. A Python long with that much space is reserved near the start,
1900and the result is computed into it.
1901
1902The input string is actually treated as being in base base**i (i.e., i digits
1903are processed at a time), where two more static arrays hold:
1904
1905 convwidth_base[base] = the largest integer i such that base**i <= BASE
1906 convmultmax_base[base] = base ** convwidth_base[base]
1907
1908The first of these is the largest i such that i consecutive input digits
1909must fit in a single Python digit. The second is effectively the input
1910base we're really using.
1911
1912Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1913convmultmax_base[base], the result is "simply"
1914
1915 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1916
1917where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001918
1919Error analysis: as above, the number of Python digits `n` needed is worst-
1920case
1921
1922 n >= N * log(B)/log(BASE)
1923
1924where `N` is the number of input digits in base `B`. This is computed via
1925
1926 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1927
1928below. Two numeric concerns are how much space this can waste, and whether
1929the computed result can be too small. To be concrete, assume BASE = 2**15,
1930which is the default (and it's unlikely anyone changes that).
1931
1932Waste isn't a problem: provided the first input digit isn't 0, the difference
1933between the worst-case input with N digits and the smallest input with N
1934digits is about a factor of B, but B is small compared to BASE so at most
1935one allocated Python digit can remain unused on that count. If
1936N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1937and adding 1 returns a result 1 larger than necessary. However, that can't
1938happen: whenever B is a power of 2, long_from_binary_base() is called
1939instead, and it's impossible for B**i to be an integer power of 2**15 when
1940B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1941an exact integer when B is not a power of 2, since B**i has a prime factor
1942other than 2 in that case, but (2**15)**j's only prime factor is 2).
1943
1944The computed result can be too small if the true value of N*log(B)/log(BASE)
1945is a little bit larger than an exact integer, but due to roundoff errors (in
1946computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1947yields a numeric result a little less than that integer. Unfortunately, "how
1948close can a transcendental function get to an integer over some range?"
1949questions are generally theoretically intractable. Computer analysis via
1950continued fractions is practical: expand log(B)/log(BASE) via continued
1951fractions, giving a sequence i/j of "the best" rational approximations. Then
1952j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1953we can get very close to being in trouble, but very rarely. For example,
195476573 is a denominator in one of the continued-fraction approximations to
1955log(10)/log(2**15), and indeed:
1956
1957 >>> log(10)/log(2**15)*76573
1958 16958.000000654003
1959
1960is very close to an integer. If we were working with IEEE single-precision,
1961rounding errors could kill us. Finding worst cases in IEEE double-precision
1962requires better-than-double-precision log() functions, and Tim didn't bother.
1963Instead the code checks to see whether the allocated space is enough as each
1964new Python digit is added, and copies the whole thing to a larger long if not.
1965This should happen extremely rarely, and in fact I don't have a test case
1966that triggers it(!). Instead the code was tested by artificially allocating
1967just 1 digit at the start, so that the copying code was exercised for every
1968digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001969***/
1970 register twodigits c; /* current input character */
1971 Py_ssize_t size_z;
1972 int i;
1973 int convwidth;
1974 twodigits convmultmax, convmult;
1975 digit *pz, *pzstop;
1976 char* scan;
1977
1978 static double log_base_BASE[37] = {0.0e0,};
1979 static int convwidth_base[37] = {0,};
1980 static twodigits convmultmax_base[37] = {0,};
1981
1982 if (log_base_BASE[base] == 0.0) {
1983 twodigits convmax = base;
1984 int i = 1;
1985
1986 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001987 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001988 for (;;) {
1989 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001990 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991 break;
1992 convmax = next;
1993 ++i;
1994 }
1995 convmultmax_base[base] = convmax;
1996 assert(i > 0);
1997 convwidth_base[base] = i;
1998 }
1999
2000 /* Find length of the string of numeric characters. */
2001 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00002002 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002003 ++scan;
2004
2005 /* Create a long object that can contain the largest possible
2006 * integer with this base and length. Note that there's no
2007 * need to initialize z->ob_digit -- no slot is read up before
2008 * being stored into.
2009 */
2010 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011 /* Uncomment next line to test exceedingly rare copy code */
2012 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002013 assert(size_z > 0);
2014 z = _PyLong_New(size_z);
2015 if (z == NULL)
2016 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002017 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018
2019 /* `convwidth` consecutive input digits are treated as a single
2020 * digit in base `convmultmax`.
2021 */
2022 convwidth = convwidth_base[base];
2023 convmultmax = convmultmax_base[base];
2024
2025 /* Work ;-) */
2026 while (str < scan) {
2027 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00002028 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002029 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2030 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00002031 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002032 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002033 }
2034
2035 convmult = convmultmax;
2036 /* Calculate the shift only if we couldn't get
2037 * convwidth digits.
2038 */
2039 if (i != convwidth) {
2040 convmult = base;
2041 for ( ; i > 1; --i)
2042 convmult *= base;
2043 }
2044
2045 /* Multiply z by convmult, and add c. */
2046 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00002047 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048 for (; pz < pzstop; ++pz) {
2049 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002050 *pz = (digit)(c & PyLong_MASK);
2051 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002052 }
2053 /* carry off the current end? */
2054 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002055 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00002056 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002057 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00002058 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002059 }
2060 else {
2061 PyLongObject *tmp;
2062 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002063 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002064 tmp = _PyLong_New(size_z + 1);
2065 if (tmp == NULL) {
2066 Py_DECREF(z);
2067 return NULL;
2068 }
2069 memcpy(tmp->ob_digit,
2070 z->ob_digit,
2071 sizeof(digit) * size_z);
2072 Py_DECREF(z);
2073 z = tmp;
2074 z->ob_digit[size_z] = (digit)c;
2075 ++size_z;
2076 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002077 }
Tim Petersbf2674b2003-02-02 07:51:32 +00002078 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00002080 if (z == NULL)
2081 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002082 if (error_if_nonzero) {
2083 /* reset the base to 0, else the exception message
2084 doesn't make too much sense */
2085 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00002086 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002087 goto onError;
2088 /* there might still be other problems, therefore base
2089 remains zero here for the same reason */
2090 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00002091 if (str == start)
2092 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002093 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00002094 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00002095 while (*str && isspace(Py_CHARMASK(*str)))
2096 str++;
2097 if (*str != '\0')
2098 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002099 if (pend)
2100 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002101 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002102 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002103
2104 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002105 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002106 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002107 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002108 if (strobj == NULL)
2109 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002110 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002111 "invalid literal for int() with base %d: %R",
2112 base, strobj);
2113 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002114 return NULL;
2115}
2116
2117PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002118PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002119{
Walter Dörwald07e14762002-11-06 16:15:14 +00002120 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002121 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002122
Walter Dörwald07e14762002-11-06 16:15:14 +00002123 if (buffer == NULL)
2124 return NULL;
2125
2126 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2127 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002128 return NULL;
2129 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002130 result = PyLong_FromString(buffer, NULL, base);
2131 PyMem_FREE(buffer);
2132 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002133}
2134
Tim Peters9f688bf2000-07-07 15:53:28 +00002135/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002137 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002138static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002139
2140/* Long division with remainder, top-level routine */
2141
Guido van Rossume32e0141992-01-19 16:31:05 +00002142static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002143long_divrem(PyLongObject *a, PyLongObject *b,
2144 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145{
Christian Heimes90aa7642007-12-19 02:45:37 +00002146 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002148
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002150 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002151 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002152 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002153 }
2154 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002155 (size_a == size_b &&
2156 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002158 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002159 if (*pdiv == NULL)
2160 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 Py_INCREF(a);
2162 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002163 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002164 }
2165 if (size_b == 1) {
2166 digit rem = 0;
2167 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002168 if (z == NULL)
2169 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002170 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002171 if (*prem == NULL) {
2172 Py_DECREF(z);
2173 return -1;
2174 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002175 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002176 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002177 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002178 if (z == NULL)
2179 return -1;
2180 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002181 /* Set the signs.
2182 The quotient z has the sign of a*b;
2183 the remainder r has the sign of a,
2184 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002185 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002186 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002187 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002188 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002189 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002190 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002191}
2192
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002193/* Unsigned long division with remainder -- the algorithm. The arguments v1
2194 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002197x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002198{
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002199 PyLongObject *v, *w, *a;
2200 Py_ssize_t i, k, size_v, size_w;
2201 int d;
2202 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2203 twodigits vv;
2204 sdigit zhi;
2205 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002206
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002207 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2208 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2209 handle the special case when the initial estimate q for a quotient
2210 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2211 that won't overflow a digit. */
2212
2213 /* allocate space; w will also be used to hold the final remainder */
2214 size_v = ABS(Py_SIZE(v1));
2215 size_w = ABS(Py_SIZE(w1));
2216 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2217 v = _PyLong_New(size_v+1);
2218 if (v == NULL) {
2219 *prem = NULL;
2220 return NULL;
2221 }
2222 w = _PyLong_New(size_w);
2223 if (w == NULL) {
2224 Py_DECREF(v);
2225 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002226 return NULL;
2227 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002228
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002229 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2230 shift v1 left by the same amount. Results go into w and v. */
2231 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2232 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2233 assert(carry == 0);
2234 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2235 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2236 v->ob_digit[size_v] = carry;
2237 size_v++;
2238 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002239
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002240 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2241 at most (and usually exactly) k = size_v - size_w digits. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002242 k = size_v - size_w;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002243 assert(k >= 0);
2244 a = _PyLong_New(k);
2245 if (a == NULL) {
2246 Py_DECREF(w);
2247 Py_DECREF(v);
2248 *prem = NULL;
2249 return NULL;
2250 }
2251 v0 = v->ob_digit;
2252 w0 = w->ob_digit;
2253 wm1 = w0[size_w-1];
2254 wm2 = w0[size_w-2];
2255 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2256 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2257 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002258
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002259 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260 Py_DECREF(a);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002261 Py_DECREF(w);
2262 Py_DECREF(v);
2263 *prem = NULL;
2264 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002265 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002266
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002267 /* estimate quotient digit q; may overestimate by 1 (rare) */
2268 vtop = vk[size_w];
2269 assert(vtop <= wm1);
2270 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2271 q = (digit)(vv / wm1);
2272 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2273 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2274 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002275 --q;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002276 r += wm1;
2277 if (r >= PyLong_BASE)
2278 break;
2279 }
2280 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002281
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002282 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2283 zhi = 0;
2284 for (i = 0; i < size_w; ++i) {
2285 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2286 -PyLong_BASE * q <= z < PyLong_BASE */
2287 z = (sdigit)vk[i] + zhi -
2288 (stwodigits)q * (stwodigits)w0[i];
2289 vk[i] = (digit)z & PyLong_MASK;
2290 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2291 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002292 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002293
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002294 /* add w back if q was too large (this branch taken rarely) */
2295 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2296 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002297 carry = 0;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002298 for (i = 0; i < size_w; ++i) {
2299 carry += vk[i] + w0[i];
2300 vk[i] = carry & PyLong_MASK;
2301 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002302 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002303 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002304 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002305
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002306 /* store quotient digit */
2307 assert(q < PyLong_BASE);
2308 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002309 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002310
2311 /* unshift remainder; we reuse w to store the result */
2312 carry = v_rshift(w0, v0, size_w, d);
2313 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002314 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002315
2316 *prem = long_normalize(w);
2317 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002318}
2319
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002320/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2321 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2322 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2323 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2324 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2325 -1.0. */
2326
2327/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2328#if DBL_MANT_DIG == 53
2329#define EXP2_DBL_MANT_DIG 9007199254740992.0
2330#else
2331#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2332#endif
2333
2334double
2335_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2336{
2337 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2338 /* See below for why x_digits is always large enough. */
2339 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2340 double dx;
2341 /* Correction term for round-half-to-even rounding. For a digit x,
2342 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2343 multiple of 4, rounding ties to a multiple of 8. */
2344 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
2345
2346 a_size = ABS(Py_SIZE(a));
2347 if (a_size == 0) {
2348 /* Special case for 0: significand 0.0, exponent 0. */
2349 *e = 0;
2350 return 0.0;
2351 }
2352 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2353 /* The following is an overflow-free version of the check
2354 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2355 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2356 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2357 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
2358 goto overflow;
2359 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
2360
2361 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2362 (shifting left if a_bits <= DBL_MANT_DIG + 2).
2363
2364 Number of digits needed for result: write // for floor division.
2365 Then if shifting left, we end up using
2366
2367 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
2368
2369 digits. If shifting right, we use
2370
2371 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
2372
2373 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2374 the inequalities
2375
2376 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2377 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2378 1 + (m - n - 1) // PyLong_SHIFT,
2379
2380 valid for any integers m and n, we find that x_size satisfies
2381
2382 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
2383
2384 in both cases.
2385 */
2386 if (a_bits <= DBL_MANT_DIG + 2) {
2387 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2388 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2389 x_size = 0;
2390 while (x_size < shift_digits)
2391 x_digits[x_size++] = 0;
2392 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2393 shift_bits);
2394 x_size += a_size;
2395 x_digits[x_size++] = rem;
2396 }
2397 else {
2398 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2399 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2400 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2401 a_size - shift_digits, shift_bits);
2402 x_size = a_size - shift_digits;
2403 /* For correct rounding below, we need the least significant
2404 bit of x to be 'sticky' for this shift: if any of the bits
2405 shifted out was nonzero, we set the least significant bit
2406 of x. */
2407 if (rem)
2408 x_digits[0] |= 1;
2409 else
2410 while (shift_digits > 0)
2411 if (a->ob_digit[--shift_digits]) {
2412 x_digits[0] |= 1;
2413 break;
2414 }
2415 }
2416 assert(1 <= x_size && x_size <= sizeof(x_digits)/sizeof(digit));
2417
2418 /* Round, and convert to double. */
2419 x_digits[0] += half_even_correction[x_digits[0] & 7];
2420 dx = x_digits[--x_size];
2421 while (x_size > 0)
2422 dx = dx * PyLong_BASE + x_digits[--x_size];
2423
2424 /* Rescale; make correction if result is 1.0. */
2425 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2426 if (dx == 1.0) {
2427 if (a_bits == PY_SSIZE_T_MAX)
2428 goto overflow;
2429 dx = 0.5;
2430 a_bits += 1;
2431 }
2432
2433 *e = a_bits;
2434 return Py_SIZE(a) < 0 ? -dx : dx;
2435
2436 overflow:
2437 /* exponent > PY_SSIZE_T_MAX */
2438 PyErr_SetString(PyExc_OverflowError,
2439 "huge integer: number of bits overflows a Py_ssize_t");
2440 *e = 0;
2441 return -1.0;
2442}
2443
2444/* Get a C double from a long int object. Rounds to the nearest double,
2445 using the round-half-to-even rule in the case of a tie. */
2446
2447double
2448PyLong_AsDouble(PyObject *v)
2449{
2450 Py_ssize_t exponent;
2451 double x;
2452
2453 if (v == NULL || !PyLong_Check(v)) {
2454 PyErr_BadInternalCall();
2455 return -1.0;
2456 }
2457 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2458 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2459 PyErr_SetString(PyExc_OverflowError,
2460 "long int too large to convert to float");
2461 return -1.0;
2462 }
2463 return ldexp(x, exponent);
2464}
2465
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002466/* Methods */
2467
2468static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002469long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002470{
Christian Heimes90aa7642007-12-19 02:45:37 +00002471 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002472}
2473
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002474static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002475long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002476{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002477 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002478
Christian Heimes90aa7642007-12-19 02:45:37 +00002479 if (Py_SIZE(a) != Py_SIZE(b)) {
2480 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002481 sign = 0;
2482 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002483 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002484 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002485 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002486 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002487 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2488 ;
2489 if (i < 0)
2490 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002491 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002492 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002493 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002494 sign = -sign;
2495 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002496 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002497 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002498}
2499
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002500#define TEST_COND(cond) \
2501 ((cond) ? Py_True : Py_False)
2502
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002503static PyObject *
2504long_richcompare(PyObject *self, PyObject *other, int op)
2505{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002506 int result;
2507 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002508 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002509 if (self == other)
2510 result = 0;
2511 else
2512 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2513 /* Convert the return value to a Boolean */
2514 switch (op) {
2515 case Py_EQ:
2516 v = TEST_COND(result == 0);
2517 break;
2518 case Py_NE:
2519 v = TEST_COND(result != 0);
2520 break;
2521 case Py_LE:
2522 v = TEST_COND(result <= 0);
2523 break;
2524 case Py_GE:
2525 v = TEST_COND(result >= 0);
2526 break;
2527 case Py_LT:
2528 v = TEST_COND(result == -1);
2529 break;
2530 case Py_GT:
2531 v = TEST_COND(result == 1);
2532 break;
2533 default:
2534 PyErr_BadArgument();
2535 return NULL;
2536 }
2537 Py_INCREF(v);
2538 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002539}
2540
Guido van Rossum9bfef441993-03-29 10:43:31 +00002541static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002542long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002543{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002544 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002545 Py_ssize_t i;
2546 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002547
2548 /* This is designed so that Python ints and longs with the
2549 same value hash to the same value, otherwise comparisons
2550 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002551 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002552 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002553 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002554 case 0: return 0;
2555 case 1: return v->ob_digit[0];
2556 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002557 sign = 1;
2558 x = 0;
2559 if (i < 0) {
2560 sign = -1;
2561 i = -(i);
2562 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002563 /* The following loop produces a C unsigned long x such that x is
2564 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002565 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002566 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002567 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002568 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002569 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002570 /* If the addition above overflowed we compensate by
2571 incrementing. This preserves the value modulo
2572 ULONG_MAX. */
2573 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002574 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002575 }
2576 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002577 if (x == (unsigned long)-1)
2578 x = (unsigned long)-2;
2579 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002580}
2581
2582
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002583/* Add the absolute values of two long integers. */
2584
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002585static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002586x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002587{
Christian Heimes90aa7642007-12-19 02:45:37 +00002588 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002589 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002590 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002591 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002592
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002593 /* Ensure a is the larger of the two: */
2594 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002595 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002596 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002597 size_a = size_b;
2598 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002599 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002600 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002601 if (z == NULL)
2602 return NULL;
2603 for (i = 0; i < size_b; ++i) {
2604 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002605 z->ob_digit[i] = carry & PyLong_MASK;
2606 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002607 }
2608 for (; i < size_a; ++i) {
2609 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002610 z->ob_digit[i] = carry & PyLong_MASK;
2611 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002612 }
2613 z->ob_digit[i] = carry;
2614 return long_normalize(z);
2615}
2616
2617/* Subtract the absolute values of two integers. */
2618
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002619static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002620x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002621{
Christian Heimes90aa7642007-12-19 02:45:37 +00002622 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002623 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002624 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002625 int sign = 1;
2626 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002627
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002628 /* Ensure a is the larger of the two: */
2629 if (size_a < size_b) {
2630 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002631 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002632 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002633 size_a = size_b;
2634 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002635 }
2636 else if (size_a == size_b) {
2637 /* Find highest digit where a and b differ: */
2638 i = size_a;
2639 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2640 ;
2641 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002642 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643 if (a->ob_digit[i] < b->ob_digit[i]) {
2644 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002645 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002646 }
2647 size_a = size_b = i+1;
2648 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002649 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002650 if (z == NULL)
2651 return NULL;
2652 for (i = 0; i < size_b; ++i) {
2653 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002654 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002655 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002656 z->ob_digit[i] = borrow & PyLong_MASK;
2657 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002658 borrow &= 1; /* Keep only one sign bit */
2659 }
2660 for (; i < size_a; ++i) {
2661 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002662 z->ob_digit[i] = borrow & PyLong_MASK;
2663 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002664 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002665 }
2666 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002667 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002668 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002669 return long_normalize(z);
2670}
2671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002672static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002673long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002674{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002675 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002676
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002677 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002678
Christian Heimes90aa7642007-12-19 02:45:37 +00002679 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002680 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002681 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002682 return result;
2683 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002684 if (Py_SIZE(a) < 0) {
2685 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002686 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002687 if (z != NULL && Py_SIZE(z) != 0)
2688 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002689 }
2690 else
2691 z = x_sub(b, a);
2692 }
2693 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002694 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002695 z = x_sub(a, b);
2696 else
2697 z = x_add(a, b);
2698 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002699 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002700}
2701
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002702static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002703long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002704{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002705 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002706
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002707 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002708
Christian Heimes90aa7642007-12-19 02:45:37 +00002709 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002710 PyObject* r;
2711 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002712 return r;
2713 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002714 if (Py_SIZE(a) < 0) {
2715 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002716 z = x_sub(a, b);
2717 else
2718 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002719 if (z != NULL && Py_SIZE(z) != 0)
2720 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002721 }
2722 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002723 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002724 z = x_add(a, b);
2725 else
2726 z = x_sub(a, b);
2727 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002728 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002729}
2730
Tim Peters5af4e6c2002-08-12 02:31:19 +00002731/* Grade school multiplication, ignoring the signs.
2732 * Returns the absolute value of the product, or NULL if error.
2733 */
2734static PyLongObject *
2735x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002736{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002737 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002738 Py_ssize_t size_a = ABS(Py_SIZE(a));
2739 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002740 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002741
Tim Peters5af4e6c2002-08-12 02:31:19 +00002742 z = _PyLong_New(size_a + size_b);
2743 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002744 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002745
Christian Heimes90aa7642007-12-19 02:45:37 +00002746 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002747 if (a == b) {
2748 /* Efficient squaring per HAC, Algorithm 14.16:
2749 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2750 * Gives slightly less than a 2x speedup when a == b,
2751 * via exploiting that each entry in the multiplication
2752 * pyramid appears twice (except for the size_a squares).
2753 */
2754 for (i = 0; i < size_a; ++i) {
2755 twodigits carry;
2756 twodigits f = a->ob_digit[i];
2757 digit *pz = z->ob_digit + (i << 1);
2758 digit *pa = a->ob_digit + i + 1;
2759 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002760
Tim Peters0973b992004-08-29 22:16:50 +00002761 SIGCHECK({
2762 Py_DECREF(z);
2763 return NULL;
2764 })
2765
2766 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002767 *pz++ = (digit)(carry & PyLong_MASK);
2768 carry >>= PyLong_SHIFT;
2769 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002770
2771 /* Now f is added in twice in each column of the
2772 * pyramid it appears. Same as adding f<<1 once.
2773 */
2774 f <<= 1;
2775 while (pa < paend) {
2776 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002777 *pz++ = (digit)(carry & PyLong_MASK);
2778 carry >>= PyLong_SHIFT;
2779 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002780 }
2781 if (carry) {
2782 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002783 *pz++ = (digit)(carry & PyLong_MASK);
2784 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002785 }
2786 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002787 *pz += (digit)(carry & PyLong_MASK);
2788 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002789 }
Tim Peters0973b992004-08-29 22:16:50 +00002790 }
2791 else { /* a is not the same as b -- gradeschool long mult */
2792 for (i = 0; i < size_a; ++i) {
2793 twodigits carry = 0;
2794 twodigits f = a->ob_digit[i];
2795 digit *pz = z->ob_digit + i;
2796 digit *pb = b->ob_digit;
2797 digit *pbend = b->ob_digit + size_b;
2798
2799 SIGCHECK({
2800 Py_DECREF(z);
2801 return NULL;
2802 })
2803
2804 while (pb < pbend) {
2805 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002806 *pz++ = (digit)(carry & PyLong_MASK);
2807 carry >>= PyLong_SHIFT;
2808 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002809 }
2810 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002811 *pz += (digit)(carry & PyLong_MASK);
2812 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002813 }
2814 }
Tim Peters44121a62002-08-12 06:17:58 +00002815 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002816}
2817
2818/* A helper for Karatsuba multiplication (k_mul).
2819 Takes a long "n" and an integer "size" representing the place to
2820 split, and sets low and high such that abs(n) == (high << size) + low,
2821 viewing the shift as being by digits. The sign bit is ignored, and
2822 the return values are >= 0.
2823 Returns 0 on success, -1 on failure.
2824*/
2825static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002826kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002827{
2828 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002829 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002830 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002831
2832 size_lo = MIN(size_n, size);
2833 size_hi = size_n - size_lo;
2834
2835 if ((hi = _PyLong_New(size_hi)) == NULL)
2836 return -1;
2837 if ((lo = _PyLong_New(size_lo)) == NULL) {
2838 Py_DECREF(hi);
2839 return -1;
2840 }
2841
2842 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2843 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2844
2845 *high = long_normalize(hi);
2846 *low = long_normalize(lo);
2847 return 0;
2848}
2849
Tim Peters60004642002-08-12 22:01:34 +00002850static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2851
Tim Peters5af4e6c2002-08-12 02:31:19 +00002852/* Karatsuba multiplication. Ignores the input signs, and returns the
2853 * absolute value of the product (or NULL if error).
2854 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2855 */
2856static PyLongObject *
2857k_mul(PyLongObject *a, PyLongObject *b)
2858{
Christian Heimes90aa7642007-12-19 02:45:37 +00002859 Py_ssize_t asize = ABS(Py_SIZE(a));
2860 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002861 PyLongObject *ah = NULL;
2862 PyLongObject *al = NULL;
2863 PyLongObject *bh = NULL;
2864 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002865 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002866 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002867 Py_ssize_t shift; /* the number of digits we split off */
2868 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002869
Tim Peters5af4e6c2002-08-12 02:31:19 +00002870 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2871 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2872 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002873 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002874 * By picking X to be a power of 2, "*X" is just shifting, and it's
2875 * been reduced to 3 multiplies on numbers half the size.
2876 */
2877
Tim Petersfc07e562002-08-12 02:54:10 +00002878 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002879 * is largest.
2880 */
Tim Peters738eda72002-08-12 15:08:20 +00002881 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002882 t1 = a;
2883 a = b;
2884 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002885
2886 i = asize;
2887 asize = bsize;
2888 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002889 }
2890
2891 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002892 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2893 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002894 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002895 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002896 else
2897 return x_mul(a, b);
2898 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002899
Tim Peters60004642002-08-12 22:01:34 +00002900 /* If a is small compared to b, splitting on b gives a degenerate
2901 * case with ah==0, and Karatsuba may be (even much) less efficient
2902 * than "grade school" then. However, we can still win, by viewing
2903 * b as a string of "big digits", each of width a->ob_size. That
2904 * leads to a sequence of balanced calls to k_mul.
2905 */
2906 if (2 * asize <= bsize)
2907 return k_lopsided_mul(a, b);
2908
Tim Petersd6974a52002-08-13 20:37:51 +00002909 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002910 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002911 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002912 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002913
Tim Peters0973b992004-08-29 22:16:50 +00002914 if (a == b) {
2915 bh = ah;
2916 bl = al;
2917 Py_INCREF(bh);
2918 Py_INCREF(bl);
2919 }
2920 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002921
Tim Petersd64c1de2002-08-12 17:36:03 +00002922 /* The plan:
2923 * 1. Allocate result space (asize + bsize digits: that's always
2924 * enough).
2925 * 2. Compute ah*bh, and copy into result at 2*shift.
2926 * 3. Compute al*bl, and copy into result at 0. Note that this
2927 * can't overlap with #2.
2928 * 4. Subtract al*bl from the result, starting at shift. This may
2929 * underflow (borrow out of the high digit), but we don't care:
2930 * we're effectively doing unsigned arithmetic mod
2931 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2932 * borrows and carries out of the high digit can be ignored.
2933 * 5. Subtract ah*bh from the result, starting at shift.
2934 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2935 * at shift.
2936 */
2937
2938 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002939 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002940 if (ret == NULL) goto fail;
2941#ifdef Py_DEBUG
2942 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002943 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002944#endif
Tim Peters44121a62002-08-12 06:17:58 +00002945
Tim Petersd64c1de2002-08-12 17:36:03 +00002946 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002947 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002948 assert(Py_SIZE(t1) >= 0);
2949 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002950 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002951 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002952
2953 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002954 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002955 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002956 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002957 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002958
Tim Petersd64c1de2002-08-12 17:36:03 +00002959 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002960 if ((t2 = k_mul(al, bl)) == NULL) {
2961 Py_DECREF(t1);
2962 goto fail;
2963 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002964 assert(Py_SIZE(t2) >= 0);
2965 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2966 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002967
2968 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002969 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002970 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002971 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002972
Tim Petersd64c1de2002-08-12 17:36:03 +00002973 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2974 * because it's fresher in cache.
2975 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002976 i = Py_SIZE(ret) - shift; /* # digits after shift */
2977 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002978 Py_DECREF(t2);
2979
Christian Heimes90aa7642007-12-19 02:45:37 +00002980 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002981 Py_DECREF(t1);
2982
Tim Petersd64c1de2002-08-12 17:36:03 +00002983 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002984 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2985 Py_DECREF(ah);
2986 Py_DECREF(al);
2987 ah = al = NULL;
2988
Tim Peters0973b992004-08-29 22:16:50 +00002989 if (a == b) {
2990 t2 = t1;
2991 Py_INCREF(t2);
2992 }
2993 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002994 Py_DECREF(t1);
2995 goto fail;
2996 }
2997 Py_DECREF(bh);
2998 Py_DECREF(bl);
2999 bh = bl = NULL;
3000
Tim Peters738eda72002-08-12 15:08:20 +00003001 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003002 Py_DECREF(t1);
3003 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003004 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00003005 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003006
Tim Petersd6974a52002-08-13 20:37:51 +00003007 /* Add t3. It's not obvious why we can't run out of room here.
3008 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00003009 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003010 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00003011 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003012
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013 return long_normalize(ret);
3014
3015 fail:
3016 Py_XDECREF(ret);
3017 Py_XDECREF(ah);
3018 Py_XDECREF(al);
3019 Py_XDECREF(bh);
3020 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003021 return NULL;
3022}
3023
Tim Petersd6974a52002-08-13 20:37:51 +00003024/* (*) Why adding t3 can't "run out of room" above.
3025
Tim Petersab86c2b2002-08-15 20:06:00 +00003026Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3027to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003028
Tim Petersab86c2b2002-08-15 20:06:00 +000030291. For any integer i, i = c(i/2) + f(i/2). In particular,
3030 bsize = c(bsize/2) + f(bsize/2).
30312. shift = f(bsize/2)
30323. asize <= bsize
30334. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3034 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003035
Tim Petersab86c2b2002-08-15 20:06:00 +00003036We allocated asize + bsize result digits, and add t3 into them at an offset
3037of shift. This leaves asize+bsize-shift allocated digit positions for t3
3038to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3039asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003040
Tim Petersab86c2b2002-08-15 20:06:00 +00003041bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3042at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003043
Tim Petersab86c2b2002-08-15 20:06:00 +00003044If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3045digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3046most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003047
Tim Petersab86c2b2002-08-15 20:06:00 +00003048The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003049
Tim Petersab86c2b2002-08-15 20:06:00 +00003050 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003051
Tim Petersab86c2b2002-08-15 20:06:00 +00003052and we have asize + c(bsize/2) available digit positions. We need to show
3053this is always enough. An instance of c(bsize/2) cancels out in both, so
3054the question reduces to whether asize digits is enough to hold
3055(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3056then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3057asize 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 +00003058digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003059asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003060c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3061is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3062bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003063
Tim Peters48d52c02002-08-14 17:07:32 +00003064Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3065clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3066ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003067*/
3068
Tim Peters60004642002-08-12 22:01:34 +00003069/* b has at least twice the digits of a, and a is big enough that Karatsuba
3070 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3071 * of slices, each with a->ob_size digits, and multiply the slices by a,
3072 * one at a time. This gives k_mul balanced inputs to work with, and is
3073 * also cache-friendly (we compute one double-width slice of the result
3074 * at a time, then move on, never bactracking except for the helpful
3075 * single-width slice overlap between successive partial sums).
3076 */
3077static PyLongObject *
3078k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3079{
Christian Heimes90aa7642007-12-19 02:45:37 +00003080 const Py_ssize_t asize = ABS(Py_SIZE(a));
3081 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00003082 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00003083 PyLongObject *ret;
3084 PyLongObject *bslice = NULL;
3085
3086 assert(asize > KARATSUBA_CUTOFF);
3087 assert(2 * asize <= bsize);
3088
3089 /* Allocate result space, and zero it out. */
3090 ret = _PyLong_New(asize + bsize);
3091 if (ret == NULL)
3092 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003093 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003094
3095 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00003096 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00003097 if (bslice == NULL)
3098 goto fail;
3099
3100 nbdone = 0;
3101 while (bsize > 0) {
3102 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003103 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003104
3105 /* Multiply the next slice of b by a. */
3106 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3107 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00003108 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00003109 product = k_mul(a, bslice);
3110 if (product == NULL)
3111 goto fail;
3112
3113 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003114 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3115 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00003116 Py_DECREF(product);
3117
3118 bsize -= nbtouse;
3119 nbdone += nbtouse;
3120 }
3121
3122 Py_DECREF(bslice);
3123 return long_normalize(ret);
3124
3125 fail:
3126 Py_DECREF(ret);
3127 Py_XDECREF(bslice);
3128 return NULL;
3129}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003130
3131static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003132long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003133{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003134 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003135
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003136 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003137
Mark Dickinsonbd792642009-03-18 20:06:12 +00003138 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00003139 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00003140 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
3141#ifdef HAVE_LONG_LONG
3142 return PyLong_FromLongLong((PY_LONG_LONG)v);
3143#else
3144 /* if we don't have long long then we're almost certainly
3145 using 15-bit digits, so v will fit in a long. In the
3146 unlikely event that we're using 30-bit digits on a platform
3147 without long long, a large v will just cause us to fall
3148 through to the general multiplication code below. */
3149 if (v >= LONG_MIN && v <= LONG_MAX)
3150 return PyLong_FromLong((long)v);
3151#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00003152 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003153
Tim Petersd64c1de2002-08-12 17:36:03 +00003154 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00003155 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003156 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003157 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00003158 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003159}
3160
Guido van Rossume32e0141992-01-19 16:31:05 +00003161/* The / and % operators are now defined in terms of divmod().
3162 The expression a mod b has the value a - b*floor(a/b).
3163 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003164 |a| by |b|, with the sign of a. This is also expressed
3165 as a - b*trunc(a/b), if trunc truncates towards zero.
3166 Some examples:
3167 a b a rem b a mod b
3168 13 10 3 3
3169 -13 10 -3 7
3170 13 -10 3 -7
3171 -13 -10 -3 -3
3172 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003173 have different signs. We then subtract one from the 'div'
3174 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003175
Tim Peters47e52ee2004-08-30 02:44:38 +00003176/* Compute
3177 * *pdiv, *pmod = divmod(v, w)
3178 * NULL can be passed for pdiv or pmod, in which case that part of
3179 * the result is simply thrown away. The caller owns a reference to
3180 * each of these it requests (does not pass NULL for).
3181 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003182static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003183l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00003184 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003185{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003186 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003187
Guido van Rossume32e0141992-01-19 16:31:05 +00003188 if (long_divrem(v, w, &div, &mod) < 0)
3189 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00003190 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3191 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003192 PyLongObject *temp;
3193 PyLongObject *one;
3194 temp = (PyLongObject *) long_add(mod, w);
3195 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003196 mod = temp;
3197 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003198 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003199 return -1;
3200 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003201 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003202 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003203 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3204 Py_DECREF(mod);
3205 Py_DECREF(div);
3206 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003207 return -1;
3208 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003209 Py_DECREF(one);
3210 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003211 div = temp;
3212 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003213 if (pdiv != NULL)
3214 *pdiv = div;
3215 else
3216 Py_DECREF(div);
3217
3218 if (pmod != NULL)
3219 *pmod = mod;
3220 else
3221 Py_DECREF(mod);
3222
Guido van Rossume32e0141992-01-19 16:31:05 +00003223 return 0;
3224}
3225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003226static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003227long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003228{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003229 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003230
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003231 CHECK_BINOP(a, b);
3232 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003233 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003234 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003235}
3236
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003237/* PyLong/PyLong -> float, with correctly rounded result. */
3238
3239#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3240#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003242static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003243long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003244{
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003245 PyLongObject *a, *b, *x;
3246 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3247 digit mask, low;
3248 int inexact, negate, a_is_small, b_is_small;
3249 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003250
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003251 CHECK_BINOP(v, w);
3252 a = (PyLongObject *)v;
3253 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003254
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003255 /*
3256 Method in a nutshell:
3257
3258 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3259 1. choose a suitable integer 'shift'
3260 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3261 3. adjust x for correct rounding
3262 4. convert x to a double dx with the same value
3263 5. return ldexp(dx, shift).
3264
3265 In more detail:
3266
3267 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3268 returns either 0.0 or -0.0, depending on the sign of b. For a and
3269 b both nonzero, ignore signs of a and b, and add the sign back in
3270 at the end. Now write a_bits and b_bits for the bit lengths of a
3271 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3272 for b). Then
3273
3274 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
3275
3276 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3277 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3278 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3279 the way, we can assume that
3280
3281 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
3282
3283 1. The integer 'shift' is chosen so that x has the right number of
3284 bits for a double, plus two or three extra bits that will be used
3285 in the rounding decisions. Writing a_bits and b_bits for the
3286 number of significant bits in a and b respectively, a
3287 straightforward formula for shift is:
3288
3289 shift = a_bits - b_bits - DBL_MANT_DIG - 2
3290
3291 This is fine in the usual case, but if a/b is smaller than the
3292 smallest normal float then it can lead to double rounding on an
3293 IEEE 754 platform, giving incorrectly rounded results. So we
3294 adjust the formula slightly. The actual formula used is:
3295
3296 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
3297
3298 2. The quantity x is computed by first shifting a (left -shift bits
3299 if shift <= 0, right shift bits if shift > 0) and then dividing by
3300 b. For both the shift and the division, we keep track of whether
3301 the result is inexact, in a flag 'inexact'; this information is
3302 needed at the rounding stage.
3303
3304 With the choice of shift above, together with our assumption that
3305 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3306 that x >= 1.
3307
3308 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3309 this with an exactly representable float of the form
3310
3311 round(x/2**extra_bits) * 2**(extra_bits+shift).
3312
3313 For float representability, we need x/2**extra_bits <
3314 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3315 DBL_MANT_DIG. This translates to the condition:
3316
3317 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
3318
3319 To round, we just modify the bottom digit of x in-place; this can
3320 end up giving a digit with value > PyLONG_MASK, but that's not a
3321 problem since digits can hold values up to 2*PyLONG_MASK+1.
3322
3323 With the original choices for shift above, extra_bits will always
3324 be 2 or 3. Then rounding under the round-half-to-even rule, we
3325 round up iff the most significant of the extra bits is 1, and
3326 either: (a) the computation of x in step 2 had an inexact result,
3327 or (b) at least one other of the extra bits is 1, or (c) the least
3328 significant bit of x (above those to be rounded) is 1.
3329
3330 4. Conversion to a double is straightforward; all floating-point
3331 operations involved in the conversion are exact, so there's no
3332 danger of rounding errors.
3333
3334 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3335 The result will always be exactly representable as a double, except
3336 in the case that it overflows. To avoid dependence on the exact
3337 behaviour of ldexp on overflow, we check for overflow before
3338 applying ldexp. The result of ldexp is adjusted for sign before
3339 returning.
3340 */
3341
3342 /* Reduce to case where a and b are both positive. */
3343 a_size = ABS(Py_SIZE(a));
3344 b_size = ABS(Py_SIZE(b));
3345 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3346 if (b_size == 0) {
Tim Peterse2a60002001-09-04 06:17:36 +00003347 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003348 "division by zero");
3349 goto error;
3350 }
3351 if (a_size == 0)
3352 goto underflow_or_zero;
3353
3354 /* Fast path for a and b small (exactly representable in a double).
3355 Relies on floating-point division being correctly rounded; results
3356 may be subject to double rounding on x86 machines that operate with
3357 the x87 FPU set to 64-bit precision. */
3358 a_is_small = a_size <= MANT_DIG_DIGITS ||
3359 (a_size == MANT_DIG_DIGITS+1 &&
3360 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3361 b_is_small = b_size <= MANT_DIG_DIGITS ||
3362 (b_size == MANT_DIG_DIGITS+1 &&
3363 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3364 if (a_is_small && b_is_small) {
3365 double da, db;
3366 da = a->ob_digit[--a_size];
3367 while (a_size > 0)
3368 da = da * PyLong_BASE + a->ob_digit[--a_size];
3369 db = b->ob_digit[--b_size];
3370 while (b_size > 0)
3371 db = db * PyLong_BASE + b->ob_digit[--b_size];
3372 result = da / db;
3373 goto success;
Tim Peterse2a60002001-09-04 06:17:36 +00003374 }
3375
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003376 /* Catch obvious cases of underflow and overflow */
3377 diff = a_size - b_size;
3378 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3379 /* Extreme overflow */
Tim Peterse2a60002001-09-04 06:17:36 +00003380 goto overflow;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003381 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3382 /* Extreme underflow */
3383 goto underflow_or_zero;
3384 /* Next line is now safe from overflowing a Py_ssize_t */
3385 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3386 bits_in_digit(b->ob_digit[b_size - 1]);
3387 /* Now diff = a_bits - b_bits. */
3388 if (diff > DBL_MAX_EXP)
Tim Peterse2a60002001-09-04 06:17:36 +00003389 goto overflow;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003390 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3391 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003392
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003393 /* Choose value for shift; see comments for step 1 above. */
3394 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
3395
3396 inexact = 0;
3397
3398 /* x = abs(a * 2**-shift) */
3399 if (shift <= 0) {
3400 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3401 digit rem;
3402 /* x = a << -shift */
3403 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3404 /* In practice, it's probably impossible to end up
3405 here. Both a and b would have to be enormous,
3406 using close to SIZE_T_MAX bytes of memory each. */
3407 PyErr_SetString(PyExc_OverflowError,
3408 "intermediate overflow during division");
3409 goto error;
3410 }
3411 x = _PyLong_New(a_size + shift_digits + 1);
3412 if (x == NULL)
3413 goto error;
3414 for (i = 0; i < shift_digits; i++)
3415 x->ob_digit[i] = 0;
3416 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3417 a_size, -shift % PyLong_SHIFT);
3418 x->ob_digit[a_size + shift_digits] = rem;
3419 }
3420 else {
3421 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3422 digit rem;
3423 /* x = a >> shift */
3424 assert(a_size >= shift_digits);
3425 x = _PyLong_New(a_size - shift_digits);
3426 if (x == NULL)
3427 goto error;
3428 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3429 a_size - shift_digits, shift % PyLong_SHIFT);
3430 /* set inexact if any of the bits shifted out is nonzero */
3431 if (rem)
3432 inexact = 1;
3433 while (!inexact && shift_digits > 0)
3434 if (a->ob_digit[--shift_digits])
3435 inexact = 1;
3436 }
3437 long_normalize(x);
3438 x_size = Py_SIZE(x);
3439
3440 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3441 reference to x, so it's safe to modify it in-place. */
3442 if (b_size == 1) {
3443 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3444 b->ob_digit[0]);
3445 long_normalize(x);
3446 if (rem)
3447 inexact = 1;
3448 }
3449 else {
3450 PyLongObject *div, *rem;
3451 div = x_divrem(x, b, &rem);
3452 Py_DECREF(x);
3453 x = div;
3454 if (x == NULL)
3455 goto error;
3456 if (Py_SIZE(rem))
3457 inexact = 1;
3458 Py_DECREF(rem);
3459 }
3460 x_size = ABS(Py_SIZE(x));
3461 assert(x_size > 0); /* result of division is never zero */
3462 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
3463
3464 /* The number of extra bits that have to be rounded away. */
3465 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3466 assert(extra_bits == 2 || extra_bits == 3);
3467
3468 /* Round by directly modifying the low digit of x. */
3469 mask = (digit)1 << (extra_bits - 1);
3470 low = x->ob_digit[0] | inexact;
3471 if (low & mask && low & (3*mask-1))
3472 low += mask;
3473 x->ob_digit[0] = low & ~(mask-1U);
3474
3475 /* Convert x to a double dx; the conversion is exact. */
3476 dx = x->ob_digit[--x_size];
3477 while (x_size > 0)
3478 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3479 Py_DECREF(x);
3480
3481 /* Check whether ldexp result will overflow a double. */
3482 if (shift + x_bits >= DBL_MAX_EXP &&
3483 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, x_bits)))
3484 goto overflow;
3485 result = ldexp(dx, shift);
3486
3487 success:
3488 return PyFloat_FromDouble(negate ? -result : result);
3489
3490 underflow_or_zero:
3491 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
3492
3493 overflow:
Tim Peterse2a60002001-09-04 06:17:36 +00003494 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003495 "integer division result too large for a float");
3496 error:
Tim Peterse2a60002001-09-04 06:17:36 +00003497 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003498}
3499
3500static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003501long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003502{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003503 PyLongObject *mod;
3504
3505 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003506
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003507 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003508 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003509 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003510}
3511
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003512static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003513long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003514{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003515 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003516 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003517
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003518 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003519
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003520 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003521 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003522 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003523 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003524 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003525 PyTuple_SetItem(z, 0, (PyObject *) div);
3526 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003527 }
3528 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003529 Py_DECREF(div);
3530 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003531 }
3532 return z;
3533}
3534
Tim Peters47e52ee2004-08-30 02:44:38 +00003535/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003536static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003537long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003538{
Tim Peters47e52ee2004-08-30 02:44:38 +00003539 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3540 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003541
Tim Peters47e52ee2004-08-30 02:44:38 +00003542 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003543 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003544 PyLongObject *temp = NULL;
3545
3546 /* 5-ary values. If the exponent is large enough, table is
3547 * precomputed so that table[i] == a**i % c for i in range(32).
3548 */
3549 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3550 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3551
3552 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003553 CHECK_BINOP(v, w);
3554 a = (PyLongObject*)v; Py_INCREF(a);
3555 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003556 if (PyLong_Check(x)) {
3557 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003558 Py_INCREF(x);
3559 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003560 else if (x == Py_None)
3561 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003562 else {
3563 Py_DECREF(a);
3564 Py_DECREF(b);
3565 Py_INCREF(Py_NotImplemented);
3566 return Py_NotImplemented;
3567 }
Tim Peters4c483c42001-09-05 06:24:58 +00003568
Christian Heimes90aa7642007-12-19 02:45:37 +00003569 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003570 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003571 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003572 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003573 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003574 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003575 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003576 /* else return a float. This works because we know
3577 that this calls float_pow() which converts its
3578 arguments to double. */
3579 Py_DECREF(a);
3580 Py_DECREF(b);
3581 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003582 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003583 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003584
3585 if (c) {
3586 /* if modulus == 0:
3587 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003588 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003589 PyErr_SetString(PyExc_ValueError,
3590 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003591 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003592 }
3593
3594 /* if modulus < 0:
3595 negativeOutput = True
3596 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003597 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003598 negativeOutput = 1;
3599 temp = (PyLongObject *)_PyLong_Copy(c);
3600 if (temp == NULL)
3601 goto Error;
3602 Py_DECREF(c);
3603 c = temp;
3604 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003605 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003606 }
3607
3608 /* if modulus == 1:
3609 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003610 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003611 z = (PyLongObject *)PyLong_FromLong(0L);
3612 goto Done;
3613 }
3614
3615 /* if base < 0:
3616 base = base % modulus
3617 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003618 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003619 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003620 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003621 Py_DECREF(a);
3622 a = temp;
3623 temp = NULL;
3624 }
3625 }
3626
3627 /* At this point a, b, and c are guaranteed non-negative UNLESS
3628 c is NULL, in which case a may be negative. */
3629
3630 z = (PyLongObject *)PyLong_FromLong(1L);
3631 if (z == NULL)
3632 goto Error;
3633
3634 /* Perform a modular reduction, X = X % c, but leave X alone if c
3635 * is NULL.
3636 */
3637#define REDUCE(X) \
3638 if (c != NULL) { \
3639 if (l_divmod(X, c, NULL, &temp) < 0) \
3640 goto Error; \
3641 Py_XDECREF(X); \
3642 X = temp; \
3643 temp = NULL; \
3644 }
3645
3646 /* Multiply two values, then reduce the result:
3647 result = X*Y % c. If c is NULL, skip the mod. */
3648#define MULT(X, Y, result) \
3649{ \
3650 temp = (PyLongObject *)long_mul(X, Y); \
3651 if (temp == NULL) \
3652 goto Error; \
3653 Py_XDECREF(result); \
3654 result = temp; \
3655 temp = NULL; \
3656 REDUCE(result) \
3657}
3658
Christian Heimes90aa7642007-12-19 02:45:37 +00003659 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003660 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3661 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003662 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003663 digit bi = b->ob_digit[i];
3664
Mark Dickinsone4416742009-02-15 15:14:57 +00003665 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003666 MULT(z, z, z)
3667 if (bi & j)
3668 MULT(z, a, z)
3669 }
3670 }
3671 }
3672 else {
3673 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3674 Py_INCREF(z); /* still holds 1L */
3675 table[0] = z;
3676 for (i = 1; i < 32; ++i)
3677 MULT(table[i-1], a, table[i])
3678
Christian Heimes90aa7642007-12-19 02:45:37 +00003679 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003680 const digit bi = b->ob_digit[i];
3681
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003682 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003683 const int index = (bi >> j) & 0x1f;
3684 for (k = 0; k < 5; ++k)
3685 MULT(z, z, z)
3686 if (index)
3687 MULT(z, table[index], z)
3688 }
3689 }
3690 }
3691
Christian Heimes90aa7642007-12-19 02:45:37 +00003692 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003693 temp = (PyLongObject *)long_sub(z, c);
3694 if (temp == NULL)
3695 goto Error;
3696 Py_DECREF(z);
3697 z = temp;
3698 temp = NULL;
3699 }
3700 goto Done;
3701
3702 Error:
3703 if (z != NULL) {
3704 Py_DECREF(z);
3705 z = NULL;
3706 }
3707 /* fall through */
3708 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003709 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003710 for (i = 0; i < 32; ++i)
3711 Py_XDECREF(table[i]);
3712 }
Tim Petersde7990b2005-07-17 23:45:23 +00003713 Py_DECREF(a);
3714 Py_DECREF(b);
3715 Py_XDECREF(c);
3716 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003717 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003718}
3719
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003720static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003721long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003722{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003723 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003724 PyLongObject *x;
3725 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003726 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003727 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003728 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003729 if (w == NULL)
3730 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003731 x = (PyLongObject *) long_add(v, w);
3732 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003733 if (x == NULL)
3734 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003735 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003736 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003737}
3738
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003739static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003740long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003741{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003742 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003743 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003744 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003745 z = (PyLongObject *)_PyLong_Copy(v);
3746 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003747 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003748 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003749}
3750
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003751static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003752long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003753{
Christian Heimes90aa7642007-12-19 02:45:37 +00003754 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003755 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003756 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003757 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003758}
3759
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003760static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003761long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003762{
Christian Heimes90aa7642007-12-19 02:45:37 +00003763 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003764}
3765
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003766static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003767long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003768{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003769 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003770 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003771 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003772 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003773
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003774 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003775
Christian Heimes90aa7642007-12-19 02:45:37 +00003776 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003777 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003778 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003779 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003780 if (a1 == NULL)
3781 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003782 a2 = (PyLongObject *) long_rshift(a1, b);
3783 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003784 if (a2 == NULL)
3785 goto rshift_error;
3786 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003787 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003788 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003789 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003790
Neil Schemenauerba872e22001-01-04 01:46:03 +00003791 shiftby = PyLong_AsLong((PyObject *)b);
3792 if (shiftby == -1L && PyErr_Occurred())
3793 goto rshift_error;
3794 if (shiftby < 0) {
3795 PyErr_SetString(PyExc_ValueError,
3796 "negative shift count");
3797 goto rshift_error;
3798 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003799 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003800 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003801 if (newsize <= 0)
3802 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003803 loshift = shiftby % PyLong_SHIFT;
3804 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003805 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003806 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003807 z = _PyLong_New(newsize);
3808 if (z == NULL)
3809 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003810 if (Py_SIZE(a) < 0)
3811 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003812 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3813 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3814 if (i+1 < newsize)
3815 z->ob_digit[i] |=
3816 (a->ob_digit[j+1] << hishift) & himask;
3817 }
3818 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003819 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003820rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003821 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003822
Guido van Rossumc6913e71991-11-19 20:26:46 +00003823}
3824
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003825static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003826long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003827{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003828 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003829 PyLongObject *a = (PyLongObject*)v;
3830 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003831 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003832 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003833 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003834 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003835
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003836 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003837
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003838 shiftby = PyLong_AsLong((PyObject *)b);
3839 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003840 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003841 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003842 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003843 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003844 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003845 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003846 PyErr_SetString(PyExc_ValueError,
3847 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003848 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003849 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003850 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3851 wordshift = (int)shiftby / PyLong_SHIFT;
3852 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003853
Christian Heimes90aa7642007-12-19 02:45:37 +00003854 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003855 newsize = oldsize + wordshift;
3856 if (remshift)
3857 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003858 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003859 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003860 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003861 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003862 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003863 for (i = 0; i < wordshift; i++)
3864 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003865 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003866 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003867 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003868 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3869 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003870 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003871 if (remshift)
3872 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003873 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003874 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003875 z = long_normalize(z);
3876lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003877 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003878}
3879
Mark Dickinson27a87a22009-10-25 20:43:34 +00003880/* Compute two's complement of digit vector a[0:m], writing result to
3881 z[0:m]. The digit vector a need not be normalized, but should not
3882 be entirely zero. a and z may point to the same digit vector. */
3883
3884static void
3885v_complement(digit *z, digit *a, Py_ssize_t m)
3886{
3887 Py_ssize_t i;
3888 digit carry = 1;
3889 for (i = 0; i < m; ++i) {
3890 carry += a[i] ^ PyLong_MASK;
3891 z[i] = carry & PyLong_MASK;
3892 carry >>= PyLong_SHIFT;
3893 }
3894 assert(carry == 0);
3895}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003896
3897/* Bitwise and/xor/or operations */
3898
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003899static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003900long_bitwise(PyLongObject *a,
3901 int op, /* '&', '|', '^' */
3902 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003903{
Mark Dickinson27a87a22009-10-25 20:43:34 +00003904 int nega, negb, negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003905 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003906 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003907
Mark Dickinson27a87a22009-10-25 20:43:34 +00003908 /* Bitwise operations for negative numbers operate as though
3909 on a two's complement representation. So convert arguments
3910 from sign-magnitude to two's complement, and convert the
3911 result back to sign-magnitude at the end. */
3912
3913 /* If a is negative, replace it by its two's complement. */
3914 size_a = ABS(Py_SIZE(a));
3915 nega = Py_SIZE(a) < 0;
3916 if (nega) {
3917 z = _PyLong_New(size_a);
3918 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003919 return NULL;
Mark Dickinson27a87a22009-10-25 20:43:34 +00003920 v_complement(z->ob_digit, a->ob_digit, size_a);
3921 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003922 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003923 else
3924 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003925 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003926
3927 /* Same for b. */
3928 size_b = ABS(Py_SIZE(b));
3929 negb = Py_SIZE(b) < 0;
3930 if (negb) {
3931 z = _PyLong_New(size_b);
3932 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003933 Py_DECREF(a);
3934 return NULL;
3935 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003936 v_complement(z->ob_digit, b->ob_digit, size_b);
3937 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003938 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003939 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003940 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003941
Mark Dickinson27a87a22009-10-25 20:43:34 +00003942 /* Swap a and b if necessary to ensure size_a >= size_b. */
3943 if (size_a < size_b) {
3944 z = a; a = b; b = z;
3945 size_z = size_a; size_a = size_b; size_b = size_z;
3946 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003947 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003948
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003949 /* JRH: The original logic here was to allocate the result value (z)
3950 as the longer of the two operands. However, there are some cases
3951 where the result is guaranteed to be shorter than that: AND of two
3952 positives, OR of two negatives: use the shorter number. AND with
3953 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson27a87a22009-10-25 20:43:34 +00003954 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003955 */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003956 switch (op) {
3957 case '^':
3958 negz = nega ^ negb;
3959 size_z = size_a;
3960 break;
3961 case '&':
3962 negz = nega & negb;
3963 size_z = negb ? size_a : size_b;
3964 break;
3965 case '|':
3966 negz = nega | negb;
3967 size_z = negb ? size_b : size_a;
3968 break;
3969 default:
3970 PyErr_BadArgument();
3971 return NULL;
3972 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003973
Mark Dickinson27a87a22009-10-25 20:43:34 +00003974 /* We allow an extra digit if z is negative, to make sure that
3975 the final two's complement of z doesn't overflow. */
3976 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003977 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003978 Py_DECREF(a);
3979 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003980 return NULL;
3981 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003982
Mark Dickinson27a87a22009-10-25 20:43:34 +00003983 /* Compute digits for overlap of a and b. */
3984 switch(op) {
3985 case '&':
3986 for (i = 0; i < size_b; ++i)
3987 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3988 break;
3989 case '|':
3990 for (i = 0; i < size_b; ++i)
3991 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3992 break;
3993 case '^':
3994 for (i = 0; i < size_b; ++i)
3995 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3996 break;
3997 default:
3998 PyErr_BadArgument();
3999 return NULL;
4000 }
4001
4002 /* Copy any remaining digits of a, inverting if necessary. */
4003 if (op == '^' && negb)
4004 for (; i < size_z; ++i)
4005 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4006 else if (i < size_z)
4007 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4008 (size_z-i)*sizeof(digit));
4009
4010 /* Complement result if negative. */
4011 if (negz) {
4012 Py_SIZE(z) = -(Py_SIZE(z));
4013 z->ob_digit[size_z] = PyLong_MASK;
4014 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00004015 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004017 Py_DECREF(a);
4018 Py_DECREF(b);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004019 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004020}
4021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004022static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004023long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004024{
Neil Schemenauerba872e22001-01-04 01:46:03 +00004025 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004026 CHECK_BINOP(a, b);
4027 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004028 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004029}
4030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004031static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004032long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004033{
Neil Schemenauerba872e22001-01-04 01:46:03 +00004034 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004035 CHECK_BINOP(a, b);
4036 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004037 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004038}
4039
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004040static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004041long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004042{
Neil Schemenauerba872e22001-01-04 01:46:03 +00004043 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004044 CHECK_BINOP(a, b);
4045 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004046 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004047}
4048
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004049static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004050long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004051{
Brett Cannonc3647ac2005-04-26 03:45:26 +00004052 if (PyLong_CheckExact(v))
4053 Py_INCREF(v);
4054 else
4055 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004056 return v;
4057}
4058
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004059static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004060long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004061{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00004062 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004063 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00004064 if (result == -1.0 && PyErr_Occurred())
4065 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004066 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004067}
4068
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004069static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004070long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004071
Tim Peters6d6c1a32001-08-02 04:15:00 +00004072static PyObject *
4073long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4074{
4075 PyObject *x = NULL;
4076 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00004077 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004078
Guido van Rossumbef14172001-08-29 15:47:46 +00004079 if (type != &PyLong_Type)
4080 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004081 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00004082 &x, &base))
4083 return NULL;
4084 if (x == NULL)
4085 return PyLong_FromLong(0L);
4086 if (base == -909)
4087 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004088 else if (PyUnicode_Check(x))
4089 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4090 PyUnicode_GET_SIZE(x),
4091 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00004092 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00004093 /* Since PyLong_FromString doesn't have a length parameter,
4094 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00004095 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004096 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00004097 if (PyByteArray_Check(x))
4098 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004099 else
Christian Heimes72b710a2008-05-26 13:28:38 +00004100 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004101 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00004102 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00004103 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00004104 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00004105 "invalid literal for int() with base %d: %R",
4106 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004107 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004108 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00004109 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004110 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004111 else {
4112 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004113 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004114 return NULL;
4115 }
4116}
4117
Guido van Rossumbef14172001-08-29 15:47:46 +00004118/* Wimpy, slow approach to tp_new calls for subtypes of long:
4119 first create a regular long from whatever arguments we got,
4120 then allocate a subtype instance and initialize it from
4121 the regular long. The regular long is then thrown away.
4122*/
4123static PyObject *
4124long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4125{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004126 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004127 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004128
4129 assert(PyType_IsSubtype(type, &PyLong_Type));
4130 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4131 if (tmp == NULL)
4132 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00004133 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00004134 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004135 if (n < 0)
4136 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004137 newobj = (PyLongObject *)type->tp_alloc(type, n);
4138 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00004139 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004140 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00004141 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004142 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00004143 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004144 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004145 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00004146 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004147 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004148}
4149
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004150static PyObject *
4151long_getnewargs(PyLongObject *v)
4152{
4153 return Py_BuildValue("(N)", _PyLong_Copy(v));
4154}
4155
Guido van Rossumb43daf72007-08-01 18:08:08 +00004156static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004157long_get0(PyLongObject *v, void *context) {
4158 return PyLong_FromLong(0L);
4159}
4160
4161static PyObject *
4162long_get1(PyLongObject *v, void *context) {
4163 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004164}
4165
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004166static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004167long__format__(PyObject *self, PyObject *args)
4168{
Eric Smith4a7d76d2008-05-30 18:10:19 +00004169 PyObject *format_spec;
4170
4171 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4172 return NULL;
4173 return _PyLong_FormatAdvanced(self,
4174 PyUnicode_AS_UNICODE(format_spec),
4175 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004176}
4177
Eric Smith8c663262007-08-25 02:26:07 +00004178static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004179long_round(PyObject *self, PyObject *args)
4180{
Mark Dickinson1124e712009-01-28 21:25:58 +00004181 PyObject *o_ndigits=NULL, *temp;
4182 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
4183 int errcode;
4184 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004185
Mark Dickinson1124e712009-01-28 21:25:58 +00004186 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
4187 the straightforward method is:
4188
4189 (1) divide by 10**n
4190 (2) round to nearest integer (round to even in case of tie)
4191 (3) multiply result by 10**n.
4192
4193 But the rounding step involves examining the fractional part of the
4194 quotient to see whether it's greater than 0.5 or not. Since we
4195 want to do the whole calculation in integer arithmetic, it's
4196 simpler to do:
4197
4198 (1) divide by (10**n)/2
4199 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
4200 (3) multiply result by (10**n)/2.
4201
4202 Then all we need to know about the fractional part of the quotient
4203 arising in step (2) is whether it's zero or not.
4204
4205 Doing both a multiplication and division is wasteful, and is easily
4206 avoided if we just figure out how much to adjust the original input
4207 by to do the rounding.
4208
4209 Here's the whole algorithm expressed in Python.
4210
4211 def round(self, ndigits = None):
4212 """round(int, int) -> int"""
4213 if ndigits is None or ndigits >= 0:
4214 return self
4215 pow = 10**-ndigits >> 1
4216 q, r = divmod(self, pow)
4217 self -= r
4218 if (q & 1 != 0):
4219 if (q & 2 == r == 0):
4220 self -= pow
4221 else:
4222 self += pow
4223 return self
4224
4225 */
4226 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4227 return NULL;
4228 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004229 return long_long(self);
4230
Mark Dickinson1124e712009-01-28 21:25:58 +00004231 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
4232 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004233 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004234
4235 if (Py_SIZE(ndigits) >= 0) {
4236 Py_DECREF(ndigits);
4237 return long_long(self);
4238 }
4239
4240 Py_INCREF(self); /* to keep refcounting simple */
4241 /* we now own references to self, ndigits */
4242
4243 /* pow = 10 ** -ndigits >> 1 */
4244 pow = (PyLongObject *)PyLong_FromLong(10L);
4245 if (pow == NULL)
4246 goto error;
4247 temp = long_neg(ndigits);
4248 Py_DECREF(ndigits);
4249 ndigits = (PyLongObject *)temp;
4250 if (ndigits == NULL)
4251 goto error;
4252 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4253 Py_DECREF(pow);
4254 pow = (PyLongObject *)temp;
4255 if (pow == NULL)
4256 goto error;
4257 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4258 one = (PyLongObject *)PyLong_FromLong(1L);
4259 if (one == NULL)
4260 goto error;
4261 temp = long_rshift(pow, one);
4262 Py_DECREF(one);
4263 Py_DECREF(pow);
4264 pow = (PyLongObject *)temp;
4265 if (pow == NULL)
4266 goto error;
4267
4268 /* q, r = divmod(self, pow) */
4269 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4270 if (errcode == -1)
4271 goto error;
4272
4273 /* self -= r */
4274 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004275 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00004276 self = temp;
4277 if (self == NULL)
4278 goto error;
4279
4280 /* get value of quotient modulo 4 */
4281 if (Py_SIZE(q) == 0)
4282 q_mod_4 = 0;
4283 else if (Py_SIZE(q) > 0)
4284 q_mod_4 = q->ob_digit[0] & 3;
4285 else
4286 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
4287
4288 if ((q_mod_4 & 1) == 1) {
4289 /* q is odd; round self up or down by adding or subtracting pow */
4290 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4291 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4292 else
4293 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4294 Py_DECREF(self);
4295 self = temp;
4296 if (self == NULL)
4297 goto error;
4298 }
4299 Py_DECREF(q);
4300 Py_DECREF(r);
4301 Py_DECREF(pow);
4302 Py_DECREF(ndigits);
4303 return self;
4304
4305 error:
4306 Py_XDECREF(q);
4307 Py_XDECREF(r);
4308 Py_XDECREF(pow);
4309 Py_XDECREF(self);
4310 Py_XDECREF(ndigits);
4311 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004312}
4313
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004314static PyObject *
4315long_sizeof(PyLongObject *v)
4316{
4317 Py_ssize_t res;
4318
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004319 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004320 return PyLong_FromSsize_t(res);
4321}
4322
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004323static PyObject *
4324long_bit_length(PyLongObject *v)
4325{
4326 PyLongObject *result, *x, *y;
4327 Py_ssize_t ndigits, msd_bits = 0;
4328 digit msd;
4329
4330 assert(v != NULL);
4331 assert(PyLong_Check(v));
4332
4333 ndigits = ABS(Py_SIZE(v));
4334 if (ndigits == 0)
4335 return PyLong_FromLong(0);
4336
4337 msd = v->ob_digit[ndigits-1];
4338 while (msd >= 32) {
4339 msd_bits += 6;
4340 msd >>= 6;
4341 }
4342 msd_bits += (long)(BitLengthTable[msd]);
4343
4344 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4345 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4346
4347 /* expression above may overflow; use Python integers instead */
4348 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4349 if (result == NULL)
4350 return NULL;
4351 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4352 if (x == NULL)
4353 goto error;
4354 y = (PyLongObject *)long_mul(result, x);
4355 Py_DECREF(x);
4356 if (y == NULL)
4357 goto error;
4358 Py_DECREF(result);
4359 result = y;
4360
4361 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4362 if (x == NULL)
4363 goto error;
4364 y = (PyLongObject *)long_add(result, x);
4365 Py_DECREF(x);
4366 if (y == NULL)
4367 goto error;
4368 Py_DECREF(result);
4369 result = y;
4370
4371 return (PyObject *)result;
4372
4373error:
4374 Py_DECREF(result);
4375 return NULL;
4376}
4377
4378PyDoc_STRVAR(long_bit_length_doc,
4379"int.bit_length() -> int\n\
4380\n\
4381Number of bits necessary to represent self in binary.\n\
4382>>> bin(37)\n\
4383'0b100101'\n\
4384>>> (37).bit_length()\n\
43856");
4386
Christian Heimes53876d92008-04-19 00:31:39 +00004387#if 0
4388static PyObject *
4389long_is_finite(PyObject *v)
4390{
4391 Py_RETURN_TRUE;
4392}
4393#endif
4394
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004395
4396PyDoc_STRVAR(long_to_bytes_doc,
4397"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
4398\n\
4399Return an array of bytes representing an integer.\n\
4400\n\
4401The integer is represented using length bytes. An OverflowError is\n\
4402raised if the integer is not representable with the given number of\n\
4403bytes.\n\
4404\n\
4405The byteorder argument determines the byte order used to represent the\n\
4406integer. If byteorder is 'big', the most significant byte is at the\n\
4407beginning of the byte array. If byteorder is 'little', the most\n\
4408significant byte is at the end of the byte array. To request the native\n\
4409byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4410\n\
4411The signed keyword-only argument determines whether two's complement is\n\
4412used to represent the integer. If signed is False and a negative integer\n\
4413is given, an OverflowError is raised.");
4414
4415static PyObject *
4416long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4417{
4418 PyObject *byteorder_str;
4419 PyObject *is_signed_obj = NULL;
4420 Py_ssize_t length;
4421 int little_endian;
4422 int is_signed;
4423 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004424 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
4425
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004426 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004427 &length, &byteorder_str,
4428 &is_signed_obj))
4429 return NULL;
4430
4431 if (args != NULL && Py_SIZE(args) > 2) {
4432 PyErr_SetString(PyExc_TypeError,
4433 "'signed' is a keyword-only argument");
4434 return NULL;
4435 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004436
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004437 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004438 little_endian = 1;
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004439 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004440 little_endian = 0;
4441 else {
4442 PyErr_SetString(PyExc_ValueError,
4443 "byteorder must be either 'little' or 'big'");
4444 return NULL;
4445 }
4446
4447 if (is_signed_obj != NULL) {
4448 int cmp = PyObject_IsTrue(is_signed_obj);
4449 if (cmp < 0)
4450 return NULL;
4451 is_signed = cmp ? 1 : 0;
4452 }
4453 else {
4454 /* If the signed argument was omitted, use False as the
4455 default. */
4456 is_signed = 0;
4457 }
4458
4459 if (length < 0) {
4460 PyErr_SetString(PyExc_ValueError,
4461 "length argument must be non-negative");
4462 return NULL;
4463 }
4464
4465 bytes = PyBytes_FromStringAndSize(NULL, length);
4466 if (bytes == NULL)
4467 return NULL;
4468
4469 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4470 length, little_endian, is_signed) < 0) {
4471 Py_DECREF(bytes);
4472 return NULL;
4473 }
4474
4475 return bytes;
4476}
4477
4478PyDoc_STRVAR(long_from_bytes_doc,
4479"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4480\n\
4481Return the integer represented by the given array of bytes.\n\
4482\n\
4483The bytes argument must either support the buffer protocol or be an\n\
4484iterable object producing bytes. Bytes and bytearray are examples of\n\
4485built-in objects that support the buffer protocol.\n\
4486\n\
4487The byteorder argument determines the byte order used to represent the\n\
4488integer. If byteorder is 'big', the most significant byte is at the\n\
4489beginning of the byte array. If byteorder is 'little', the most\n\
4490significant byte is at the end of the byte array. To request the native\n\
4491byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4492\n\
4493The signed keyword-only argument indicates whether two's complement is\n\
4494used to represent the integer.");
4495
4496static PyObject *
4497long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4498{
4499 PyObject *byteorder_str;
4500 PyObject *is_signed_obj = NULL;
4501 int little_endian;
4502 int is_signed;
4503 PyObject *obj;
4504 PyObject *bytes;
4505 PyObject *long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004506 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
4507
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004508 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004509 &obj, &byteorder_str,
4510 &is_signed_obj))
4511 return NULL;
4512
4513 if (args != NULL && Py_SIZE(args) > 2) {
4514 PyErr_SetString(PyExc_TypeError,
4515 "'signed' is a keyword-only argument");
4516 return NULL;
4517 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004518
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004519 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004520 little_endian = 1;
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004521 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004522 little_endian = 0;
4523 else {
4524 PyErr_SetString(PyExc_ValueError,
4525 "byteorder must be either 'little' or 'big'");
4526 return NULL;
4527 }
4528
4529 if (is_signed_obj != NULL) {
4530 int cmp = PyObject_IsTrue(is_signed_obj);
4531 if (cmp < 0)
4532 return NULL;
4533 is_signed = cmp ? 1 : 0;
4534 }
4535 else {
4536 /* If the signed argument was omitted, use False as the
4537 default. */
4538 is_signed = 0;
4539 }
4540
4541 bytes = PyObject_Bytes(obj);
4542 if (bytes == NULL)
4543 return NULL;
4544
4545 long_obj = _PyLong_FromByteArray(
4546 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4547 little_endian, is_signed);
4548 Py_DECREF(bytes);
4549
4550 /* If from_bytes() was used on subclass, allocate new subclass
4551 * instance, initialize it with decoded long value and return it.
4552 */
4553 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4554 PyLongObject *newobj;
4555 int i;
4556 Py_ssize_t n = ABS(Py_SIZE(long_obj));
4557
4558 newobj = (PyLongObject *)type->tp_alloc(type, n);
4559 if (newobj == NULL) {
4560 Py_DECREF(long_obj);
4561 return NULL;
4562 }
4563 assert(PyLong_Check(newobj));
4564 Py_SIZE(newobj) = Py_SIZE(long_obj);
4565 for (i = 0; i < n; i++) {
4566 newobj->ob_digit[i] =
4567 ((PyLongObject *)long_obj)->ob_digit[i];
4568 }
4569 Py_DECREF(long_obj);
4570 return (PyObject *)newobj;
4571 }
4572
4573 return long_obj;
4574}
4575
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004576static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00004577 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4578 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004579 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4580 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004581#if 0
4582 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4583 "Returns always True."},
4584#endif
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004585 {"to_bytes", (PyCFunction)long_to_bytes,
4586 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4587 {"from_bytes", (PyCFunction)long_from_bytes,
4588 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004589 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4590 "Truncating an Integral returns itself."},
4591 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4592 "Flooring an Integral returns itself."},
4593 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4594 "Ceiling of an Integral returns itself."},
4595 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00004596 "Rounding an Integral returns itself.\n"
4597 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004598 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00004599 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004600 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4601 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004602 {NULL, NULL} /* sentinel */
4603};
4604
Guido van Rossumb43daf72007-08-01 18:08:08 +00004605static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004606 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004607 (getter)long_long, (setter)NULL,
4608 "the real part of a complex number",
4609 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004610 {"imag",
4611 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004612 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004613 NULL},
4614 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004615 (getter)long_long, (setter)NULL,
4616 "the numerator of a rational number in lowest terms",
4617 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004618 {"denominator",
4619 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004620 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004621 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004622 {NULL} /* Sentinel */
4623};
4624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004625PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004626"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004627\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004628Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004629point argument will be truncated towards zero (this does not include a\n\
4630string representation of a floating point number!) When converting a\n\
4631string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004632converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004633
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004634static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004635 (binaryfunc) long_add, /*nb_add*/
4636 (binaryfunc) long_sub, /*nb_subtract*/
4637 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004638 long_mod, /*nb_remainder*/
4639 long_divmod, /*nb_divmod*/
4640 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004641 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004642 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004643 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00004644 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004645 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004646 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004647 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004648 long_and, /*nb_and*/
4649 long_xor, /*nb_xor*/
4650 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004651 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00004652 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004653 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004654 0, /* nb_inplace_add */
4655 0, /* nb_inplace_subtract */
4656 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00004657 0, /* nb_inplace_remainder */
4658 0, /* nb_inplace_power */
4659 0, /* nb_inplace_lshift */
4660 0, /* nb_inplace_rshift */
4661 0, /* nb_inplace_and */
4662 0, /* nb_inplace_xor */
4663 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004664 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004665 long_true_divide, /* nb_true_divide */
4666 0, /* nb_inplace_floor_divide */
4667 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004668 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004669};
4670
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004671PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004672 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00004673 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004674 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004675 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004676 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004677 0, /* tp_print */
4678 0, /* tp_getattr */
4679 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004680 0, /* tp_reserved */
Mark Dickinson2031d132009-09-17 00:17:48 +00004681 long_to_decimal_string, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004682 &long_as_number, /* tp_as_number */
4683 0, /* tp_as_sequence */
4684 0, /* tp_as_mapping */
4685 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004686 0, /* tp_call */
Mark Dickinson2031d132009-09-17 00:17:48 +00004687 long_to_decimal_string, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004688 PyObject_GenericGetAttr, /* tp_getattro */
4689 0, /* tp_setattro */
4690 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00004691 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4692 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693 long_doc, /* tp_doc */
4694 0, /* tp_traverse */
4695 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004696 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004697 0, /* tp_weaklistoffset */
4698 0, /* tp_iter */
4699 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004700 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004701 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00004702 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004703 0, /* tp_base */
4704 0, /* tp_dict */
4705 0, /* tp_descr_get */
4706 0, /* tp_descr_set */
4707 0, /* tp_dictoffset */
4708 0, /* tp_init */
4709 0, /* tp_alloc */
4710 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004711 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004712};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004713
Mark Dickinsonbd792642009-03-18 20:06:12 +00004714static PyTypeObject Int_InfoType;
4715
4716PyDoc_STRVAR(int_info__doc__,
4717"sys.int_info\n\
4718\n\
4719A struct sequence that holds information about Python's\n\
4720internal representation of integers. The attributes are read only.");
4721
4722static PyStructSequence_Field int_info_fields[] = {
4723 {"bits_per_digit", "size of a digit in bits"},
4724 {"sizeof_digit", "size in bytes of the C type used to "
4725 "represent a digit"},
4726 {NULL, NULL}
4727};
4728
4729static PyStructSequence_Desc int_info_desc = {
4730 "sys.int_info", /* name */
4731 int_info__doc__, /* doc */
4732 int_info_fields, /* fields */
4733 2 /* number of fields */
4734};
4735
4736PyObject *
4737PyLong_GetInfo(void)
4738{
4739 PyObject* int_info;
4740 int field = 0;
4741 int_info = PyStructSequence_New(&Int_InfoType);
4742 if (int_info == NULL)
4743 return NULL;
Mark Dickinson0bdab682009-04-02 18:41:40 +00004744 PyStructSequence_SET_ITEM(int_info, field++,
4745 PyLong_FromLong(PyLong_SHIFT));
4746 PyStructSequence_SET_ITEM(int_info, field++,
4747 PyLong_FromLong(sizeof(digit)));
Mark Dickinsonbd792642009-03-18 20:06:12 +00004748 if (PyErr_Occurred()) {
4749 Py_CLEAR(int_info);
4750 return NULL;
4751 }
4752 return int_info;
4753}
4754
Guido van Rossumddefaf32007-01-14 03:31:43 +00004755int
4756_PyLong_Init(void)
4757{
4758#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004759 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004760 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004761
4762 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4763 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4764 if (Py_TYPE(v) == &PyLong_Type) {
4765 /* The element is already initialized, most likely
4766 * the Python interpreter was initialized before.
4767 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004768 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004769 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004770
Christian Heimes48aa4b12008-02-01 16:56:30 +00004771 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4772 _Py_NewReference(op);
4773 /* _Py_NewReference sets the ref count to 1 but
4774 * the ref count might be larger. Set the refcnt
4775 * to the original refcnt + 1 */
4776 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004777 assert(Py_SIZE(op) == size);
4778 assert(v->ob_digit[0] == abs(ival));
4779 }
4780 else {
4781 PyObject_INIT(v, &PyLong_Type);
4782 }
4783 Py_SIZE(v) = size;
4784 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004785 }
4786#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004787 /* initialize int_info */
4788 if (Int_InfoType.tp_name == 0)
4789 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4790
Guido van Rossumddefaf32007-01-14 03:31:43 +00004791 return 1;
4792}
4793
4794void
4795PyLong_Fini(void)
4796{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004797 /* Integers are currently statically allocated. Py_DECREF is not
4798 needed, but Python must forget about the reference or multiple
4799 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004800#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004801 int i;
4802 PyLongObject *v = small_ints;
4803 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4804 _Py_DEC_REFTOTAL;
4805 _Py_ForgetReference((PyObject*)v);
4806 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004807#endif
4808}