blob: afac856cd0aaa338cac24ed86c606d3eb71f93e8 [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
Tim Petersd1a7da62001-06-13 00:35:57 +0000974
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000975/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000976
977PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000978PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000979{
Thomas Wouters477c8d52006-05-27 19:21:47 +0000980 PyLongObject *v;
Christian Heimesdae2a892008-04-19 00:55:37 +0000981 unsigned PY_LONG_LONG abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000982 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
983 int ndigits = 0;
984 int negative = 0;
985
Guido van Rossumddefaf32007-01-14 03:31:43 +0000986 CHECK_SMALL_INT(ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000987 if (ival < 0) {
Christian Heimesdae2a892008-04-19 00:55:37 +0000988 /* avoid signed overflow on negation; see comments
989 in PyLong_FromLong above. */
990 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000991 negative = 1;
992 }
Christian Heimesdae2a892008-04-19 00:55:37 +0000993 else {
994 abs_ival = (unsigned PY_LONG_LONG)ival;
995 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996
997 /* Count the number of Python digits.
998 We used to pick 5 ("big enough for anything"), but that's a
999 waste of time and space given that 5*15 = 75 bits are rarely
1000 needed. */
Christian Heimesdae2a892008-04-19 00:55:37 +00001001 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002 while (t) {
1003 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001004 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001005 }
1006 v = _PyLong_New(ndigits);
1007 if (v != NULL) {
1008 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001009 Py_SIZE(v) = negative ? -ndigits : ndigits;
Christian Heimesdae2a892008-04-19 00:55:37 +00001010 t = abs_ival;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011 while (t) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001012 *p++ = (digit)(t & PyLong_MASK);
1013 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001014 }
1015 }
1016 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001017}
1018
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001019/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001020
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001022PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001023{
Thomas Wouters477c8d52006-05-27 19:21:47 +00001024 PyLongObject *v;
1025 unsigned PY_LONG_LONG t;
1026 int ndigits = 0;
1027
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001028 if (ival < PyLong_BASE)
Mark Dickinson50b2b6e2008-12-05 17:14:29 +00001029 return PyLong_FromLong((long)ival);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030 /* Count the number of Python digits. */
1031 t = (unsigned PY_LONG_LONG)ival;
1032 while (t) {
1033 ++ndigits;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001034 t >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 }
1036 v = _PyLong_New(ndigits);
1037 if (v != NULL) {
1038 digit *p = v->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001039 Py_SIZE(v) = ndigits;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040 while (ival) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001041 *p++ = (digit)(ival & PyLong_MASK);
1042 ival >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043 }
1044 }
1045 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001046}
1047
Martin v. Löwis18e16552006-02-15 17:27:45 +00001048/* Create a new long int object from a C Py_ssize_t. */
1049
1050PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001051PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001052{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001053 PyLongObject *v;
1054 size_t abs_ival;
1055 size_t t; /* unsigned so >> doesn't propagate sign bit */
1056 int ndigits = 0;
1057 int negative = 0;
1058
1059 CHECK_SMALL_INT(ival);
1060 if (ival < 0) {
1061 /* avoid signed overflow when ival = SIZE_T_MIN */
1062 abs_ival = (size_t)(-1-ival)+1;
1063 negative = 1;
1064 }
1065 else {
1066 abs_ival = (size_t)ival;
1067 }
1068
1069 /* Count the number of Python digits. */
1070 t = abs_ival;
1071 while (t) {
1072 ++ndigits;
1073 t >>= PyLong_SHIFT;
1074 }
1075 v = _PyLong_New(ndigits);
1076 if (v != NULL) {
1077 digit *p = v->ob_digit;
1078 Py_SIZE(v) = negative ? -ndigits : ndigits;
1079 t = abs_ival;
1080 while (t) {
1081 *p++ = (digit)(t & PyLong_MASK);
1082 t >>= PyLong_SHIFT;
1083 }
1084 }
1085 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001086}
1087
1088/* Create a new long int object from a C size_t. */
1089
1090PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001091PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001092{
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001093 PyLongObject *v;
1094 size_t t;
1095 int ndigits = 0;
1096
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001097 if (ival < PyLong_BASE)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001098 return PyLong_FromLong(ival);
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001099 /* Count the number of Python digits. */
1100 t = ival;
1101 while (t) {
1102 ++ndigits;
1103 t >>= PyLong_SHIFT;
1104 }
1105 v = _PyLong_New(ndigits);
1106 if (v != NULL) {
1107 digit *p = v->ob_digit;
1108 Py_SIZE(v) = ndigits;
1109 while (ival) {
1110 *p++ = (digit)(ival & PyLong_MASK);
1111 ival >>= PyLong_SHIFT;
1112 }
1113 }
1114 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001115}
1116
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001117/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001118 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001119
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001120PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001121PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001122{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001123 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001124 PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001125 int one = 1;
1126 int res;
1127
Tim Petersd38b1c72001-09-30 05:09:37 +00001128 if (vv == NULL) {
1129 PyErr_BadInternalCall();
1130 return -1;
1131 }
1132 if (!PyLong_Check(vv)) {
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001133 PyNumberMethods *nb;
1134 PyObject *io;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001135 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1136 nb->nb_int == NULL) {
1137 PyErr_SetString(PyExc_TypeError, "an integer is required");
1138 return -1;
1139 }
1140 io = (*nb->nb_int) (vv);
1141 if (io == NULL)
1142 return -1;
Martin v. Löwis6ce7ed22005-03-03 12:26:35 +00001143 if (PyLong_Check(io)) {
1144 bytes = PyLong_AsLongLong(io);
1145 Py_DECREF(io);
1146 return bytes;
1147 }
1148 Py_DECREF(io);
1149 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001150 return -1;
1151 }
1152
Guido van Rossumddefaf32007-01-14 03:31:43 +00001153 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001154 switch(Py_SIZE(v)) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00001155 case -1: return -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00001156 case 0: return 0;
1157 case 1: return v->ob_digit[0];
1158 }
Tim Petersd1a7da62001-06-13 00:35:57 +00001159 res = _PyLong_AsByteArray(
1160 (PyLongObject *)vv, (unsigned char *)&bytes,
1161 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001162
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001163 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001164 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001165 return (PY_LONG_LONG)-1;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001166 else
1167 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001168}
1169
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001170/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001171 Return -1 and set an error if overflow occurs. */
1172
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001173unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001174PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001175{
Guido van Rossumddefaf32007-01-14 03:31:43 +00001176 PyLongObject *v;
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001177 unsigned PY_LONG_LONG bytes;
Tim Petersd1a7da62001-06-13 00:35:57 +00001178 int one = 1;
1179 int res;
1180
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001181 if (vv == NULL || !PyLong_Check(vv)) {
1182 PyErr_BadInternalCall();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001183 return (unsigned PY_LONG_LONG)-1;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184 }
1185
Guido van Rossumddefaf32007-01-14 03:31:43 +00001186 v = (PyLongObject*)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001187 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001188 case 0: return 0;
1189 case 1: return v->ob_digit[0];
1190 }
1191
Tim Petersd1a7da62001-06-13 00:35:57 +00001192 res = _PyLong_AsByteArray(
1193 (PyLongObject *)vv, (unsigned char *)&bytes,
1194 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001196 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001197 if (res < 0)
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001198 return (unsigned PY_LONG_LONG)res;
Martin v. Löwisc8bb9eb2002-03-09 12:02:59 +00001199 else
1200 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001201}
Tim Petersd1a7da62001-06-13 00:35:57 +00001202
Thomas Hellera4ea6032003-04-17 18:55:45 +00001203/* Get a C unsigned long int from a long int object, ignoring the high bits.
1204 Returns -1 and sets an error condition if an error occurs. */
1205
Guido van Rossumddefaf32007-01-14 03:31:43 +00001206static unsigned PY_LONG_LONG
1207_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001208{
1209 register PyLongObject *v;
1210 unsigned PY_LONG_LONG x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001211 Py_ssize_t i;
1212 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001213
1214 if (vv == NULL || !PyLong_Check(vv)) {
1215 PyErr_BadInternalCall();
1216 return (unsigned long) -1;
1217 }
1218 v = (PyLongObject *)vv;
Christian Heimes90aa7642007-12-19 02:45:37 +00001219 switch(Py_SIZE(v)) {
Guido van Rossumddefaf32007-01-14 03:31:43 +00001220 case 0: return 0;
1221 case 1: return v->ob_digit[0];
1222 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001223 i = Py_SIZE(v);
Thomas Hellera4ea6032003-04-17 18:55:45 +00001224 sign = 1;
1225 x = 0;
1226 if (i < 0) {
1227 sign = -1;
1228 i = -i;
1229 }
1230 while (--i >= 0) {
Mark Dickinson24f57852009-09-28 17:54:52 +00001231 x = (x << PyLong_SHIFT) | v->ob_digit[i];
Thomas Hellera4ea6032003-04-17 18:55:45 +00001232 }
1233 return x * sign;
1234}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001235
1236unsigned PY_LONG_LONG
1237PyLong_AsUnsignedLongLongMask(register PyObject *op)
1238{
1239 PyNumberMethods *nb;
1240 PyLongObject *lo;
1241 unsigned PY_LONG_LONG val;
1242
1243 if (op && PyLong_Check(op))
1244 return _PyLong_AsUnsignedLongLongMask(op);
1245
1246 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1247 nb->nb_int == NULL) {
1248 PyErr_SetString(PyExc_TypeError, "an integer is required");
1249 return (unsigned PY_LONG_LONG)-1;
1250 }
1251
1252 lo = (PyLongObject*) (*nb->nb_int) (op);
1253 if (lo == NULL)
1254 return (unsigned PY_LONG_LONG)-1;
1255 if (PyLong_Check(lo)) {
1256 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1257 Py_DECREF(lo);
1258 if (PyErr_Occurred())
1259 return (unsigned PY_LONG_LONG)-1;
1260 return val;
1261 }
1262 else
1263 {
1264 Py_DECREF(lo);
1265 PyErr_SetString(PyExc_TypeError,
1266 "nb_int should return int object");
1267 return (unsigned PY_LONG_LONG)-1;
1268 }
1269}
Tim Petersd1a7da62001-06-13 00:35:57 +00001270#undef IS_LITTLE_ENDIAN
1271
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001272#endif /* HAVE_LONG_LONG */
1273
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001274#define CHECK_BINOP(v,w) \
1275 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
Neil Schemenauerba872e22001-01-04 01:46:03 +00001276 Py_INCREF(Py_NotImplemented); \
1277 return Py_NotImplemented; \
1278 }
1279
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001280/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1281 2**k if d is nonzero, else 0. */
1282
1283static const unsigned char BitLengthTable[32] = {
1284 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1285 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
1286};
1287
1288static int
1289bits_in_digit(digit d)
1290{
1291 int d_bits = 0;
1292 while (d >= 32) {
1293 d_bits += 6;
1294 d >>= 6;
1295 }
1296 d_bits += (int)BitLengthTable[d];
1297 return d_bits;
1298}
1299
Tim Peters877a2122002-08-12 05:09:36 +00001300/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1301 * is modified in place, by adding y to it. Carries are propagated as far as
1302 * x[m-1], and the remaining carry (0 or 1) is returned.
1303 */
1304static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001305v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001306{
Mark Dickinson17e55872009-01-24 15:56:57 +00001307 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001308 digit carry = 0;
1309
1310 assert(m >= n);
1311 for (i = 0; i < n; ++i) {
1312 carry += x[i] + y[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001313 x[i] = carry & PyLong_MASK;
1314 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001315 assert((carry & 1) == carry);
1316 }
1317 for (; carry && i < m; ++i) {
1318 carry += x[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001319 x[i] = carry & PyLong_MASK;
1320 carry >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001321 assert((carry & 1) == carry);
1322 }
1323 return carry;
1324}
1325
1326/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1327 * is modified in place, by subtracting y from it. Borrows are propagated as
1328 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1329 */
1330static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001331v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001332{
Mark Dickinson17e55872009-01-24 15:56:57 +00001333 Py_ssize_t i;
Tim Peters877a2122002-08-12 05:09:36 +00001334 digit borrow = 0;
1335
1336 assert(m >= n);
1337 for (i = 0; i < n; ++i) {
1338 borrow = x[i] - y[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001339 x[i] = borrow & PyLong_MASK;
1340 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001341 borrow &= 1; /* keep only 1 sign bit */
1342 }
1343 for (; borrow && i < m; ++i) {
1344 borrow = x[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001345 x[i] = borrow & PyLong_MASK;
1346 borrow >>= PyLong_SHIFT;
Tim Peters877a2122002-08-12 05:09:36 +00001347 borrow &= 1;
1348 }
1349 return borrow;
1350}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001351
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001352/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1353 * result in z[0:m], and return the d bits shifted out of the top.
1354 */
1355static digit
1356v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001357{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001358 Py_ssize_t i;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001359 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001360
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001361 assert(0 <= d && d < PyLong_SHIFT);
1362 for (i=0; i < m; i++) {
1363 twodigits acc = (twodigits)a[i] << d | carry;
1364 z[i] = (digit)acc & PyLong_MASK;
1365 carry = (digit)(acc >> PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001366 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001367 return carry;
1368}
1369
1370/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1371 * result in z[0:m], and return the d bits shifted out of the bottom.
1372 */
1373static digit
1374v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1375{
1376 Py_ssize_t i;
1377 digit carry = 0;
1378 digit mask = ((digit)1 << d) - 1U;
1379
1380 assert(0 <= d && d < PyLong_SHIFT);
1381 for (i=m; i-- > 0;) {
1382 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1383 carry = (digit)acc & mask;
1384 z[i] = (digit)(acc >> d);
1385 }
1386 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001387}
1388
Tim Peters212e6142001-07-14 12:23:19 +00001389/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1390 in pout, and returning the remainder. pin and pout point at the LSD.
1391 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001392 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001393 immutable. */
1394
1395static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001396inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001397{
1398 twodigits rem = 0;
1399
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001400 assert(n > 0 && n <= PyLong_MASK);
Tim Peters212e6142001-07-14 12:23:19 +00001401 pin += size;
1402 pout += size;
1403 while (--size >= 0) {
1404 digit hi;
Mark Dickinson24f57852009-09-28 17:54:52 +00001405 rem = (rem << PyLong_SHIFT) | *--pin;
Tim Peters212e6142001-07-14 12:23:19 +00001406 *--pout = hi = (digit)(rem / n);
Mark Dickinson17e55872009-01-24 15:56:57 +00001407 rem -= (twodigits)hi * n;
Tim Peters212e6142001-07-14 12:23:19 +00001408 }
1409 return (digit)rem;
1410}
1411
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001412/* Divide a long integer by a digit, returning both the quotient
1413 (as function result) and the remainder (through *prem).
1414 The sign of a is ignored; n should not be zero. */
1415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001416static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001417divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001418{
Christian Heimes90aa7642007-12-19 02:45:37 +00001419 const Py_ssize_t size = ABS(Py_SIZE(a));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001420 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001421
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001422 assert(n > 0 && n <= PyLong_MASK);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001423 z = _PyLong_New(size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001424 if (z == NULL)
1425 return NULL;
Tim Peters212e6142001-07-14 12:23:19 +00001426 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001427 return long_normalize(z);
1428}
1429
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001430/* Convert a long integer to a base 10 string. Returns a new non-shared
1431 string. (Return value is non-shared so that callers can modify the
1432 returned value if necessary.) */
1433
1434static PyObject *
1435long_to_decimal_string(PyObject *aa)
1436{
1437 PyLongObject *scratch, *a;
1438 PyObject *str;
1439 Py_ssize_t size, strlen, size_a, i, j;
1440 digit *pout, *pin, rem, tenpow;
1441 Py_UNICODE *p;
1442 int negative;
1443
1444 a = (PyLongObject *)aa;
1445 if (a == NULL || !PyLong_Check(a)) {
1446 PyErr_BadInternalCall();
1447 return NULL;
1448 }
1449 size_a = ABS(Py_SIZE(a));
1450 negative = Py_SIZE(a) < 0;
1451
1452 /* quick and dirty upper bound for the number of digits
1453 required to express a in base _PyLong_DECIMAL_BASE:
1454
1455 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
1456
1457 But log2(a) < size_a * PyLong_SHIFT, and
1458 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1459 > 3 * _PyLong_DECIMAL_SHIFT
1460 */
1461 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1462 PyErr_SetString(PyExc_OverflowError,
1463 "long is too large to format");
1464 return NULL;
1465 }
1466 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1467 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1468 scratch = _PyLong_New(size);
1469 if (scratch == NULL)
1470 return NULL;
1471
1472 /* convert array of base _PyLong_BASE digits in pin to an array of
1473 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1474 Volume 2 (3rd edn), section 4.4, Method 1b). */
1475 pin = a->ob_digit;
1476 pout = scratch->ob_digit;
1477 size = 0;
1478 for (i = size_a; --i >= 0; ) {
1479 digit hi = pin[i];
1480 for (j = 0; j < size; j++) {
1481 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
Mark Dickinson741984d2009-09-21 16:18:27 +00001482 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1483 pout[j] = (digit)(z - (twodigits)hi *
1484 _PyLong_DECIMAL_BASE);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001485 }
1486 while (hi) {
1487 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1488 hi /= _PyLong_DECIMAL_BASE;
1489 }
1490 /* check for keyboard interrupt */
1491 SIGCHECK({
1492 Py_DECREF(scratch);
1493 return NULL;
1494 })
1495 }
1496 /* pout should have at least one digit, so that the case when a = 0
1497 works correctly */
1498 if (size == 0)
1499 pout[size++] = 0;
1500
1501 /* calculate exact length of output string, and allocate */
1502 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1503 tenpow = 10;
1504 rem = pout[size-1];
1505 while (rem >= tenpow) {
1506 tenpow *= 10;
1507 strlen++;
1508 }
1509 str = PyUnicode_FromUnicode(NULL, strlen);
1510 if (str == NULL) {
1511 Py_DECREF(scratch);
1512 return NULL;
1513 }
1514
1515 /* fill the string right-to-left */
1516 p = PyUnicode_AS_UNICODE(str) + strlen;
1517 *p = '\0';
1518 /* pout[0] through pout[size-2] contribute exactly
1519 _PyLong_DECIMAL_SHIFT digits each */
1520 for (i=0; i < size - 1; i++) {
1521 rem = pout[i];
1522 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1523 *--p = '0' + rem % 10;
1524 rem /= 10;
1525 }
1526 }
1527 /* pout[size-1]: always produce at least one decimal digit */
1528 rem = pout[i];
1529 do {
1530 *--p = '0' + rem % 10;
1531 rem /= 10;
1532 } while (rem != 0);
1533
1534 /* and sign */
1535 if (negative)
1536 *--p = '-';
1537
1538 /* check we've counted correctly */
1539 assert(p == PyUnicode_AS_UNICODE(str));
1540 Py_DECREF(scratch);
1541 return (PyObject *)str;
1542}
1543
Mark Dickinsoncd068122009-09-18 14:53:08 +00001544/* Convert a long int object to a string, using a given conversion base,
1545 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001546 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001548PyObject *
1549_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001550{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001551 register PyLongObject *a = (PyLongObject *)aa;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001552 PyObject *str;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001553 Py_ssize_t i, sz;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001554 Py_ssize_t size_a;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001555 Py_UNICODE *p, sign = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001556 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001557
Mark Dickinsoncd068122009-09-18 14:53:08 +00001558 assert(base == 2 || base == 8 || base == 10 || base == 16);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001559 if (base == 10)
1560 return long_to_decimal_string((PyObject *)a);
1561
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001562 if (a == NULL || !PyLong_Check(a)) {
1563 PyErr_BadInternalCall();
Guido van Rossume32e0141992-01-19 16:31:05 +00001564 return NULL;
1565 }
Christian Heimes90aa7642007-12-19 02:45:37 +00001566 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001567
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568 /* Compute a rough upper bound for the length of the string */
Mark Dickinsoncd068122009-09-18 14:53:08 +00001569 switch (base) {
1570 case 16:
1571 bits = 4;
1572 break;
1573 case 8:
1574 bits = 3;
1575 break;
1576 case 2:
1577 bits = 1;
1578 break;
1579 default:
1580 assert(0); /* shouldn't ever get here */
1581 bits = 0; /* to silence gcc warning */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001582 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001583 /* compute length of output string: allow 2 characters for prefix and
1584 1 for possible '-' sign. */
1585 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
Thomas Wouters89f507f2006-12-13 04:49:30 +00001586 PyErr_SetString(PyExc_OverflowError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001587 "int is too large to format");
Thomas Wouters89f507f2006-12-13 04:49:30 +00001588 return NULL;
1589 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001590 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1591 is safe from overflow */
1592 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001593 assert(sz >= 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +00001594 str = PyUnicode_FromUnicode(NULL, sz);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001595 if (str == NULL)
1596 return NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001597 p = PyUnicode_AS_UNICODE(str) + sz;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001598 *p = '\0';
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001599 if (Py_SIZE(a) < 0)
1600 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001601
Christian Heimes90aa7642007-12-19 02:45:37 +00001602 if (Py_SIZE(a) == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00001603 *--p = '0';
1604 }
Mark Dickinsoncd068122009-09-18 14:53:08 +00001605 else {
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001606 /* JRH: special case for power-of-2 bases */
1607 twodigits accum = 0;
1608 int accumbits = 0; /* # of bits in accum */
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001609 for (i = 0; i < size_a; ++i) {
1610 accum |= (twodigits)a->ob_digit[i] << accumbits;
1611 accumbits += PyLong_SHIFT;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001612 assert(accumbits >= bits);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001613 do {
Mark Dickinson1f7e18c2009-09-24 18:31:17 +00001614 Py_UNICODE cdigit;
1615 cdigit = (Py_UNICODE)(accum & (base - 1));
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001616 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1617 assert(p > PyUnicode_AS_UNICODE(str));
1618 *--p = cdigit;
Mark Dickinsoncd068122009-09-18 14:53:08 +00001619 accumbits -= bits;
1620 accum >>= bits;
1621 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001622 }
1623 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001624
Mark Dickinsoncd068122009-09-18 14:53:08 +00001625 if (base == 16)
Guido van Rossum3d3037d1991-10-24 14:55:57 +00001626 *--p = 'x';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001627 else if (base == 8)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001628 *--p = 'o';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001629 else /* (base == 2) */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001630 *--p = 'b';
Mark Dickinsoncd068122009-09-18 14:53:08 +00001631 *--p = '0';
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001632 if (sign)
1633 *--p = sign;
Walter Dörwald1ab83302007-05-18 17:15:44 +00001634 if (p != PyUnicode_AS_UNICODE(str)) {
1635 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001636 assert(p > q);
1637 do {
1638 } while ((*q++ = *p++) != '\0');
Guido van Rossumc7ec9c91991-05-28 21:58:16 +00001639 q--;
Mark Dickinson659c7b12009-09-13 12:06:08 +00001640 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1641 PyUnicode_AS_UNICODE(str)))) {
Walter Dörwald1ab83302007-05-18 17:15:44 +00001642 Py_DECREF(str);
1643 return NULL;
1644 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001645 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001646 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001647}
1648
Thomas Wouters477c8d52006-05-27 19:21:47 +00001649/* Table of digit values for 8-bit string -> integer conversion.
1650 * '0' maps to 0, ..., '9' maps to 9.
1651 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1652 * All other indices map to 37.
1653 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001654 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001656unsigned char _PyLong_DigitValue[256] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001657 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1658 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1659 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1660 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1661 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1662 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1663 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1664 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1665 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1666 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1667 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1668 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1669 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1670 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1671 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1672 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1673};
1674
1675/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001676 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1677 * non-digit (which may be *str!). A normalized long is returned.
1678 * The point to this routine is that it takes time linear in the number of
1679 * string characters.
1680 */
1681static PyLongObject *
1682long_from_binary_base(char **str, int base)
1683{
1684 char *p = *str;
1685 char *start = p;
1686 int bits_per_char;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001687 Py_ssize_t n;
Tim Petersbf2674b2003-02-02 07:51:32 +00001688 PyLongObject *z;
1689 twodigits accum;
1690 int bits_in_accum;
1691 digit *pdigit;
1692
1693 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1694 n = base;
1695 for (bits_per_char = -1; n; ++bits_per_char)
1696 n >>= 1;
1697 /* n <- total # of bits needed, while setting p to end-of-string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001698 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001699 ++p;
Tim Petersbf2674b2003-02-02 07:51:32 +00001700 *str = p;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001701 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1702 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
Thomas Wouters89f507f2006-12-13 04:49:30 +00001703 if (n / bits_per_char < p - start) {
Tim Peters1a3b19a2003-02-02 17:33:53 +00001704 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001705 "int string too large to convert");
Tim Peters1a3b19a2003-02-02 17:33:53 +00001706 return NULL;
1707 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001708 n = n / PyLong_SHIFT;
Tim Petersbf2674b2003-02-02 07:51:32 +00001709 z = _PyLong_New(n);
1710 if (z == NULL)
1711 return NULL;
1712 /* Read string from right, and fill in long from left; i.e.,
1713 * from least to most significant in both.
1714 */
1715 accum = 0;
1716 bits_in_accum = 0;
1717 pdigit = z->ob_digit;
1718 while (--p >= start) {
Raymond Hettinger35631532009-01-09 03:58:09 +00001719 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Tim Petersc7bc0b92003-05-05 20:39:43 +00001720 assert(k >= 0 && k < base);
Mark Dickinson17e55872009-01-24 15:56:57 +00001721 accum |= (twodigits)k << bits_in_accum;
Tim Petersbf2674b2003-02-02 07:51:32 +00001722 bits_in_accum += bits_per_char;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001723 if (bits_in_accum >= PyLong_SHIFT) {
1724 *pdigit++ = (digit)(accum & PyLong_MASK);
Mark Dickinson17e55872009-01-24 15:56:57 +00001725 assert(pdigit - z->ob_digit <= n);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001726 accum >>= PyLong_SHIFT;
1727 bits_in_accum -= PyLong_SHIFT;
1728 assert(bits_in_accum < PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001729 }
1730 }
1731 if (bits_in_accum) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001732 assert(bits_in_accum <= PyLong_SHIFT);
Tim Petersbf2674b2003-02-02 07:51:32 +00001733 *pdigit++ = (digit)accum;
Mark Dickinson17e55872009-01-24 15:56:57 +00001734 assert(pdigit - z->ob_digit <= n);
Tim Petersbf2674b2003-02-02 07:51:32 +00001735 }
1736 while (pdigit - z->ob_digit < n)
1737 *pdigit++ = 0;
1738 return long_normalize(z);
1739}
1740
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001741PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001742PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001743{
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001744 int sign = 1, error_if_nonzero = 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00001745 char *start, *orig_str = str;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001746 PyLongObject *z = NULL;
Guido van Rossum25236212007-08-22 23:28:23 +00001747 PyObject *strobj;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001748 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001749
Guido van Rossum472c04f1996-12-05 21:57:21 +00001750 if ((base != 0 && base < 2) || base > 36) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001751 PyErr_SetString(PyExc_ValueError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00001752 "int() arg 2 must be >= 2 and <= 36");
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001753 return NULL;
1754 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00001755 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001756 str++;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001757 if (*str == '+')
1758 ++str;
1759 else if (*str == '-') {
1760 ++str;
1761 sign = -1;
1762 }
1763 if (base == 0) {
1764 if (str[0] != '0')
1765 base = 10;
1766 else if (str[1] == 'x' || str[1] == 'X')
1767 base = 16;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001768 else if (str[1] == 'o' || str[1] == 'O')
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001769 base = 8;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001770 else if (str[1] == 'b' || str[1] == 'B')
1771 base = 2;
1772 else {
1773 /* "old" (C-style) octal literal, now invalid.
1774 it might still be zero though */
1775 error_if_nonzero = 1;
1776 base = 10;
1777 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001778 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001779 if (str[0] == '0' &&
1780 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1781 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1782 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001783 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784
Guido van Rossume6762971998-06-22 03:54:46 +00001785 start = str;
Tim Petersbf2674b2003-02-02 07:51:32 +00001786 if ((base & (base - 1)) == 0)
1787 z = long_from_binary_base(&str, base);
1788 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001789/***
1790Binary bases can be converted in time linear in the number of digits, because
1791Python's representation base is binary. Other bases (including decimal!) use
1792the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001793
Thomas Wouters477c8d52006-05-27 19:21:47 +00001794First some math: the largest integer that can be expressed in N base-B digits
1795is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1796case number of Python digits needed to hold it is the smallest integer n s.t.
1797
1798 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1799 BASE**n >= B**N [taking logs to base BASE]
1800 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1801
1802The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1803this quickly. A Python long with that much space is reserved near the start,
1804and the result is computed into it.
1805
1806The input string is actually treated as being in base base**i (i.e., i digits
1807are processed at a time), where two more static arrays hold:
1808
1809 convwidth_base[base] = the largest integer i such that base**i <= BASE
1810 convmultmax_base[base] = base ** convwidth_base[base]
1811
1812The first of these is the largest i such that i consecutive input digits
1813must fit in a single Python digit. The second is effectively the input
1814base we're really using.
1815
1816Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1817convmultmax_base[base], the result is "simply"
1818
1819 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1820
1821where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001822
1823Error analysis: as above, the number of Python digits `n` needed is worst-
1824case
1825
1826 n >= N * log(B)/log(BASE)
1827
1828where `N` is the number of input digits in base `B`. This is computed via
1829
1830 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1831
1832below. Two numeric concerns are how much space this can waste, and whether
1833the computed result can be too small. To be concrete, assume BASE = 2**15,
1834which is the default (and it's unlikely anyone changes that).
1835
1836Waste isn't a problem: provided the first input digit isn't 0, the difference
1837between the worst-case input with N digits and the smallest input with N
1838digits is about a factor of B, but B is small compared to BASE so at most
1839one allocated Python digit can remain unused on that count. If
1840N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1841and adding 1 returns a result 1 larger than necessary. However, that can't
1842happen: whenever B is a power of 2, long_from_binary_base() is called
1843instead, and it's impossible for B**i to be an integer power of 2**15 when
1844B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1845an exact integer when B is not a power of 2, since B**i has a prime factor
1846other than 2 in that case, but (2**15)**j's only prime factor is 2).
1847
1848The computed result can be too small if the true value of N*log(B)/log(BASE)
1849is a little bit larger than an exact integer, but due to roundoff errors (in
1850computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1851yields a numeric result a little less than that integer. Unfortunately, "how
1852close can a transcendental function get to an integer over some range?"
1853questions are generally theoretically intractable. Computer analysis via
1854continued fractions is practical: expand log(B)/log(BASE) via continued
1855fractions, giving a sequence i/j of "the best" rational approximations. Then
1856j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1857we can get very close to being in trouble, but very rarely. For example,
185876573 is a denominator in one of the continued-fraction approximations to
1859log(10)/log(2**15), and indeed:
1860
1861 >>> log(10)/log(2**15)*76573
1862 16958.000000654003
1863
1864is very close to an integer. If we were working with IEEE single-precision,
1865rounding errors could kill us. Finding worst cases in IEEE double-precision
1866requires better-than-double-precision log() functions, and Tim didn't bother.
1867Instead the code checks to see whether the allocated space is enough as each
1868new Python digit is added, and copies the whole thing to a larger long if not.
1869This should happen extremely rarely, and in fact I don't have a test case
1870that triggers it(!). Instead the code was tested by artificially allocating
1871just 1 digit at the start, so that the copying code was exercised for every
1872digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001873***/
1874 register twodigits c; /* current input character */
1875 Py_ssize_t size_z;
1876 int i;
1877 int convwidth;
1878 twodigits convmultmax, convmult;
1879 digit *pz, *pzstop;
1880 char* scan;
1881
1882 static double log_base_BASE[37] = {0.0e0,};
1883 static int convwidth_base[37] = {0,};
1884 static twodigits convmultmax_base[37] = {0,};
1885
1886 if (log_base_BASE[base] == 0.0) {
1887 twodigits convmax = base;
1888 int i = 1;
1889
1890 log_base_BASE[base] = log((double)base) /
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001891 log((double)PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001892 for (;;) {
1893 twodigits next = convmax * base;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001894 if (next > PyLong_BASE)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001895 break;
1896 convmax = next;
1897 ++i;
1898 }
1899 convmultmax_base[base] = convmax;
1900 assert(i > 0);
1901 convwidth_base[base] = i;
1902 }
1903
1904 /* Find length of the string of numeric characters. */
1905 scan = str;
Christian Heimesbbe741d2008-03-28 10:53:29 +00001906 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001907 ++scan;
1908
1909 /* Create a long object that can contain the largest possible
1910 * integer with this base and length. Note that there's no
1911 * need to initialize z->ob_digit -- no slot is read up before
1912 * being stored into.
1913 */
1914 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001915 /* Uncomment next line to test exceedingly rare copy code */
1916 /* size_z = 1; */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001917 assert(size_z > 0);
1918 z = _PyLong_New(size_z);
1919 if (z == NULL)
1920 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00001921 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922
1923 /* `convwidth` consecutive input digits are treated as a single
1924 * digit in base `convmultmax`.
1925 */
1926 convwidth = convwidth_base[base];
1927 convmultmax = convmultmax_base[base];
1928
1929 /* Work ;-) */
1930 while (str < scan) {
1931 /* grab up to convwidth digits from the input string */
Christian Heimesbbe741d2008-03-28 10:53:29 +00001932 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Thomas Wouters477c8d52006-05-27 19:21:47 +00001933 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
1934 c = (twodigits)(c * base +
Raymond Hettinger35631532009-01-09 03:58:09 +00001935 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001936 assert(c < PyLong_BASE);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001937 }
1938
1939 convmult = convmultmax;
1940 /* Calculate the shift only if we couldn't get
1941 * convwidth digits.
1942 */
1943 if (i != convwidth) {
1944 convmult = base;
1945 for ( ; i > 1; --i)
1946 convmult *= base;
1947 }
1948
1949 /* Multiply z by convmult, and add c. */
1950 pz = z->ob_digit;
Christian Heimes90aa7642007-12-19 02:45:37 +00001951 pzstop = pz + Py_SIZE(z);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001952 for (; pz < pzstop; ++pz) {
1953 c += (twodigits)*pz * convmult;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001954 *pz = (digit)(c & PyLong_MASK);
1955 c >>= PyLong_SHIFT;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001956 }
1957 /* carry off the current end? */
1958 if (c) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001959 assert(c < PyLong_BASE);
Christian Heimes90aa7642007-12-19 02:45:37 +00001960 if (Py_SIZE(z) < size_z) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001961 *pz = (digit)c;
Christian Heimes90aa7642007-12-19 02:45:37 +00001962 ++Py_SIZE(z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001963 }
1964 else {
1965 PyLongObject *tmp;
1966 /* Extremely rare. Get more space. */
Christian Heimes90aa7642007-12-19 02:45:37 +00001967 assert(Py_SIZE(z) == size_z);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001968 tmp = _PyLong_New(size_z + 1);
1969 if (tmp == NULL) {
1970 Py_DECREF(z);
1971 return NULL;
1972 }
1973 memcpy(tmp->ob_digit,
1974 z->ob_digit,
1975 sizeof(digit) * size_z);
1976 Py_DECREF(z);
1977 z = tmp;
1978 z->ob_digit[size_z] = (digit)c;
1979 ++size_z;
1980 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001981 }
Tim Petersbf2674b2003-02-02 07:51:32 +00001982 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001983 }
Guido van Rossumac6a37a1998-08-04 15:04:06 +00001984 if (z == NULL)
1985 return NULL;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001986 if (error_if_nonzero) {
1987 /* reset the base to 0, else the exception message
1988 doesn't make too much sense */
1989 base = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +00001990 if (Py_SIZE(z) != 0)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001991 goto onError;
1992 /* there might still be other problems, therefore base
1993 remains zero here for the same reason */
1994 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00001995 if (str == start)
1996 goto onError;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997 if (sign < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +00001998 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossum9e896b32000-04-05 20:11:21 +00001999 while (*str && isspace(Py_CHARMASK(*str)))
2000 str++;
2001 if (*str != '\0')
2002 goto onError;
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002003 if (pend)
2004 *pend = str;
Martin v. Löwis029656f2008-06-30 04:06:08 +00002005 long_normalize(z);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002006 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002007
2008 onError:
Guido van Rossum9e896b32000-04-05 20:11:21 +00002009 Py_XDECREF(z);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002010 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
Guido van Rossum25236212007-08-22 23:28:23 +00002011 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002012 if (strobj == NULL)
2013 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002014 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00002015 "invalid literal for int() with base %d: %R",
2016 base, strobj);
2017 Py_DECREF(strobj);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002018 return NULL;
2019}
2020
2021PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002022PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002023{
Walter Dörwald07e14762002-11-06 16:15:14 +00002024 PyObject *result;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002025 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002026
Walter Dörwald07e14762002-11-06 16:15:14 +00002027 if (buffer == NULL)
2028 return NULL;
2029
2030 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2031 PyMem_FREE(buffer);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002032 return NULL;
2033 }
Walter Dörwald07e14762002-11-06 16:15:14 +00002034 result = PyLong_FromString(buffer, NULL, base);
2035 PyMem_FREE(buffer);
2036 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002037}
2038
Tim Peters9f688bf2000-07-07 15:53:28 +00002039/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002040static PyLongObject *x_divrem
Tim Peters9f688bf2000-07-07 15:53:28 +00002041 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002042static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002043
2044/* Long division with remainder, top-level routine */
2045
Guido van Rossume32e0141992-01-19 16:31:05 +00002046static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002047long_divrem(PyLongObject *a, PyLongObject *b,
2048 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002049{
Christian Heimes90aa7642007-12-19 02:45:37 +00002050 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002051 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002052
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002053 if (size_b == 0) {
Guido van Rossumbd3a5271998-08-11 15:04:47 +00002054 PyErr_SetString(PyExc_ZeroDivisionError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00002055 "integer division or modulo by zero");
Guido van Rossume32e0141992-01-19 16:31:05 +00002056 return -1;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002057 }
2058 if (size_a < size_b ||
Guido van Rossum472c04f1996-12-05 21:57:21 +00002059 (size_a == size_b &&
2060 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002061 /* |a| < |b|. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00002062 *pdiv = (PyLongObject*)PyLong_FromLong(0);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002063 if (*pdiv == NULL)
2064 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002065 Py_INCREF(a);
2066 *prem = (PyLongObject *) a;
Guido van Rossume32e0141992-01-19 16:31:05 +00002067 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002068 }
2069 if (size_b == 1) {
2070 digit rem = 0;
2071 z = divrem1(a, b->ob_digit[0], &rem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002072 if (z == NULL)
2073 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002075 if (*prem == NULL) {
2076 Py_DECREF(z);
2077 return -1;
2078 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002079 }
Guido van Rossume32e0141992-01-19 16:31:05 +00002080 else {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002081 z = x_divrem(a, b, prem);
Guido van Rossume32e0141992-01-19 16:31:05 +00002082 if (z == NULL)
2083 return -1;
2084 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002085 /* Set the signs.
2086 The quotient z has the sign of a*b;
2087 the remainder r has the sign of a,
2088 so a = b*z + r. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002089 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
Guido van Rossumddefaf32007-01-14 03:31:43 +00002090 NEGATE(z);
Christian Heimes90aa7642007-12-19 02:45:37 +00002091 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002092 NEGATE(*prem);
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002093 *pdiv = maybe_small_long(z);
Guido van Rossume32e0141992-01-19 16:31:05 +00002094 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002095}
2096
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002097/* Unsigned long division with remainder -- the algorithm. The arguments v1
2098 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002101x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002102{
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002103 PyLongObject *v, *w, *a;
2104 Py_ssize_t i, k, size_v, size_w;
2105 int d;
2106 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2107 twodigits vv;
2108 sdigit zhi;
2109 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002110
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002111 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2112 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2113 handle the special case when the initial estimate q for a quotient
2114 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2115 that won't overflow a digit. */
2116
2117 /* allocate space; w will also be used to hold the final remainder */
2118 size_v = ABS(Py_SIZE(v1));
2119 size_w = ABS(Py_SIZE(w1));
2120 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2121 v = _PyLong_New(size_v+1);
2122 if (v == NULL) {
2123 *prem = NULL;
2124 return NULL;
2125 }
2126 w = _PyLong_New(size_w);
2127 if (w == NULL) {
2128 Py_DECREF(v);
2129 *prem = NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002130 return NULL;
2131 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002132
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002133 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2134 shift v1 left by the same amount. Results go into w and v. */
2135 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2136 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2137 assert(carry == 0);
2138 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2139 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2140 v->ob_digit[size_v] = carry;
2141 size_v++;
2142 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002143
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002144 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2145 at most (and usually exactly) k = size_v - size_w digits. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146 k = size_v - size_w;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002147 assert(k >= 0);
2148 a = _PyLong_New(k);
2149 if (a == NULL) {
2150 Py_DECREF(w);
2151 Py_DECREF(v);
2152 *prem = NULL;
2153 return NULL;
2154 }
2155 v0 = v->ob_digit;
2156 w0 = w->ob_digit;
2157 wm1 = w0[size_w-1];
2158 wm2 = w0[size_w-2];
2159 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2160 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2161 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002162
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002163 SIGCHECK({
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002164 Py_DECREF(a);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002165 Py_DECREF(w);
2166 Py_DECREF(v);
2167 *prem = NULL;
2168 return NULL;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00002169 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002170
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002171 /* estimate quotient digit q; may overestimate by 1 (rare) */
2172 vtop = vk[size_w];
2173 assert(vtop <= wm1);
2174 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2175 q = (digit)(vv / wm1);
2176 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2177 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2178 | vk[size_w-2])) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002179 --q;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002180 r += wm1;
2181 if (r >= PyLong_BASE)
2182 break;
2183 }
2184 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002185
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002186 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2187 zhi = 0;
2188 for (i = 0; i < size_w; ++i) {
2189 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2190 -PyLong_BASE * q <= z < PyLong_BASE */
2191 z = (sdigit)vk[i] + zhi -
2192 (stwodigits)q * (stwodigits)w0[i];
2193 vk[i] = (digit)z & PyLong_MASK;
2194 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
2195 z, PyLong_SHIFT);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002196 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002197
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002198 /* add w back if q was too large (this branch taken rarely) */
2199 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2200 if ((sdigit)vtop + zhi < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002201 carry = 0;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002202 for (i = 0; i < size_w; ++i) {
2203 carry += vk[i] + w0[i];
2204 vk[i] = carry & PyLong_MASK;
2205 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002206 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002207 --q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002208 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002209
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002210 /* store quotient digit */
2211 assert(q < PyLong_BASE);
2212 *--ak = q;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002213 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002214
2215 /* unshift remainder; we reuse w to store the result */
2216 carry = v_rshift(w0, v0, size_w, d);
2217 assert(carry==0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002218 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002219
2220 *prem = long_normalize(w);
2221 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002222}
2223
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002224/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2225 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2226 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2227 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2228 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2229 -1.0. */
2230
2231/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2232#if DBL_MANT_DIG == 53
2233#define EXP2_DBL_MANT_DIG 9007199254740992.0
2234#else
2235#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2236#endif
2237
2238double
2239_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2240{
2241 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2242 /* See below for why x_digits is always large enough. */
2243 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2244 double dx;
2245 /* Correction term for round-half-to-even rounding. For a digit x,
2246 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2247 multiple of 4, rounding ties to a multiple of 8. */
2248 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
2249
2250 a_size = ABS(Py_SIZE(a));
2251 if (a_size == 0) {
2252 /* Special case for 0: significand 0.0, exponent 0. */
2253 *e = 0;
2254 return 0.0;
2255 }
2256 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2257 /* The following is an overflow-free version of the check
2258 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2259 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2260 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2261 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
2262 goto overflow;
2263 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
2264
2265 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2266 (shifting left if a_bits <= DBL_MANT_DIG + 2).
2267
2268 Number of digits needed for result: write // for floor division.
2269 Then if shifting left, we end up using
2270
2271 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
2272
2273 digits. If shifting right, we use
2274
2275 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
2276
2277 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2278 the inequalities
2279
2280 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2281 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2282 1 + (m - n - 1) // PyLong_SHIFT,
2283
2284 valid for any integers m and n, we find that x_size satisfies
2285
2286 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
2287
2288 in both cases.
2289 */
2290 if (a_bits <= DBL_MANT_DIG + 2) {
2291 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2292 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2293 x_size = 0;
2294 while (x_size < shift_digits)
2295 x_digits[x_size++] = 0;
2296 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2297 shift_bits);
2298 x_size += a_size;
2299 x_digits[x_size++] = rem;
2300 }
2301 else {
2302 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2303 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2304 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2305 a_size - shift_digits, shift_bits);
2306 x_size = a_size - shift_digits;
2307 /* For correct rounding below, we need the least significant
2308 bit of x to be 'sticky' for this shift: if any of the bits
2309 shifted out was nonzero, we set the least significant bit
2310 of x. */
2311 if (rem)
2312 x_digits[0] |= 1;
2313 else
2314 while (shift_digits > 0)
2315 if (a->ob_digit[--shift_digits]) {
2316 x_digits[0] |= 1;
2317 break;
2318 }
2319 }
2320 assert(1 <= x_size && x_size <= sizeof(x_digits)/sizeof(digit));
2321
2322 /* Round, and convert to double. */
2323 x_digits[0] += half_even_correction[x_digits[0] & 7];
2324 dx = x_digits[--x_size];
2325 while (x_size > 0)
2326 dx = dx * PyLong_BASE + x_digits[--x_size];
2327
2328 /* Rescale; make correction if result is 1.0. */
2329 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2330 if (dx == 1.0) {
2331 if (a_bits == PY_SSIZE_T_MAX)
2332 goto overflow;
2333 dx = 0.5;
2334 a_bits += 1;
2335 }
2336
2337 *e = a_bits;
2338 return Py_SIZE(a) < 0 ? -dx : dx;
2339
2340 overflow:
2341 /* exponent > PY_SSIZE_T_MAX */
2342 PyErr_SetString(PyExc_OverflowError,
2343 "huge integer: number of bits overflows a Py_ssize_t");
2344 *e = 0;
2345 return -1.0;
2346}
2347
2348/* Get a C double from a long int object. Rounds to the nearest double,
2349 using the round-half-to-even rule in the case of a tie. */
2350
2351double
2352PyLong_AsDouble(PyObject *v)
2353{
2354 Py_ssize_t exponent;
2355 double x;
2356
2357 if (v == NULL || !PyLong_Check(v)) {
2358 PyErr_BadInternalCall();
2359 return -1.0;
2360 }
2361 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2362 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2363 PyErr_SetString(PyExc_OverflowError,
2364 "long int too large to convert to float");
2365 return -1.0;
2366 }
2367 return ldexp(x, exponent);
2368}
2369
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370/* Methods */
2371
2372static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002373long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374{
Christian Heimes90aa7642007-12-19 02:45:37 +00002375 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376}
2377
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002379long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002380{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002381 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002382
Christian Heimes90aa7642007-12-19 02:45:37 +00002383 if (Py_SIZE(a) != Py_SIZE(b)) {
2384 if (ABS(Py_SIZE(a)) == 0 && ABS(Py_SIZE(b)) == 0)
Guido van Rossumc6913e71991-11-19 20:26:46 +00002385 sign = 0;
2386 else
Christian Heimes90aa7642007-12-19 02:45:37 +00002387 sign = Py_SIZE(a) - Py_SIZE(b);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002388 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002389 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002390 Py_ssize_t i = ABS(Py_SIZE(a));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002391 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2392 ;
2393 if (i < 0)
2394 sign = 0;
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002395 else {
Mark Dickinsone4416742009-02-15 15:14:57 +00002396 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
Christian Heimes90aa7642007-12-19 02:45:37 +00002397 if (Py_SIZE(a) < 0)
Guido van Rossum0b0db8e1993-01-21 16:07:51 +00002398 sign = -sign;
2399 }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002400 }
Guido van Rossumc6913e71991-11-19 20:26:46 +00002401 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002402}
2403
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002404#define TEST_COND(cond) \
2405 ((cond) ? Py_True : Py_False)
2406
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002407static PyObject *
2408long_richcompare(PyObject *self, PyObject *other, int op)
2409{
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002410 int result;
2411 PyObject *v;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002412 CHECK_BINOP(self, other);
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002413 if (self == other)
2414 result = 0;
2415 else
2416 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2417 /* Convert the return value to a Boolean */
2418 switch (op) {
2419 case Py_EQ:
2420 v = TEST_COND(result == 0);
2421 break;
2422 case Py_NE:
2423 v = TEST_COND(result != 0);
2424 break;
2425 case Py_LE:
2426 v = TEST_COND(result <= 0);
2427 break;
2428 case Py_GE:
2429 v = TEST_COND(result >= 0);
2430 break;
2431 case Py_LT:
2432 v = TEST_COND(result == -1);
2433 break;
2434 case Py_GT:
2435 v = TEST_COND(result == 1);
2436 break;
2437 default:
2438 PyErr_BadArgument();
2439 return NULL;
2440 }
2441 Py_INCREF(v);
2442 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002443}
2444
Guido van Rossum9bfef441993-03-29 10:43:31 +00002445static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002446long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002447{
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002448 unsigned long x;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002449 Py_ssize_t i;
2450 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002451
2452 /* This is designed so that Python ints and longs with the
2453 same value hash to the same value, otherwise comparisons
2454 of mapping keys will turn out weird */
Christian Heimes90aa7642007-12-19 02:45:37 +00002455 i = Py_SIZE(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +00002456 switch(i) {
Mark Dickinson0d4785b2009-02-15 17:27:41 +00002457 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
Guido van Rossumddefaf32007-01-14 03:31:43 +00002458 case 0: return 0;
2459 case 1: return v->ob_digit[0];
2460 }
Guido van Rossum9bfef441993-03-29 10:43:31 +00002461 sign = 1;
2462 x = 0;
2463 if (i < 0) {
2464 sign = -1;
2465 i = -(i);
2466 }
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002467 /* The following loop produces a C unsigned long x such that x is
2468 congruent to the absolute value of v modulo ULONG_MAX. The
Thomas Woutersce272b62007-09-19 21:19:28 +00002469 resulting x is nonzero if and only if v is. */
Guido van Rossum9bfef441993-03-29 10:43:31 +00002470 while (--i >= 0) {
Neal Norwitzd5a65a72003-02-23 23:11:41 +00002471 /* Force a native long #-bits (32 or 64) circular shift */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002472 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
Guido van Rossum9bfef441993-03-29 10:43:31 +00002473 x += v->ob_digit[i];
Mark Dickinsona5cafdf2009-01-26 21:56:07 +00002474 /* If the addition above overflowed we compensate by
2475 incrementing. This preserves the value modulo
2476 ULONG_MAX. */
2477 if (x < v->ob_digit[i])
Thomas Woutersce272b62007-09-19 21:19:28 +00002478 x++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002479 }
2480 x = x * sign;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00002481 if (x == (unsigned long)-1)
2482 x = (unsigned long)-2;
2483 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002484}
2485
2486
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002487/* Add the absolute values of two long integers. */
2488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002489static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002490x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002491{
Christian Heimes90aa7642007-12-19 02:45:37 +00002492 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002493 PyLongObject *z;
Mark Dickinson17e55872009-01-24 15:56:57 +00002494 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002495 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002496
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002497 /* Ensure a is the larger of the two: */
2498 if (size_a < size_b) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002499 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002500 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002501 size_a = size_b;
2502 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002503 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002504 z = _PyLong_New(size_a+1);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002505 if (z == NULL)
2506 return NULL;
2507 for (i = 0; i < size_b; ++i) {
2508 carry += a->ob_digit[i] + b->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002509 z->ob_digit[i] = carry & PyLong_MASK;
2510 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002511 }
2512 for (; i < size_a; ++i) {
2513 carry += a->ob_digit[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002514 z->ob_digit[i] = carry & PyLong_MASK;
2515 carry >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002516 }
2517 z->ob_digit[i] = carry;
2518 return long_normalize(z);
2519}
2520
2521/* Subtract the absolute values of two integers. */
2522
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002523static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002524x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002525{
Christian Heimes90aa7642007-12-19 02:45:37 +00002526 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002527 PyLongObject *z;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002528 Py_ssize_t i;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002529 int sign = 1;
2530 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002531
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002532 /* Ensure a is the larger of the two: */
2533 if (size_a < size_b) {
2534 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002535 { PyLongObject *temp = a; a = b; b = temp; }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002536 { Py_ssize_t size_temp = size_a;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002537 size_a = size_b;
2538 size_b = size_temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002539 }
2540 else if (size_a == size_b) {
2541 /* Find highest digit where a and b differ: */
2542 i = size_a;
2543 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2544 ;
2545 if (i < 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002546 return (PyLongObject *)PyLong_FromLong(0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002547 if (a->ob_digit[i] < b->ob_digit[i]) {
2548 sign = -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002549 { PyLongObject *temp = a; a = b; b = temp; }
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002550 }
2551 size_a = size_b = i+1;
2552 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002553 z = _PyLong_New(size_a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002554 if (z == NULL)
2555 return NULL;
2556 for (i = 0; i < size_b; ++i) {
2557 /* The following assumes unsigned arithmetic
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002558 works module 2**N for some N>PyLong_SHIFT. */
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002559 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002560 z->ob_digit[i] = borrow & PyLong_MASK;
2561 borrow >>= PyLong_SHIFT;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002562 borrow &= 1; /* Keep only one sign bit */
2563 }
2564 for (; i < size_a; ++i) {
2565 borrow = a->ob_digit[i] - borrow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002566 z->ob_digit[i] = borrow & PyLong_MASK;
2567 borrow >>= PyLong_SHIFT;
Tim Peters43f04a32000-07-08 02:26:47 +00002568 borrow &= 1; /* Keep only one sign bit */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002569 }
2570 assert(borrow == 0);
Guido van Rossumc6913e71991-11-19 20:26:46 +00002571 if (sign < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00002572 NEGATE(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002573 return long_normalize(z);
2574}
2575
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002576static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002577long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002578{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002579 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002580
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002581 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002582
Christian Heimes90aa7642007-12-19 02:45:37 +00002583 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Christian Heimes217cfd12007-12-02 14:31:20 +00002584 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002585 MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002586 return result;
2587 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002588 if (Py_SIZE(a) < 0) {
2589 if (Py_SIZE(b) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002590 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002591 if (z != NULL && Py_SIZE(z) != 0)
2592 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002593 }
2594 else
2595 z = x_sub(b, a);
2596 }
2597 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002598 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002599 z = x_sub(a, b);
2600 else
2601 z = x_add(a, b);
2602 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002603 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002604}
2605
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002606static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002607long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002608{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002609 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002610
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002611 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002612
Christian Heimes90aa7642007-12-19 02:45:37 +00002613 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002614 PyObject* r;
2615 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
Martin v. Löwis14b6d922007-02-06 21:05:30 +00002616 return r;
2617 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002618 if (Py_SIZE(a) < 0) {
2619 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002620 z = x_sub(a, b);
2621 else
2622 z = x_add(a, b);
Christian Heimes90aa7642007-12-19 02:45:37 +00002623 if (z != NULL && Py_SIZE(z) != 0)
2624 Py_SIZE(z) = -(Py_SIZE(z));
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002625 }
2626 else {
Christian Heimes90aa7642007-12-19 02:45:37 +00002627 if (Py_SIZE(b) < 0)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002628 z = x_add(a, b);
2629 else
2630 z = x_sub(a, b);
2631 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002632 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002633}
2634
Tim Peters5af4e6c2002-08-12 02:31:19 +00002635/* Grade school multiplication, ignoring the signs.
2636 * Returns the absolute value of the product, or NULL if error.
2637 */
2638static PyLongObject *
2639x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002640{
Tim Peters5af4e6c2002-08-12 02:31:19 +00002641 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00002642 Py_ssize_t size_a = ABS(Py_SIZE(a));
2643 Py_ssize_t size_b = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002644 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002645
Tim Peters5af4e6c2002-08-12 02:31:19 +00002646 z = _PyLong_New(size_a + size_b);
2647 if (z == NULL)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002648 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649
Christian Heimes90aa7642007-12-19 02:45:37 +00002650 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
Tim Peters0973b992004-08-29 22:16:50 +00002651 if (a == b) {
2652 /* Efficient squaring per HAC, Algorithm 14.16:
2653 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2654 * Gives slightly less than a 2x speedup when a == b,
2655 * via exploiting that each entry in the multiplication
2656 * pyramid appears twice (except for the size_a squares).
2657 */
2658 for (i = 0; i < size_a; ++i) {
2659 twodigits carry;
2660 twodigits f = a->ob_digit[i];
2661 digit *pz = z->ob_digit + (i << 1);
2662 digit *pa = a->ob_digit + i + 1;
2663 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002664
Tim Peters0973b992004-08-29 22:16:50 +00002665 SIGCHECK({
2666 Py_DECREF(z);
2667 return NULL;
2668 })
2669
2670 carry = *pz + f * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002671 *pz++ = (digit)(carry & PyLong_MASK);
2672 carry >>= PyLong_SHIFT;
2673 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002674
2675 /* Now f is added in twice in each column of the
2676 * pyramid it appears. Same as adding f<<1 once.
2677 */
2678 f <<= 1;
2679 while (pa < paend) {
2680 carry += *pz + *pa++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002681 *pz++ = (digit)(carry & PyLong_MASK);
2682 carry >>= PyLong_SHIFT;
2683 assert(carry <= (PyLong_MASK << 1));
Tim Peters0973b992004-08-29 22:16:50 +00002684 }
2685 if (carry) {
2686 carry += *pz;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002687 *pz++ = (digit)(carry & PyLong_MASK);
2688 carry >>= PyLong_SHIFT;
Tim Peters0973b992004-08-29 22:16:50 +00002689 }
2690 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002691 *pz += (digit)(carry & PyLong_MASK);
2692 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002693 }
Tim Peters0973b992004-08-29 22:16:50 +00002694 }
2695 else { /* a is not the same as b -- gradeschool long mult */
2696 for (i = 0; i < size_a; ++i) {
2697 twodigits carry = 0;
2698 twodigits f = a->ob_digit[i];
2699 digit *pz = z->ob_digit + i;
2700 digit *pb = b->ob_digit;
2701 digit *pbend = b->ob_digit + size_b;
2702
2703 SIGCHECK({
2704 Py_DECREF(z);
2705 return NULL;
2706 })
2707
2708 while (pb < pbend) {
2709 carry += *pz + *pb++ * f;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002710 *pz++ = (digit)(carry & PyLong_MASK);
2711 carry >>= PyLong_SHIFT;
2712 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002713 }
2714 if (carry)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002715 *pz += (digit)(carry & PyLong_MASK);
2716 assert((carry >> PyLong_SHIFT) == 0);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002717 }
2718 }
Tim Peters44121a62002-08-12 06:17:58 +00002719 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002720}
2721
2722/* A helper for Karatsuba multiplication (k_mul).
2723 Takes a long "n" and an integer "size" representing the place to
2724 split, and sets low and high such that abs(n) == (high << size) + low,
2725 viewing the shift as being by digits. The sign bit is ignored, and
2726 the return values are >= 0.
2727 Returns 0 on success, -1 on failure.
2728*/
2729static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002730kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002731{
2732 PyLongObject *hi, *lo;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002733 Py_ssize_t size_lo, size_hi;
Christian Heimes90aa7642007-12-19 02:45:37 +00002734 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002735
2736 size_lo = MIN(size_n, size);
2737 size_hi = size_n - size_lo;
2738
2739 if ((hi = _PyLong_New(size_hi)) == NULL)
2740 return -1;
2741 if ((lo = _PyLong_New(size_lo)) == NULL) {
2742 Py_DECREF(hi);
2743 return -1;
2744 }
2745
2746 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2747 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
2748
2749 *high = long_normalize(hi);
2750 *low = long_normalize(lo);
2751 return 0;
2752}
2753
Tim Peters60004642002-08-12 22:01:34 +00002754static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2755
Tim Peters5af4e6c2002-08-12 02:31:19 +00002756/* Karatsuba multiplication. Ignores the input signs, and returns the
2757 * absolute value of the product (or NULL if error).
2758 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2759 */
2760static PyLongObject *
2761k_mul(PyLongObject *a, PyLongObject *b)
2762{
Christian Heimes90aa7642007-12-19 02:45:37 +00002763 Py_ssize_t asize = ABS(Py_SIZE(a));
2764 Py_ssize_t bsize = ABS(Py_SIZE(b));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002765 PyLongObject *ah = NULL;
2766 PyLongObject *al = NULL;
2767 PyLongObject *bh = NULL;
2768 PyLongObject *bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002769 PyLongObject *ret = NULL;
Tim Peters738eda72002-08-12 15:08:20 +00002770 PyLongObject *t1, *t2, *t3;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002771 Py_ssize_t shift; /* the number of digits we split off */
2772 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002773
Tim Peters5af4e6c2002-08-12 02:31:19 +00002774 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2775 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2776 * Then the original product is
Tim Peters18c15b92002-08-12 02:43:58 +00002777 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
Tim Peters5af4e6c2002-08-12 02:31:19 +00002778 * By picking X to be a power of 2, "*X" is just shifting, and it's
2779 * been reduced to 3 multiplies on numbers half the size.
2780 */
2781
Tim Petersfc07e562002-08-12 02:54:10 +00002782 /* We want to split based on the larger number; fiddle so that b
Tim Peters5af4e6c2002-08-12 02:31:19 +00002783 * is largest.
2784 */
Tim Peters738eda72002-08-12 15:08:20 +00002785 if (asize > bsize) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002786 t1 = a;
2787 a = b;
2788 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002789
2790 i = asize;
2791 asize = bsize;
2792 bsize = i;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002793 }
2794
2795 /* Use gradeschool math when either number is too small. */
Tim Peters0973b992004-08-29 22:16:50 +00002796 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2797 if (asize <= i) {
Tim Peters738eda72002-08-12 15:08:20 +00002798 if (asize == 0)
Facundo Batista6e6f59b2008-07-24 18:57:11 +00002799 return (PyLongObject *)PyLong_FromLong(0);
Tim Peters44121a62002-08-12 06:17:58 +00002800 else
2801 return x_mul(a, b);
2802 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002803
Tim Peters60004642002-08-12 22:01:34 +00002804 /* If a is small compared to b, splitting on b gives a degenerate
2805 * case with ah==0, and Karatsuba may be (even much) less efficient
2806 * than "grade school" then. However, we can still win, by viewing
2807 * b as a string of "big digits", each of width a->ob_size. That
2808 * leads to a sequence of balanced calls to k_mul.
2809 */
2810 if (2 * asize <= bsize)
2811 return k_lopsided_mul(a, b);
2812
Tim Petersd6974a52002-08-13 20:37:51 +00002813 /* Split a & b into hi & lo pieces. */
Tim Peters738eda72002-08-12 15:08:20 +00002814 shift = bsize >> 1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002815 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002816 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002817
Tim Peters0973b992004-08-29 22:16:50 +00002818 if (a == b) {
2819 bh = ah;
2820 bl = al;
2821 Py_INCREF(bh);
2822 Py_INCREF(bl);
2823 }
2824 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002825
Tim Petersd64c1de2002-08-12 17:36:03 +00002826 /* The plan:
2827 * 1. Allocate result space (asize + bsize digits: that's always
2828 * enough).
2829 * 2. Compute ah*bh, and copy into result at 2*shift.
2830 * 3. Compute al*bl, and copy into result at 0. Note that this
2831 * can't overlap with #2.
2832 * 4. Subtract al*bl from the result, starting at shift. This may
2833 * underflow (borrow out of the high digit), but we don't care:
2834 * we're effectively doing unsigned arithmetic mod
2835 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2836 * borrows and carries out of the high digit can be ignored.
2837 * 5. Subtract ah*bh from the result, starting at shift.
2838 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2839 * at shift.
2840 */
2841
2842 /* 1. Allocate result space. */
Tim Peters70b041b2002-08-12 19:38:01 +00002843 ret = _PyLong_New(asize + bsize);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844 if (ret == NULL) goto fail;
2845#ifdef Py_DEBUG
2846 /* Fill with trash, to catch reference to uninitialized digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002847 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002848#endif
Tim Peters44121a62002-08-12 06:17:58 +00002849
Tim Petersd64c1de2002-08-12 17:36:03 +00002850 /* 2. t1 <- ah*bh, and copy into high digits of result. */
Tim Peters738eda72002-08-12 15:08:20 +00002851 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002852 assert(Py_SIZE(t1) >= 0);
2853 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
Tim Peters738eda72002-08-12 15:08:20 +00002854 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
Christian Heimes90aa7642007-12-19 02:45:37 +00002855 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002856
2857 /* Zero-out the digits higher than the ah*bh copy. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002858 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
Tim Peters44121a62002-08-12 06:17:58 +00002859 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002860 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
Tim Peters44121a62002-08-12 06:17:58 +00002861 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002862
Tim Petersd64c1de2002-08-12 17:36:03 +00002863 /* 3. t2 <- al*bl, and copy into the low digits. */
Tim Peters738eda72002-08-12 15:08:20 +00002864 if ((t2 = k_mul(al, bl)) == NULL) {
2865 Py_DECREF(t1);
2866 goto fail;
2867 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002868 assert(Py_SIZE(t2) >= 0);
2869 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2870 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002871
2872 /* Zero out remaining digits. */
Christian Heimes90aa7642007-12-19 02:45:37 +00002873 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002874 if (i)
Christian Heimes90aa7642007-12-19 02:45:37 +00002875 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002876
Tim Petersd64c1de2002-08-12 17:36:03 +00002877 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2878 * because it's fresher in cache.
2879 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002880 i = Py_SIZE(ret) - shift; /* # digits after shift */
2881 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
Tim Peters738eda72002-08-12 15:08:20 +00002882 Py_DECREF(t2);
2883
Christian Heimes90aa7642007-12-19 02:45:37 +00002884 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
Tim Peters738eda72002-08-12 15:08:20 +00002885 Py_DECREF(t1);
2886
Tim Petersd64c1de2002-08-12 17:36:03 +00002887 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002888 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2889 Py_DECREF(ah);
2890 Py_DECREF(al);
2891 ah = al = NULL;
2892
Tim Peters0973b992004-08-29 22:16:50 +00002893 if (a == b) {
2894 t2 = t1;
2895 Py_INCREF(t2);
2896 }
2897 else if ((t2 = x_add(bh, bl)) == NULL) {
Tim Peters5af4e6c2002-08-12 02:31:19 +00002898 Py_DECREF(t1);
2899 goto fail;
2900 }
2901 Py_DECREF(bh);
2902 Py_DECREF(bl);
2903 bh = bl = NULL;
2904
Tim Peters738eda72002-08-12 15:08:20 +00002905 t3 = k_mul(t1, t2);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002906 Py_DECREF(t1);
2907 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002908 if (t3 == NULL) goto fail;
Christian Heimes90aa7642007-12-19 02:45:37 +00002909 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002910
Tim Petersd6974a52002-08-13 20:37:51 +00002911 /* Add t3. It's not obvious why we can't run out of room here.
2912 * See the (*) comment after this function.
Tim Petersd8b21732002-08-12 19:30:26 +00002913 */
Christian Heimes90aa7642007-12-19 02:45:37 +00002914 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
Tim Peters738eda72002-08-12 15:08:20 +00002915 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002916
Tim Peters5af4e6c2002-08-12 02:31:19 +00002917 return long_normalize(ret);
2918
2919 fail:
2920 Py_XDECREF(ret);
2921 Py_XDECREF(ah);
2922 Py_XDECREF(al);
2923 Py_XDECREF(bh);
2924 Py_XDECREF(bl);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002925 return NULL;
2926}
2927
Tim Petersd6974a52002-08-13 20:37:51 +00002928/* (*) Why adding t3 can't "run out of room" above.
2929
Tim Petersab86c2b2002-08-15 20:06:00 +00002930Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
2931to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00002932
Tim Petersab86c2b2002-08-15 20:06:00 +000029331. For any integer i, i = c(i/2) + f(i/2). In particular,
2934 bsize = c(bsize/2) + f(bsize/2).
29352. shift = f(bsize/2)
29363. asize <= bsize
29374. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
2938 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00002939
Tim Petersab86c2b2002-08-15 20:06:00 +00002940We allocated asize + bsize result digits, and add t3 into them at an offset
2941of shift. This leaves asize+bsize-shift allocated digit positions for t3
2942to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
2943asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00002944
Tim Petersab86c2b2002-08-15 20:06:00 +00002945bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
2946at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002947
Tim Petersab86c2b2002-08-15 20:06:00 +00002948If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
2949digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
2950most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00002951
Tim Petersab86c2b2002-08-15 20:06:00 +00002952The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00002953
Tim Petersab86c2b2002-08-15 20:06:00 +00002954 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00002955
Tim Petersab86c2b2002-08-15 20:06:00 +00002956and we have asize + c(bsize/2) available digit positions. We need to show
2957this is always enough. An instance of c(bsize/2) cancels out in both, so
2958the question reduces to whether asize digits is enough to hold
2959(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
2960then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
2961asize 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 +00002962digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00002963asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00002964c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
2965is enough to hold 2 bits. This is so if bsize >= 2, which holds because
2966bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00002967
Tim Peters48d52c02002-08-14 17:07:32 +00002968Note that since there's always enough room for (ah+al)*(bh+bl), and that's
2969clearly >= each of ah*bh and al*bl, there's always enough room to subtract
2970ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00002971*/
2972
Tim Peters60004642002-08-12 22:01:34 +00002973/* b has at least twice the digits of a, and a is big enough that Karatsuba
2974 * would pay off *if* the inputs had balanced sizes. View b as a sequence
2975 * of slices, each with a->ob_size digits, and multiply the slices by a,
2976 * one at a time. This gives k_mul balanced inputs to work with, and is
2977 * also cache-friendly (we compute one double-width slice of the result
2978 * at a time, then move on, never bactracking except for the helpful
2979 * single-width slice overlap between successive partial sums).
2980 */
2981static PyLongObject *
2982k_lopsided_mul(PyLongObject *a, PyLongObject *b)
2983{
Christian Heimes90aa7642007-12-19 02:45:37 +00002984 const Py_ssize_t asize = ABS(Py_SIZE(a));
2985 Py_ssize_t bsize = ABS(Py_SIZE(b));
Martin v. Löwis18e16552006-02-15 17:27:45 +00002986 Py_ssize_t nbdone; /* # of b digits already multiplied */
Tim Peters60004642002-08-12 22:01:34 +00002987 PyLongObject *ret;
2988 PyLongObject *bslice = NULL;
2989
2990 assert(asize > KARATSUBA_CUTOFF);
2991 assert(2 * asize <= bsize);
2992
2993 /* Allocate result space, and zero it out. */
2994 ret = _PyLong_New(asize + bsize);
2995 if (ret == NULL)
2996 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00002997 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00002998
2999 /* Successive slices of b are copied into bslice. */
Tim Peters12034032002-08-12 22:10:00 +00003000 bslice = _PyLong_New(asize);
Tim Peters60004642002-08-12 22:01:34 +00003001 if (bslice == NULL)
3002 goto fail;
3003
3004 nbdone = 0;
3005 while (bsize > 0) {
3006 PyLongObject *product;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003007 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003008
3009 /* Multiply the next slice of b by a. */
3010 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3011 nbtouse * sizeof(digit));
Christian Heimes90aa7642007-12-19 02:45:37 +00003012 Py_SIZE(bslice) = nbtouse;
Tim Peters60004642002-08-12 22:01:34 +00003013 product = k_mul(a, bslice);
3014 if (product == NULL)
3015 goto fail;
3016
3017 /* Add into result. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003018 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3019 product->ob_digit, Py_SIZE(product));
Tim Peters60004642002-08-12 22:01:34 +00003020 Py_DECREF(product);
3021
3022 bsize -= nbtouse;
3023 nbdone += nbtouse;
3024 }
3025
3026 Py_DECREF(bslice);
3027 return long_normalize(ret);
3028
3029 fail:
3030 Py_DECREF(ret);
3031 Py_XDECREF(bslice);
3032 return NULL;
3033}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034
3035static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003036long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003037{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003038 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003039
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003040 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003041
Mark Dickinsonbd792642009-03-18 20:06:12 +00003042 /* fast path for single-digit multiplication */
Christian Heimes90aa7642007-12-19 02:45:37 +00003043 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonbd792642009-03-18 20:06:12 +00003044 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
3045#ifdef HAVE_LONG_LONG
3046 return PyLong_FromLongLong((PY_LONG_LONG)v);
3047#else
3048 /* if we don't have long long then we're almost certainly
3049 using 15-bit digits, so v will fit in a long. In the
3050 unlikely event that we're using 30-bit digits on a platform
3051 without long long, a large v will just cause us to fall
3052 through to the general multiplication code below. */
3053 if (v >= LONG_MIN && v <= LONG_MAX)
3054 return PyLong_FromLong((long)v);
3055#endif
Martin v. Löwis14b6d922007-02-06 21:05:30 +00003056 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003057
Tim Petersd64c1de2002-08-12 17:36:03 +00003058 z = k_mul(a, b);
Tim Peters9973d742002-08-15 19:41:06 +00003059 /* Negate if exactly one of the inputs is negative. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003060 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003061 NEGATE(z);
Tim Peters9973d742002-08-15 19:41:06 +00003062 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003063}
3064
Guido van Rossume32e0141992-01-19 16:31:05 +00003065/* The / and % operators are now defined in terms of divmod().
3066 The expression a mod b has the value a - b*floor(a/b).
3067 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003068 |a| by |b|, with the sign of a. This is also expressed
3069 as a - b*trunc(a/b), if trunc truncates towards zero.
3070 Some examples:
3071 a b a rem b a mod b
3072 13 10 3 3
3073 -13 10 -3 7
3074 13 -10 3 -7
3075 -13 -10 -3 -3
3076 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003077 have different signs. We then subtract one from the 'div'
3078 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003079
Tim Peters47e52ee2004-08-30 02:44:38 +00003080/* Compute
3081 * *pdiv, *pmod = divmod(v, w)
3082 * NULL can be passed for pdiv or pmod, in which case that part of
3083 * the result is simply thrown away. The caller owns a reference to
3084 * each of these it requests (does not pass NULL for).
3085 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003086static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003087l_divmod(PyLongObject *v, PyLongObject *w,
Tim Peters9f688bf2000-07-07 15:53:28 +00003088 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003089{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003090 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003091
Guido van Rossume32e0141992-01-19 16:31:05 +00003092 if (long_divrem(v, w, &div, &mod) < 0)
3093 return -1;
Christian Heimes90aa7642007-12-19 02:45:37 +00003094 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3095 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003096 PyLongObject *temp;
3097 PyLongObject *one;
3098 temp = (PyLongObject *) long_add(mod, w);
3099 Py_DECREF(mod);
Guido van Rossume32e0141992-01-19 16:31:05 +00003100 mod = temp;
3101 if (mod == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003102 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003103 return -1;
3104 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003105 one = (PyLongObject *) PyLong_FromLong(1L);
Guido van Rossume32e0141992-01-19 16:31:05 +00003106 if (one == NULL ||
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003107 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3108 Py_DECREF(mod);
3109 Py_DECREF(div);
3110 Py_XDECREF(one);
Guido van Rossume32e0141992-01-19 16:31:05 +00003111 return -1;
3112 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003113 Py_DECREF(one);
3114 Py_DECREF(div);
Guido van Rossume32e0141992-01-19 16:31:05 +00003115 div = temp;
3116 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003117 if (pdiv != NULL)
3118 *pdiv = div;
3119 else
3120 Py_DECREF(div);
3121
3122 if (pmod != NULL)
3123 *pmod = mod;
3124 else
3125 Py_DECREF(mod);
3126
Guido van Rossume32e0141992-01-19 16:31:05 +00003127 return 0;
3128}
3129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003130static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003131long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003132{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003133 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003134
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003135 CHECK_BINOP(a, b);
3136 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003137 div = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003138 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003139}
3140
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003141/* PyLong/PyLong -> float, with correctly rounded result. */
3142
3143#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3144#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3145
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003146static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003147long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003148{
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003149 PyLongObject *a, *b, *x;
3150 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3151 digit mask, low;
3152 int inexact, negate, a_is_small, b_is_small;
3153 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003154
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003155 CHECK_BINOP(v, w);
3156 a = (PyLongObject *)v;
3157 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003158
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003159 /*
3160 Method in a nutshell:
3161
3162 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3163 1. choose a suitable integer 'shift'
3164 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3165 3. adjust x for correct rounding
3166 4. convert x to a double dx with the same value
3167 5. return ldexp(dx, shift).
3168
3169 In more detail:
3170
3171 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3172 returns either 0.0 or -0.0, depending on the sign of b. For a and
3173 b both nonzero, ignore signs of a and b, and add the sign back in
3174 at the end. Now write a_bits and b_bits for the bit lengths of a
3175 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3176 for b). Then
3177
3178 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
3179
3180 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3181 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3182 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3183 the way, we can assume that
3184
3185 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
3186
3187 1. The integer 'shift' is chosen so that x has the right number of
3188 bits for a double, plus two or three extra bits that will be used
3189 in the rounding decisions. Writing a_bits and b_bits for the
3190 number of significant bits in a and b respectively, a
3191 straightforward formula for shift is:
3192
3193 shift = a_bits - b_bits - DBL_MANT_DIG - 2
3194
3195 This is fine in the usual case, but if a/b is smaller than the
3196 smallest normal float then it can lead to double rounding on an
3197 IEEE 754 platform, giving incorrectly rounded results. So we
3198 adjust the formula slightly. The actual formula used is:
3199
3200 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
3201
3202 2. The quantity x is computed by first shifting a (left -shift bits
3203 if shift <= 0, right shift bits if shift > 0) and then dividing by
3204 b. For both the shift and the division, we keep track of whether
3205 the result is inexact, in a flag 'inexact'; this information is
3206 needed at the rounding stage.
3207
3208 With the choice of shift above, together with our assumption that
3209 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3210 that x >= 1.
3211
3212 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3213 this with an exactly representable float of the form
3214
3215 round(x/2**extra_bits) * 2**(extra_bits+shift).
3216
3217 For float representability, we need x/2**extra_bits <
3218 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3219 DBL_MANT_DIG. This translates to the condition:
3220
3221 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
3222
3223 To round, we just modify the bottom digit of x in-place; this can
3224 end up giving a digit with value > PyLONG_MASK, but that's not a
3225 problem since digits can hold values up to 2*PyLONG_MASK+1.
3226
3227 With the original choices for shift above, extra_bits will always
3228 be 2 or 3. Then rounding under the round-half-to-even rule, we
3229 round up iff the most significant of the extra bits is 1, and
3230 either: (a) the computation of x in step 2 had an inexact result,
3231 or (b) at least one other of the extra bits is 1, or (c) the least
3232 significant bit of x (above those to be rounded) is 1.
3233
3234 4. Conversion to a double is straightforward; all floating-point
3235 operations involved in the conversion are exact, so there's no
3236 danger of rounding errors.
3237
3238 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3239 The result will always be exactly representable as a double, except
3240 in the case that it overflows. To avoid dependence on the exact
3241 behaviour of ldexp on overflow, we check for overflow before
3242 applying ldexp. The result of ldexp is adjusted for sign before
3243 returning.
3244 */
3245
3246 /* Reduce to case where a and b are both positive. */
3247 a_size = ABS(Py_SIZE(a));
3248 b_size = ABS(Py_SIZE(b));
3249 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3250 if (b_size == 0) {
Tim Peterse2a60002001-09-04 06:17:36 +00003251 PyErr_SetString(PyExc_ZeroDivisionError,
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003252 "division by zero");
3253 goto error;
3254 }
3255 if (a_size == 0)
3256 goto underflow_or_zero;
3257
3258 /* Fast path for a and b small (exactly representable in a double).
3259 Relies on floating-point division being correctly rounded; results
3260 may be subject to double rounding on x86 machines that operate with
3261 the x87 FPU set to 64-bit precision. */
3262 a_is_small = a_size <= MANT_DIG_DIGITS ||
3263 (a_size == MANT_DIG_DIGITS+1 &&
3264 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3265 b_is_small = b_size <= MANT_DIG_DIGITS ||
3266 (b_size == MANT_DIG_DIGITS+1 &&
3267 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3268 if (a_is_small && b_is_small) {
3269 double da, db;
3270 da = a->ob_digit[--a_size];
3271 while (a_size > 0)
3272 da = da * PyLong_BASE + a->ob_digit[--a_size];
3273 db = b->ob_digit[--b_size];
3274 while (b_size > 0)
3275 db = db * PyLong_BASE + b->ob_digit[--b_size];
3276 result = da / db;
3277 goto success;
Tim Peterse2a60002001-09-04 06:17:36 +00003278 }
3279
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003280 /* Catch obvious cases of underflow and overflow */
3281 diff = a_size - b_size;
3282 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3283 /* Extreme overflow */
Tim Peterse2a60002001-09-04 06:17:36 +00003284 goto overflow;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003285 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3286 /* Extreme underflow */
3287 goto underflow_or_zero;
3288 /* Next line is now safe from overflowing a Py_ssize_t */
3289 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3290 bits_in_digit(b->ob_digit[b_size - 1]);
3291 /* Now diff = a_bits - b_bits. */
3292 if (diff > DBL_MAX_EXP)
Tim Peterse2a60002001-09-04 06:17:36 +00003293 goto overflow;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003294 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3295 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003296
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003297 /* Choose value for shift; see comments for step 1 above. */
3298 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
3299
3300 inexact = 0;
3301
3302 /* x = abs(a * 2**-shift) */
3303 if (shift <= 0) {
3304 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3305 digit rem;
3306 /* x = a << -shift */
3307 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3308 /* In practice, it's probably impossible to end up
3309 here. Both a and b would have to be enormous,
3310 using close to SIZE_T_MAX bytes of memory each. */
3311 PyErr_SetString(PyExc_OverflowError,
3312 "intermediate overflow during division");
3313 goto error;
3314 }
3315 x = _PyLong_New(a_size + shift_digits + 1);
3316 if (x == NULL)
3317 goto error;
3318 for (i = 0; i < shift_digits; i++)
3319 x->ob_digit[i] = 0;
3320 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3321 a_size, -shift % PyLong_SHIFT);
3322 x->ob_digit[a_size + shift_digits] = rem;
3323 }
3324 else {
3325 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3326 digit rem;
3327 /* x = a >> shift */
3328 assert(a_size >= shift_digits);
3329 x = _PyLong_New(a_size - shift_digits);
3330 if (x == NULL)
3331 goto error;
3332 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3333 a_size - shift_digits, shift % PyLong_SHIFT);
3334 /* set inexact if any of the bits shifted out is nonzero */
3335 if (rem)
3336 inexact = 1;
3337 while (!inexact && shift_digits > 0)
3338 if (a->ob_digit[--shift_digits])
3339 inexact = 1;
3340 }
3341 long_normalize(x);
3342 x_size = Py_SIZE(x);
3343
3344 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3345 reference to x, so it's safe to modify it in-place. */
3346 if (b_size == 1) {
3347 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3348 b->ob_digit[0]);
3349 long_normalize(x);
3350 if (rem)
3351 inexact = 1;
3352 }
3353 else {
3354 PyLongObject *div, *rem;
3355 div = x_divrem(x, b, &rem);
3356 Py_DECREF(x);
3357 x = div;
3358 if (x == NULL)
3359 goto error;
3360 if (Py_SIZE(rem))
3361 inexact = 1;
3362 Py_DECREF(rem);
3363 }
3364 x_size = ABS(Py_SIZE(x));
3365 assert(x_size > 0); /* result of division is never zero */
3366 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
3367
3368 /* The number of extra bits that have to be rounded away. */
3369 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3370 assert(extra_bits == 2 || extra_bits == 3);
3371
3372 /* Round by directly modifying the low digit of x. */
3373 mask = (digit)1 << (extra_bits - 1);
3374 low = x->ob_digit[0] | inexact;
3375 if (low & mask && low & (3*mask-1))
3376 low += mask;
3377 x->ob_digit[0] = low & ~(mask-1U);
3378
3379 /* Convert x to a double dx; the conversion is exact. */
3380 dx = x->ob_digit[--x_size];
3381 while (x_size > 0)
3382 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3383 Py_DECREF(x);
3384
3385 /* Check whether ldexp result will overflow a double. */
3386 if (shift + x_bits >= DBL_MAX_EXP &&
3387 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, x_bits)))
3388 goto overflow;
3389 result = ldexp(dx, shift);
3390
3391 success:
3392 return PyFloat_FromDouble(negate ? -result : result);
3393
3394 underflow_or_zero:
3395 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
3396
3397 overflow:
Tim Peterse2a60002001-09-04 06:17:36 +00003398 PyErr_SetString(PyExc_OverflowError,
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003399 "integer division result too large for a float");
3400 error:
Tim Peterse2a60002001-09-04 06:17:36 +00003401 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003402}
3403
3404static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003405long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003406{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003407 PyLongObject *mod;
3408
3409 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003410
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003411 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003412 mod = NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003413 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003414}
3415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003416static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003417long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003418{
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003419 PyLongObject *div, *mod;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003420 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003421
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003422 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003423
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003424 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003425 return NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003426 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003427 z = PyTuple_New(2);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003428 if (z != NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003429 PyTuple_SetItem(z, 0, (PyObject *) div);
3430 PyTuple_SetItem(z, 1, (PyObject *) mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003431 }
3432 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003433 Py_DECREF(div);
3434 Py_DECREF(mod);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003435 }
3436 return z;
3437}
3438
Tim Peters47e52ee2004-08-30 02:44:38 +00003439/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003440static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003441long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003442{
Tim Peters47e52ee2004-08-30 02:44:38 +00003443 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3444 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003445
Tim Peters47e52ee2004-08-30 02:44:38 +00003446 PyLongObject *z = NULL; /* accumulated result */
Martin v. Löwis18e16552006-02-15 17:27:45 +00003447 Py_ssize_t i, j, k; /* counters */
Tim Peters47e52ee2004-08-30 02:44:38 +00003448 PyLongObject *temp = NULL;
3449
3450 /* 5-ary values. If the exponent is large enough, table is
3451 * precomputed so that table[i] == a**i % c for i in range(32).
3452 */
3453 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3454 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
3455
3456 /* a, b, c = v, w, x */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003457 CHECK_BINOP(v, w);
3458 a = (PyLongObject*)v; Py_INCREF(a);
3459 b = (PyLongObject*)w; Py_INCREF(b);
Tim Peters47e52ee2004-08-30 02:44:38 +00003460 if (PyLong_Check(x)) {
3461 c = (PyLongObject *)x;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003462 Py_INCREF(x);
3463 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003464 else if (x == Py_None)
3465 c = NULL;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003466 else {
3467 Py_DECREF(a);
3468 Py_DECREF(b);
3469 Py_INCREF(Py_NotImplemented);
3470 return Py_NotImplemented;
3471 }
Tim Peters4c483c42001-09-05 06:24:58 +00003472
Christian Heimes90aa7642007-12-19 02:45:37 +00003473 if (Py_SIZE(b) < 0) { /* if exponent is negative */
Tim Peters47e52ee2004-08-30 02:44:38 +00003474 if (c) {
Tim Peters4c483c42001-09-05 06:24:58 +00003475 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Tim Peters47e52ee2004-08-30 02:44:38 +00003476 "cannot be negative when 3rd argument specified");
Tim Peterscd97da32004-08-30 02:58:59 +00003477 goto Error;
Tim Peters32f453e2001-09-03 08:35:41 +00003478 }
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003479 else {
Tim Peters47e52ee2004-08-30 02:44:38 +00003480 /* else return a float. This works because we know
3481 that this calls float_pow() which converts its
3482 arguments to double. */
3483 Py_DECREF(a);
3484 Py_DECREF(b);
3485 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
Guido van Rossum2c7b8fe1999-10-11 22:34:41 +00003486 }
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00003487 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003488
3489 if (c) {
3490 /* if modulus == 0:
3491 raise ValueError() */
Christian Heimes90aa7642007-12-19 02:45:37 +00003492 if (Py_SIZE(c) == 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003493 PyErr_SetString(PyExc_ValueError,
3494 "pow() 3rd argument cannot be 0");
Tim Peterscd97da32004-08-30 02:58:59 +00003495 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003496 }
3497
3498 /* if modulus < 0:
3499 negativeOutput = True
3500 modulus = -modulus */
Christian Heimes90aa7642007-12-19 02:45:37 +00003501 if (Py_SIZE(c) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003502 negativeOutput = 1;
3503 temp = (PyLongObject *)_PyLong_Copy(c);
3504 if (temp == NULL)
3505 goto Error;
3506 Py_DECREF(c);
3507 c = temp;
3508 temp = NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00003509 NEGATE(c);
Tim Peters47e52ee2004-08-30 02:44:38 +00003510 }
3511
3512 /* if modulus == 1:
3513 return 0 */
Christian Heimes90aa7642007-12-19 02:45:37 +00003514 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003515 z = (PyLongObject *)PyLong_FromLong(0L);
3516 goto Done;
3517 }
3518
3519 /* if base < 0:
3520 base = base % modulus
3521 Having the base positive just makes things easier. */
Christian Heimes90aa7642007-12-19 02:45:37 +00003522 if (Py_SIZE(a) < 0) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003523 if (l_divmod(a, c, NULL, &temp) < 0)
Tim Peterscd97da32004-08-30 02:58:59 +00003524 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003525 Py_DECREF(a);
3526 a = temp;
3527 temp = NULL;
3528 }
3529 }
3530
3531 /* At this point a, b, and c are guaranteed non-negative UNLESS
3532 c is NULL, in which case a may be negative. */
3533
3534 z = (PyLongObject *)PyLong_FromLong(1L);
3535 if (z == NULL)
3536 goto Error;
3537
3538 /* Perform a modular reduction, X = X % c, but leave X alone if c
3539 * is NULL.
3540 */
3541#define REDUCE(X) \
3542 if (c != NULL) { \
3543 if (l_divmod(X, c, NULL, &temp) < 0) \
3544 goto Error; \
3545 Py_XDECREF(X); \
3546 X = temp; \
3547 temp = NULL; \
3548 }
3549
3550 /* Multiply two values, then reduce the result:
3551 result = X*Y % c. If c is NULL, skip the mod. */
3552#define MULT(X, Y, result) \
3553{ \
3554 temp = (PyLongObject *)long_mul(X, Y); \
3555 if (temp == NULL) \
3556 goto Error; \
3557 Py_XDECREF(result); \
3558 result = temp; \
3559 temp = NULL; \
3560 REDUCE(result) \
3561}
3562
Christian Heimes90aa7642007-12-19 02:45:37 +00003563 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003564 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3565 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
Christian Heimes90aa7642007-12-19 02:45:37 +00003566 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003567 digit bi = b->ob_digit[i];
3568
Mark Dickinsone4416742009-02-15 15:14:57 +00003569 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003570 MULT(z, z, z)
3571 if (bi & j)
3572 MULT(z, a, z)
3573 }
3574 }
3575 }
3576 else {
3577 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3578 Py_INCREF(z); /* still holds 1L */
3579 table[0] = z;
3580 for (i = 1; i < 32; ++i)
3581 MULT(table[i-1], a, table[i])
3582
Christian Heimes90aa7642007-12-19 02:45:37 +00003583 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003584 const digit bi = b->ob_digit[i];
3585
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003586 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003587 const int index = (bi >> j) & 0x1f;
3588 for (k = 0; k < 5; ++k)
3589 MULT(z, z, z)
3590 if (index)
3591 MULT(z, table[index], z)
3592 }
3593 }
3594 }
3595
Christian Heimes90aa7642007-12-19 02:45:37 +00003596 if (negativeOutput && (Py_SIZE(z) != 0)) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003597 temp = (PyLongObject *)long_sub(z, c);
3598 if (temp == NULL)
3599 goto Error;
3600 Py_DECREF(z);
3601 z = temp;
3602 temp = NULL;
3603 }
3604 goto Done;
3605
3606 Error:
3607 if (z != NULL) {
3608 Py_DECREF(z);
3609 z = NULL;
3610 }
3611 /* fall through */
3612 Done:
Christian Heimes90aa7642007-12-19 02:45:37 +00003613 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
Tim Peters47e52ee2004-08-30 02:44:38 +00003614 for (i = 0; i < 32; ++i)
3615 Py_XDECREF(table[i]);
3616 }
Tim Petersde7990b2005-07-17 23:45:23 +00003617 Py_DECREF(a);
3618 Py_DECREF(b);
3619 Py_XDECREF(c);
3620 Py_XDECREF(temp);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003621 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003622}
3623
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003624static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003625long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003626{
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003627 /* Implement ~x as -(x+1) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003628 PyLongObject *x;
3629 PyLongObject *w;
Christian Heimes90aa7642007-12-19 02:45:37 +00003630 if (ABS(Py_SIZE(v)) <=1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003631 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003632 w = (PyLongObject *)PyLong_FromLong(1L);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003633 if (w == NULL)
3634 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003635 x = (PyLongObject *) long_add(v, w);
3636 Py_DECREF(w);
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003637 if (x == NULL)
3638 return NULL;
Christian Heimes90aa7642007-12-19 02:45:37 +00003639 Py_SIZE(x) = -(Py_SIZE(x));
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003640 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003641}
3642
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003643static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003644long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003645{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003646 PyLongObject *z;
Christian Heimes90aa7642007-12-19 02:45:37 +00003647 if (ABS(Py_SIZE(v)) <= 1)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003648 return PyLong_FromLong(-MEDIUM_VALUE(v));
Tim Peters69c2de32001-09-11 22:31:33 +00003649 z = (PyLongObject *)_PyLong_Copy(v);
3650 if (z != NULL)
Christian Heimes90aa7642007-12-19 02:45:37 +00003651 Py_SIZE(z) = -(Py_SIZE(v));
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003652 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003653}
3654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003655static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003656long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003657{
Christian Heimes90aa7642007-12-19 02:45:37 +00003658 if (Py_SIZE(v) < 0)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003659 return long_neg(v);
Tim Peters69c2de32001-09-11 22:31:33 +00003660 else
Guido van Rossumb43daf72007-08-01 18:08:08 +00003661 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003662}
3663
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003664static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003665long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003666{
Christian Heimes90aa7642007-12-19 02:45:37 +00003667 return ABS(Py_SIZE(v)) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003668}
3669
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003670static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003671long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003672{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003673 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003674 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003675 Py_ssize_t newsize, wordshift, loshift, hishift, i, j;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003676 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003677
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003678 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003679
Christian Heimes90aa7642007-12-19 02:45:37 +00003680 if (Py_SIZE(a) < 0) {
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003681 /* Right shifting negative numbers is harder */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003682 PyLongObject *a1, *a2;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003683 a1 = (PyLongObject *) long_invert(a);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003684 if (a1 == NULL)
3685 goto rshift_error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003686 a2 = (PyLongObject *) long_rshift(a1, b);
3687 Py_DECREF(a1);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003688 if (a2 == NULL)
3689 goto rshift_error;
3690 z = (PyLongObject *) long_invert(a2);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003691 Py_DECREF(a2);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003692 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003693 else {
Tim Peters5af4e6c2002-08-12 02:31:19 +00003694
Neil Schemenauerba872e22001-01-04 01:46:03 +00003695 shiftby = PyLong_AsLong((PyObject *)b);
3696 if (shiftby == -1L && PyErr_Occurred())
3697 goto rshift_error;
3698 if (shiftby < 0) {
3699 PyErr_SetString(PyExc_ValueError,
3700 "negative shift count");
3701 goto rshift_error;
3702 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003703 wordshift = shiftby / PyLong_SHIFT;
Christian Heimes90aa7642007-12-19 02:45:37 +00003704 newsize = ABS(Py_SIZE(a)) - wordshift;
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003705 if (newsize <= 0)
3706 return PyLong_FromLong(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003707 loshift = shiftby % PyLong_SHIFT;
3708 hishift = PyLong_SHIFT - loshift;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003709 lomask = ((digit)1 << hishift) - 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003710 himask = PyLong_MASK ^ lomask;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003711 z = _PyLong_New(newsize);
3712 if (z == NULL)
3713 goto rshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003714 if (Py_SIZE(a) < 0)
3715 Py_SIZE(z) = -(Py_SIZE(z));
Neil Schemenauerba872e22001-01-04 01:46:03 +00003716 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3717 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3718 if (i+1 < newsize)
3719 z->ob_digit[i] |=
3720 (a->ob_digit[j+1] << hishift) & himask;
3721 }
3722 z = long_normalize(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003723 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00003724rshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003725 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003726
Guido van Rossumc6913e71991-11-19 20:26:46 +00003727}
3728
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003729static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003730long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003731{
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003732 /* This version due to Tim Peters */
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003733 PyLongObject *a = (PyLongObject*)v;
3734 PyLongObject *b = (PyLongObject*)w;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003735 PyLongObject *z = NULL;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003736 long shiftby;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003737 Py_ssize_t oldsize, newsize, wordshift, remshift, i, j;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003738 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003739
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003740 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003742 shiftby = PyLong_AsLong((PyObject *)b);
3743 if (shiftby == -1L && PyErr_Occurred())
Neil Schemenauerba872e22001-01-04 01:46:03 +00003744 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003745 if (shiftby < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003746 PyErr_SetString(PyExc_ValueError, "negative shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003747 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003748 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003749 if ((long)(int)shiftby != shiftby) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003750 PyErr_SetString(PyExc_ValueError,
3751 "outrageous left shift count");
Neil Schemenauerba872e22001-01-04 01:46:03 +00003752 goto lshift_error;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003753 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003754 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3755 wordshift = (int)shiftby / PyLong_SHIFT;
3756 remshift = (int)shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003757
Christian Heimes90aa7642007-12-19 02:45:37 +00003758 oldsize = ABS(Py_SIZE(a));
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003759 newsize = oldsize + wordshift;
3760 if (remshift)
3761 ++newsize;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003762 z = _PyLong_New(newsize);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003763 if (z == NULL)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003764 goto lshift_error;
Christian Heimes90aa7642007-12-19 02:45:37 +00003765 if (Py_SIZE(a) < 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00003766 NEGATE(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003767 for (i = 0; i < wordshift; i++)
3768 z->ob_digit[i] = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003769 accum = 0;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003770 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
Tim Peters0d2d87d2002-08-20 19:00:22 +00003771 accum |= (twodigits)a->ob_digit[j] << remshift;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00003772 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3773 accum >>= PyLong_SHIFT;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003774 }
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003775 if (remshift)
3776 z->ob_digit[newsize-1] = (digit)accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003777 else
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003778 assert(!accum);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003779 z = long_normalize(z);
3780lshift_error:
Facundo Batista6e6f59b2008-07-24 18:57:11 +00003781 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003782}
3783
Mark Dickinson27a87a22009-10-25 20:43:34 +00003784/* Compute two's complement of digit vector a[0:m], writing result to
3785 z[0:m]. The digit vector a need not be normalized, but should not
3786 be entirely zero. a and z may point to the same digit vector. */
3787
3788static void
3789v_complement(digit *z, digit *a, Py_ssize_t m)
3790{
3791 Py_ssize_t i;
3792 digit carry = 1;
3793 for (i = 0; i < m; ++i) {
3794 carry += a[i] ^ PyLong_MASK;
3795 z[i] = carry & PyLong_MASK;
3796 carry >>= PyLong_SHIFT;
3797 }
3798 assert(carry == 0);
3799}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003800
3801/* Bitwise and/xor/or operations */
3802
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003803static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003804long_bitwise(PyLongObject *a,
3805 int op, /* '&', '|', '^' */
3806 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003807{
Mark Dickinson27a87a22009-10-25 20:43:34 +00003808 int nega, negb, negz;
Mark Dickinsone4416742009-02-15 15:14:57 +00003809 Py_ssize_t size_a, size_b, size_z, i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003810 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003811
Mark Dickinson27a87a22009-10-25 20:43:34 +00003812 /* Bitwise operations for negative numbers operate as though
3813 on a two's complement representation. So convert arguments
3814 from sign-magnitude to two's complement, and convert the
3815 result back to sign-magnitude at the end. */
3816
3817 /* If a is negative, replace it by its two's complement. */
3818 size_a = ABS(Py_SIZE(a));
3819 nega = Py_SIZE(a) < 0;
3820 if (nega) {
3821 z = _PyLong_New(size_a);
3822 if (z == NULL)
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003823 return NULL;
Mark Dickinson27a87a22009-10-25 20:43:34 +00003824 v_complement(z->ob_digit, a->ob_digit, size_a);
3825 a = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003826 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003827 else
3828 /* Keep reference count consistent. */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003829 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003830
3831 /* Same for b. */
3832 size_b = ABS(Py_SIZE(b));
3833 negb = Py_SIZE(b) < 0;
3834 if (negb) {
3835 z = _PyLong_New(size_b);
3836 if (z == NULL) {
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003837 Py_DECREF(a);
3838 return NULL;
3839 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003840 v_complement(z->ob_digit, b->ob_digit, size_b);
3841 b = z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003842 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00003843 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003844 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003845
Mark Dickinson27a87a22009-10-25 20:43:34 +00003846 /* Swap a and b if necessary to ensure size_a >= size_b. */
3847 if (size_a < size_b) {
3848 z = a; a = b; b = z;
3849 size_z = size_a; size_a = size_b; size_b = size_z;
3850 negz = nega; nega = negb; negb = negz;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003851 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003852
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003853 /* JRH: The original logic here was to allocate the result value (z)
3854 as the longer of the two operands. However, there are some cases
3855 where the result is guaranteed to be shorter than that: AND of two
3856 positives, OR of two negatives: use the shorter number. AND with
3857 mixed signs: use the positive number. OR with mixed signs: use the
Mark Dickinson27a87a22009-10-25 20:43:34 +00003858 negative number.
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003859 */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003860 switch (op) {
3861 case '^':
3862 negz = nega ^ negb;
3863 size_z = size_a;
3864 break;
3865 case '&':
3866 negz = nega & negb;
3867 size_z = negb ? size_a : size_b;
3868 break;
3869 case '|':
3870 negz = nega | negb;
3871 size_z = negb ? size_b : size_a;
3872 break;
3873 default:
3874 PyErr_BadArgument();
3875 return NULL;
3876 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003877
Mark Dickinson27a87a22009-10-25 20:43:34 +00003878 /* We allow an extra digit if z is negative, to make sure that
3879 the final two's complement of z doesn't overflow. */
3880 z = _PyLong_New(size_z + negz);
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003881 if (z == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003882 Py_DECREF(a);
3883 Py_DECREF(b);
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003884 return NULL;
3885 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003886
Mark Dickinson27a87a22009-10-25 20:43:34 +00003887 /* Compute digits for overlap of a and b. */
3888 switch(op) {
3889 case '&':
3890 for (i = 0; i < size_b; ++i)
3891 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3892 break;
3893 case '|':
3894 for (i = 0; i < size_b; ++i)
3895 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3896 break;
3897 case '^':
3898 for (i = 0; i < size_b; ++i)
3899 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3900 break;
3901 default:
3902 PyErr_BadArgument();
3903 return NULL;
3904 }
3905
3906 /* Copy any remaining digits of a, inverting if necessary. */
3907 if (op == '^' && negb)
3908 for (; i < size_z; ++i)
3909 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
3910 else if (i < size_z)
3911 memcpy(&z->ob_digit[i], &a->ob_digit[i],
3912 (size_z-i)*sizeof(digit));
3913
3914 /* Complement result if negative. */
3915 if (negz) {
3916 Py_SIZE(z) = -(Py_SIZE(z));
3917 z->ob_digit[size_z] = PyLong_MASK;
3918 v_complement(z->ob_digit, z->ob_digit, size_z+1);
Guido van Rossumafbb8db1991-12-31 13:14:13 +00003919 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003920
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003921 Py_DECREF(a);
3922 Py_DECREF(b);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003923 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00003924}
3925
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003926static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003927long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003928{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003929 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003930 CHECK_BINOP(a, b);
3931 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003932 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003933}
3934
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003935static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003936long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003937{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003938 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003939 CHECK_BINOP(a, b);
3940 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003941 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003942}
3943
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003944static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003945long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003946{
Neil Schemenauerba872e22001-01-04 01:46:03 +00003947 PyObject *c;
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003948 CHECK_BINOP(a, b);
3949 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003950 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003951}
3952
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003953static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003954long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003955{
Brett Cannonc3647ac2005-04-26 03:45:26 +00003956 if (PyLong_CheckExact(v))
3957 Py_INCREF(v);
3958 else
3959 v = _PyLong_Copy((PyLongObject *)v);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003960 return v;
3961}
3962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003963static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003964long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003965{
Guido van Rossum09e6ad01997-02-14 22:54:21 +00003966 double result;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003967 result = PyLong_AsDouble(v);
Tim Peters9fffa3e2001-09-04 05:14:19 +00003968 if (result == -1.0 && PyErr_Occurred())
3969 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003970 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003971}
3972
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003973static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00003974long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00003975
Tim Peters6d6c1a32001-08-02 04:15:00 +00003976static PyObject *
3977long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3978{
3979 PyObject *x = NULL;
3980 int base = -909; /* unlikely! */
Martin v. Löwis15e62742006-02-27 16:46:16 +00003981 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003982
Guido van Rossumbef14172001-08-29 15:47:46 +00003983 if (type != &PyLong_Type)
3984 return long_subtype_new(type, args, kwds); /* Wimp out */
Guido van Rossumddefaf32007-01-14 03:31:43 +00003985 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003986 &x, &base))
3987 return NULL;
3988 if (x == NULL)
3989 return PyLong_FromLong(0L);
3990 if (base == -909)
3991 return PyNumber_Long(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003992 else if (PyUnicode_Check(x))
3993 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
3994 PyUnicode_GET_SIZE(x),
3995 base);
Christian Heimes72b710a2008-05-26 13:28:38 +00003996 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Guido van Rossumd8faa362007-04-27 19:54:29 +00003997 /* Since PyLong_FromString doesn't have a length parameter,
3998 * check here for possible NULs in the string. */
Guido van Rossum98297ee2007-11-06 21:34:58 +00003999 char *string;
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004000 Py_ssize_t size = Py_SIZE(x);
Christian Heimes9c4756e2008-05-26 13:22:05 +00004001 if (PyByteArray_Check(x))
4002 string = PyByteArray_AS_STRING(x);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004003 else
Christian Heimes72b710a2008-05-26 13:28:38 +00004004 string = PyBytes_AS_STRING(x);
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004005 if (strlen(string) != (size_t)size) {
Guido van Rossum25236212007-08-22 23:28:23 +00004006 /* We only see this if there's a null byte in x,
Guido van Rossum98297ee2007-11-06 21:34:58 +00004007 x is a bytes or buffer, *and* a base is given. */
Guido van Rossumd8faa362007-04-27 19:54:29 +00004008 PyErr_Format(PyExc_ValueError,
Guido van Rossum25236212007-08-22 23:28:23 +00004009 "invalid literal for int() with base %d: %R",
4010 base, x);
Guido van Rossumd8faa362007-04-27 19:54:29 +00004011 return NULL;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004012 }
Guido van Rossum4581ae52007-05-22 21:56:47 +00004013 return PyLong_FromString(string, NULL, base);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004014 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004015 else {
4016 PyErr_SetString(PyExc_TypeError,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004017 "int() can't convert non-string with explicit base");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004018 return NULL;
4019 }
4020}
4021
Guido van Rossumbef14172001-08-29 15:47:46 +00004022/* Wimpy, slow approach to tp_new calls for subtypes of long:
4023 first create a regular long from whatever arguments we got,
4024 then allocate a subtype instance and initialize it from
4025 the regular long. The regular long is then thrown away.
4026*/
4027static PyObject *
4028long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4029{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004030 PyLongObject *tmp, *newobj;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004031 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004032
4033 assert(PyType_IsSubtype(type, &PyLong_Type));
4034 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4035 if (tmp == NULL)
4036 return NULL;
Tim Peters64b5ce32001-09-10 20:52:51 +00004037 assert(PyLong_CheckExact(tmp));
Christian Heimes90aa7642007-12-19 02:45:37 +00004038 n = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004039 if (n < 0)
4040 n = -n;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004041 newobj = (PyLongObject *)type->tp_alloc(type, n);
4042 if (newobj == NULL) {
Raymond Hettingerf4667932003-06-28 20:04:25 +00004043 Py_DECREF(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004044 return NULL;
Raymond Hettingerf4667932003-06-28 20:04:25 +00004045 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004046 assert(PyLong_Check(newobj));
Christian Heimes90aa7642007-12-19 02:45:37 +00004047 Py_SIZE(newobj) = Py_SIZE(tmp);
Guido van Rossumbef14172001-08-29 15:47:46 +00004048 for (i = 0; i < n; i++)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004049 newobj->ob_digit[i] = tmp->ob_digit[i];
Guido van Rossumbef14172001-08-29 15:47:46 +00004050 Py_DECREF(tmp);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004051 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004052}
4053
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004054static PyObject *
4055long_getnewargs(PyLongObject *v)
4056{
4057 return Py_BuildValue("(N)", _PyLong_Copy(v));
4058}
4059
Guido van Rossumb43daf72007-08-01 18:08:08 +00004060static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004061long_get0(PyLongObject *v, void *context) {
4062 return PyLong_FromLong(0L);
4063}
4064
4065static PyObject *
4066long_get1(PyLongObject *v, void *context) {
4067 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004068}
4069
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004070static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004071long__format__(PyObject *self, PyObject *args)
4072{
Eric Smith4a7d76d2008-05-30 18:10:19 +00004073 PyObject *format_spec;
4074
4075 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4076 return NULL;
4077 return _PyLong_FormatAdvanced(self,
4078 PyUnicode_AS_UNICODE(format_spec),
4079 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004080}
4081
Eric Smith8c663262007-08-25 02:26:07 +00004082static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004083long_round(PyObject *self, PyObject *args)
4084{
Mark Dickinson1124e712009-01-28 21:25:58 +00004085 PyObject *o_ndigits=NULL, *temp;
4086 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
4087 int errcode;
4088 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004089
Mark Dickinson1124e712009-01-28 21:25:58 +00004090 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
4091 the straightforward method is:
4092
4093 (1) divide by 10**n
4094 (2) round to nearest integer (round to even in case of tie)
4095 (3) multiply result by 10**n.
4096
4097 But the rounding step involves examining the fractional part of the
4098 quotient to see whether it's greater than 0.5 or not. Since we
4099 want to do the whole calculation in integer arithmetic, it's
4100 simpler to do:
4101
4102 (1) divide by (10**n)/2
4103 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
4104 (3) multiply result by (10**n)/2.
4105
4106 Then all we need to know about the fractional part of the quotient
4107 arising in step (2) is whether it's zero or not.
4108
4109 Doing both a multiplication and division is wasteful, and is easily
4110 avoided if we just figure out how much to adjust the original input
4111 by to do the rounding.
4112
4113 Here's the whole algorithm expressed in Python.
4114
4115 def round(self, ndigits = None):
4116 """round(int, int) -> int"""
4117 if ndigits is None or ndigits >= 0:
4118 return self
4119 pow = 10**-ndigits >> 1
4120 q, r = divmod(self, pow)
4121 self -= r
4122 if (q & 1 != 0):
4123 if (q & 2 == r == 0):
4124 self -= pow
4125 else:
4126 self += pow
4127 return self
4128
4129 */
4130 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4131 return NULL;
4132 if (o_ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004133 return long_long(self);
4134
Mark Dickinson1124e712009-01-28 21:25:58 +00004135 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
4136 if (ndigits == NULL)
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004137 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004138
4139 if (Py_SIZE(ndigits) >= 0) {
4140 Py_DECREF(ndigits);
4141 return long_long(self);
4142 }
4143
4144 Py_INCREF(self); /* to keep refcounting simple */
4145 /* we now own references to self, ndigits */
4146
4147 /* pow = 10 ** -ndigits >> 1 */
4148 pow = (PyLongObject *)PyLong_FromLong(10L);
4149 if (pow == NULL)
4150 goto error;
4151 temp = long_neg(ndigits);
4152 Py_DECREF(ndigits);
4153 ndigits = (PyLongObject *)temp;
4154 if (ndigits == NULL)
4155 goto error;
4156 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4157 Py_DECREF(pow);
4158 pow = (PyLongObject *)temp;
4159 if (pow == NULL)
4160 goto error;
4161 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4162 one = (PyLongObject *)PyLong_FromLong(1L);
4163 if (one == NULL)
4164 goto error;
4165 temp = long_rshift(pow, one);
4166 Py_DECREF(one);
4167 Py_DECREF(pow);
4168 pow = (PyLongObject *)temp;
4169 if (pow == NULL)
4170 goto error;
4171
4172 /* q, r = divmod(self, pow) */
4173 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4174 if (errcode == -1)
4175 goto error;
4176
4177 /* self -= r */
4178 temp = long_sub((PyLongObject *)self, r);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004179 Py_DECREF(self);
Mark Dickinson1124e712009-01-28 21:25:58 +00004180 self = temp;
4181 if (self == NULL)
4182 goto error;
4183
4184 /* get value of quotient modulo 4 */
4185 if (Py_SIZE(q) == 0)
4186 q_mod_4 = 0;
4187 else if (Py_SIZE(q) > 0)
4188 q_mod_4 = q->ob_digit[0] & 3;
4189 else
4190 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
4191
4192 if ((q_mod_4 & 1) == 1) {
4193 /* q is odd; round self up or down by adding or subtracting pow */
4194 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4195 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4196 else
4197 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4198 Py_DECREF(self);
4199 self = temp;
4200 if (self == NULL)
4201 goto error;
4202 }
4203 Py_DECREF(q);
4204 Py_DECREF(r);
4205 Py_DECREF(pow);
4206 Py_DECREF(ndigits);
4207 return self;
4208
4209 error:
4210 Py_XDECREF(q);
4211 Py_XDECREF(r);
4212 Py_XDECREF(pow);
4213 Py_XDECREF(self);
4214 Py_XDECREF(ndigits);
4215 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004216}
4217
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004218static PyObject *
4219long_sizeof(PyLongObject *v)
4220{
4221 Py_ssize_t res;
4222
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004223 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004224 return PyLong_FromSsize_t(res);
4225}
4226
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004227static PyObject *
4228long_bit_length(PyLongObject *v)
4229{
4230 PyLongObject *result, *x, *y;
4231 Py_ssize_t ndigits, msd_bits = 0;
4232 digit msd;
4233
4234 assert(v != NULL);
4235 assert(PyLong_Check(v));
4236
4237 ndigits = ABS(Py_SIZE(v));
4238 if (ndigits == 0)
4239 return PyLong_FromLong(0);
4240
4241 msd = v->ob_digit[ndigits-1];
4242 while (msd >= 32) {
4243 msd_bits += 6;
4244 msd >>= 6;
4245 }
4246 msd_bits += (long)(BitLengthTable[msd]);
4247
4248 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4249 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
4250
4251 /* expression above may overflow; use Python integers instead */
4252 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4253 if (result == NULL)
4254 return NULL;
4255 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4256 if (x == NULL)
4257 goto error;
4258 y = (PyLongObject *)long_mul(result, x);
4259 Py_DECREF(x);
4260 if (y == NULL)
4261 goto error;
4262 Py_DECREF(result);
4263 result = y;
4264
4265 x = (PyLongObject *)PyLong_FromLong(msd_bits);
4266 if (x == NULL)
4267 goto error;
4268 y = (PyLongObject *)long_add(result, x);
4269 Py_DECREF(x);
4270 if (y == NULL)
4271 goto error;
4272 Py_DECREF(result);
4273 result = y;
4274
4275 return (PyObject *)result;
4276
4277error:
4278 Py_DECREF(result);
4279 return NULL;
4280}
4281
4282PyDoc_STRVAR(long_bit_length_doc,
4283"int.bit_length() -> int\n\
4284\n\
4285Number of bits necessary to represent self in binary.\n\
4286>>> bin(37)\n\
4287'0b100101'\n\
4288>>> (37).bit_length()\n\
42896");
4290
Christian Heimes53876d92008-04-19 00:31:39 +00004291#if 0
4292static PyObject *
4293long_is_finite(PyObject *v)
4294{
4295 Py_RETURN_TRUE;
4296}
4297#endif
4298
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004299
4300PyDoc_STRVAR(long_to_bytes_doc,
4301"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
4302\n\
4303Return an array of bytes representing an integer.\n\
4304\n\
4305The integer is represented using length bytes. An OverflowError is\n\
4306raised if the integer is not representable with the given number of\n\
4307bytes.\n\
4308\n\
4309The byteorder argument determines the byte order used to represent the\n\
4310integer. If byteorder is 'big', the most significant byte is at the\n\
4311beginning of the byte array. If byteorder is 'little', the most\n\
4312significant byte is at the end of the byte array. To request the native\n\
4313byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4314\n\
4315The signed keyword-only argument determines whether two's complement is\n\
4316used to represent the integer. If signed is False and a negative integer\n\
4317is given, an OverflowError is raised.");
4318
4319static PyObject *
4320long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4321{
4322 PyObject *byteorder_str;
4323 PyObject *is_signed_obj = NULL;
4324 Py_ssize_t length;
4325 int little_endian;
4326 int is_signed;
4327 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004328 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
4329
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004330 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004331 &length, &byteorder_str,
4332 &is_signed_obj))
4333 return NULL;
4334
4335 if (args != NULL && Py_SIZE(args) > 2) {
4336 PyErr_SetString(PyExc_TypeError,
4337 "'signed' is a keyword-only argument");
4338 return NULL;
4339 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004340
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004341 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004342 little_endian = 1;
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004343 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004344 little_endian = 0;
4345 else {
4346 PyErr_SetString(PyExc_ValueError,
4347 "byteorder must be either 'little' or 'big'");
4348 return NULL;
4349 }
4350
4351 if (is_signed_obj != NULL) {
4352 int cmp = PyObject_IsTrue(is_signed_obj);
4353 if (cmp < 0)
4354 return NULL;
4355 is_signed = cmp ? 1 : 0;
4356 }
4357 else {
4358 /* If the signed argument was omitted, use False as the
4359 default. */
4360 is_signed = 0;
4361 }
4362
4363 if (length < 0) {
4364 PyErr_SetString(PyExc_ValueError,
4365 "length argument must be non-negative");
4366 return NULL;
4367 }
4368
4369 bytes = PyBytes_FromStringAndSize(NULL, length);
4370 if (bytes == NULL)
4371 return NULL;
4372
4373 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4374 length, little_endian, is_signed) < 0) {
4375 Py_DECREF(bytes);
4376 return NULL;
4377 }
4378
4379 return bytes;
4380}
4381
4382PyDoc_STRVAR(long_from_bytes_doc,
4383"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4384\n\
4385Return the integer represented by the given array of bytes.\n\
4386\n\
4387The bytes argument must either support the buffer protocol or be an\n\
4388iterable object producing bytes. Bytes and bytearray are examples of\n\
4389built-in objects that support the buffer protocol.\n\
4390\n\
4391The byteorder argument determines the byte order used to represent the\n\
4392integer. If byteorder is 'big', the most significant byte is at the\n\
4393beginning of the byte array. If byteorder is 'little', the most\n\
4394significant byte is at the end of the byte array. To request the native\n\
4395byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4396\n\
4397The signed keyword-only argument indicates whether two's complement is\n\
4398used to represent the integer.");
4399
4400static PyObject *
4401long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4402{
4403 PyObject *byteorder_str;
4404 PyObject *is_signed_obj = NULL;
4405 int little_endian;
4406 int is_signed;
4407 PyObject *obj;
4408 PyObject *bytes;
4409 PyObject *long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004410 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
4411
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004412 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004413 &obj, &byteorder_str,
4414 &is_signed_obj))
4415 return NULL;
4416
4417 if (args != NULL && Py_SIZE(args) > 2) {
4418 PyErr_SetString(PyExc_TypeError,
4419 "'signed' is a keyword-only argument");
4420 return NULL;
4421 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004422
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004423 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004424 little_endian = 1;
Benjamin Peterson0c0e2292010-01-09 21:50:11 +00004425 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004426 little_endian = 0;
4427 else {
4428 PyErr_SetString(PyExc_ValueError,
4429 "byteorder must be either 'little' or 'big'");
4430 return NULL;
4431 }
4432
4433 if (is_signed_obj != NULL) {
4434 int cmp = PyObject_IsTrue(is_signed_obj);
4435 if (cmp < 0)
4436 return NULL;
4437 is_signed = cmp ? 1 : 0;
4438 }
4439 else {
4440 /* If the signed argument was omitted, use False as the
4441 default. */
4442 is_signed = 0;
4443 }
4444
4445 bytes = PyObject_Bytes(obj);
4446 if (bytes == NULL)
4447 return NULL;
4448
4449 long_obj = _PyLong_FromByteArray(
4450 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4451 little_endian, is_signed);
4452 Py_DECREF(bytes);
4453
4454 /* If from_bytes() was used on subclass, allocate new subclass
4455 * instance, initialize it with decoded long value and return it.
4456 */
4457 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4458 PyLongObject *newobj;
4459 int i;
4460 Py_ssize_t n = ABS(Py_SIZE(long_obj));
4461
4462 newobj = (PyLongObject *)type->tp_alloc(type, n);
4463 if (newobj == NULL) {
4464 Py_DECREF(long_obj);
4465 return NULL;
4466 }
4467 assert(PyLong_Check(newobj));
4468 Py_SIZE(newobj) = Py_SIZE(long_obj);
4469 for (i = 0; i < n; i++) {
4470 newobj->ob_digit[i] =
4471 ((PyLongObject *)long_obj)->ob_digit[i];
4472 }
4473 Py_DECREF(long_obj);
4474 return (PyObject *)newobj;
4475 }
4476
4477 return long_obj;
4478}
4479
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004480static PyMethodDef long_methods[] = {
Guido van Rossumb43daf72007-08-01 18:08:08 +00004481 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4482 "Returns self, the complex conjugate of any int."},
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004483 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4484 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004485#if 0
4486 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4487 "Returns always True."},
4488#endif
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004489 {"to_bytes", (PyCFunction)long_to_bytes,
4490 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4491 {"from_bytes", (PyCFunction)long_from_bytes,
4492 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004493 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4494 "Truncating an Integral returns itself."},
4495 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4496 "Flooring an Integral returns itself."},
4497 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4498 "Ceiling of an Integral returns itself."},
4499 {"__round__", (PyCFunction)long_round, METH_VARARGS,
Mark Dickinson1124e712009-01-28 21:25:58 +00004500 "Rounding an Integral returns itself.\n"
4501 "Rounding with an ndigits argument also returns an integer."},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004502 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
Eric Smith8c663262007-08-25 02:26:07 +00004503 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004504 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4505 "Returns size in memory, in bytes"},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004506 {NULL, NULL} /* sentinel */
4507};
4508
Guido van Rossumb43daf72007-08-01 18:08:08 +00004509static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004510 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004511 (getter)long_long, (setter)NULL,
4512 "the real part of a complex number",
4513 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004514 {"imag",
4515 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004516 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004517 NULL},
4518 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004519 (getter)long_long, (setter)NULL,
4520 "the numerator of a rational number in lowest terms",
4521 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004522 {"denominator",
4523 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004524 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004525 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004526 {NULL} /* Sentinel */
4527};
4528
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004529PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004530"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004531\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004532Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004533point argument will be truncated towards zero (this does not include a\n\
4534string representation of a floating point number!) When converting a\n\
4535string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004536converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004537
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004538static PyNumberMethods long_as_number = {
Tim Peters9f688bf2000-07-07 15:53:28 +00004539 (binaryfunc) long_add, /*nb_add*/
4540 (binaryfunc) long_sub, /*nb_subtract*/
4541 (binaryfunc) long_mul, /*nb_multiply*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004542 long_mod, /*nb_remainder*/
4543 long_divmod, /*nb_divmod*/
4544 long_pow, /*nb_power*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004545 (unaryfunc) long_neg, /*nb_negative*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004546 (unaryfunc) long_long, /*tp_positive*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004547 (unaryfunc) long_abs, /*tp_absolute*/
Jack Diederich4dafcc42006-11-28 19:15:13 +00004548 (inquiry) long_bool, /*tp_bool*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004549 (unaryfunc) long_invert, /*nb_invert*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004550 long_lshift, /*nb_lshift*/
Tim Peters9f688bf2000-07-07 15:53:28 +00004551 (binaryfunc) long_rshift, /*nb_rshift*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004552 long_and, /*nb_and*/
4553 long_xor, /*nb_xor*/
4554 long_or, /*nb_or*/
Guido van Rossumb43daf72007-08-01 18:08:08 +00004555 long_long, /*nb_int*/
Mark Dickinson8055afd2009-01-17 10:04:45 +00004556 0, /*nb_reserved*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004557 long_float, /*nb_float*/
Guido van Rossum4668b002001-08-08 05:00:18 +00004558 0, /* nb_inplace_add */
4559 0, /* nb_inplace_subtract */
4560 0, /* nb_inplace_multiply */
Guido van Rossum4668b002001-08-08 05:00:18 +00004561 0, /* nb_inplace_remainder */
4562 0, /* nb_inplace_power */
4563 0, /* nb_inplace_lshift */
4564 0, /* nb_inplace_rshift */
4565 0, /* nb_inplace_and */
4566 0, /* nb_inplace_xor */
4567 0, /* nb_inplace_or */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004568 long_div, /* nb_floor_divide */
Guido van Rossum4668b002001-08-08 05:00:18 +00004569 long_true_divide, /* nb_true_divide */
4570 0, /* nb_inplace_floor_divide */
4571 0, /* nb_inplace_true_divide */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00004572 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004573};
4574
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004575PyTypeObject PyLong_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00004576 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossumddefaf32007-01-14 03:31:43 +00004577 "int", /* tp_name */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004578 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004579 sizeof(digit), /* tp_itemsize */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004580 long_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004581 0, /* tp_print */
4582 0, /* tp_getattr */
4583 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00004584 0, /* tp_reserved */
Mark Dickinson2031d132009-09-17 00:17:48 +00004585 long_to_decimal_string, /* tp_repr */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004586 &long_as_number, /* tp_as_number */
4587 0, /* tp_as_sequence */
4588 0, /* tp_as_mapping */
4589 (hashfunc)long_hash, /* tp_hash */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004590 0, /* tp_call */
Mark Dickinson2031d132009-09-17 00:17:48 +00004591 long_to_decimal_string, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004592 PyObject_GenericGetAttr, /* tp_getattro */
4593 0, /* tp_setattro */
4594 0, /* tp_as_buffer */
Thomas Wouters27d517b2007-02-25 20:39:11 +00004595 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4596 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004597 long_doc, /* tp_doc */
4598 0, /* tp_traverse */
4599 0, /* tp_clear */
Guido van Rossum47b9ff62006-08-24 00:41:19 +00004600 long_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004601 0, /* tp_weaklistoffset */
4602 0, /* tp_iter */
4603 0, /* tp_iternext */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004604 long_methods, /* tp_methods */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004605 0, /* tp_members */
Guido van Rossumb43daf72007-08-01 18:08:08 +00004606 long_getset, /* tp_getset */
Tim Peters6d6c1a32001-08-02 04:15:00 +00004607 0, /* tp_base */
4608 0, /* tp_dict */
4609 0, /* tp_descr_get */
4610 0, /* tp_descr_set */
4611 0, /* tp_dictoffset */
4612 0, /* tp_init */
4613 0, /* tp_alloc */
4614 long_new, /* tp_new */
Mark Dickinson5a74bf62009-02-15 11:04:38 +00004615 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004616};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004617
Mark Dickinsonbd792642009-03-18 20:06:12 +00004618static PyTypeObject Int_InfoType;
4619
4620PyDoc_STRVAR(int_info__doc__,
4621"sys.int_info\n\
4622\n\
4623A struct sequence that holds information about Python's\n\
4624internal representation of integers. The attributes are read only.");
4625
4626static PyStructSequence_Field int_info_fields[] = {
4627 {"bits_per_digit", "size of a digit in bits"},
4628 {"sizeof_digit", "size in bytes of the C type used to "
4629 "represent a digit"},
4630 {NULL, NULL}
4631};
4632
4633static PyStructSequence_Desc int_info_desc = {
4634 "sys.int_info", /* name */
4635 int_info__doc__, /* doc */
4636 int_info_fields, /* fields */
4637 2 /* number of fields */
4638};
4639
4640PyObject *
4641PyLong_GetInfo(void)
4642{
4643 PyObject* int_info;
4644 int field = 0;
4645 int_info = PyStructSequence_New(&Int_InfoType);
4646 if (int_info == NULL)
4647 return NULL;
Mark Dickinson0bdab682009-04-02 18:41:40 +00004648 PyStructSequence_SET_ITEM(int_info, field++,
4649 PyLong_FromLong(PyLong_SHIFT));
4650 PyStructSequence_SET_ITEM(int_info, field++,
4651 PyLong_FromLong(sizeof(digit)));
Mark Dickinsonbd792642009-03-18 20:06:12 +00004652 if (PyErr_Occurred()) {
4653 Py_CLEAR(int_info);
4654 return NULL;
4655 }
4656 return int_info;
4657}
4658
Guido van Rossumddefaf32007-01-14 03:31:43 +00004659int
4660_PyLong_Init(void)
4661{
4662#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004663 int ival, size;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004664 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004665
4666 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4667 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4668 if (Py_TYPE(v) == &PyLong_Type) {
4669 /* The element is already initialized, most likely
4670 * the Python interpreter was initialized before.
4671 */
Christian Heimes48aa4b12008-02-01 16:56:30 +00004672 Py_ssize_t refcnt;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004673 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004674
Christian Heimes48aa4b12008-02-01 16:56:30 +00004675 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4676 _Py_NewReference(op);
4677 /* _Py_NewReference sets the ref count to 1 but
4678 * the ref count might be larger. Set the refcnt
4679 * to the original refcnt + 1 */
4680 Py_REFCNT(op) = refcnt + 1;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004681 assert(Py_SIZE(op) == size);
4682 assert(v->ob_digit[0] == abs(ival));
4683 }
4684 else {
4685 PyObject_INIT(v, &PyLong_Type);
4686 }
4687 Py_SIZE(v) = size;
4688 v->ob_digit[0] = abs(ival);
Guido van Rossumddefaf32007-01-14 03:31:43 +00004689 }
4690#endif
Mark Dickinsonbd792642009-03-18 20:06:12 +00004691 /* initialize int_info */
4692 if (Int_InfoType.tp_name == 0)
4693 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
4694
Guido van Rossumddefaf32007-01-14 03:31:43 +00004695 return 1;
4696}
4697
4698void
4699PyLong_Fini(void)
4700{
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004701 /* Integers are currently statically allocated. Py_DECREF is not
4702 needed, but Python must forget about the reference or multiple
4703 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004704#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004705 int i;
4706 PyLongObject *v = small_ints;
4707 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4708 _Py_DEC_REFTOTAL;
4709 _Py_ForgetReference((PyObject*)v);
4710 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004711#endif
4712}