blob: ca069f60dcae390129f6f5eaf9669f060d2c475a [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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000015#endif
16#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#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 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021#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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000042#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
50#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
52 return get_small_int((sdigit)ival); \
53 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000056maybe_small_long(PyLongObject *v)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (v && ABS(Py_SIZE(v)) <= 1) {
59 sdigit ival = MEDIUM_VALUE(v);
60 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066}
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) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
76 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
77 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 Pitrouf95a1b32010-05-09 15:52:27 +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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 Py_ssize_t j = ABS(Py_SIZE(v));
109 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 while (i > 0 && v->ob_digit[i-1] == 0)
112 --i;
113 if (i != j)
114 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
115 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000116}
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 \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000123
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyLongObject *result;
128 /* 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. */
133 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
134 PyErr_SetString(PyExc_OverflowError,
135 "too many digits in integer");
136 return NULL;
137 }
138 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
139 size*sizeof(digit));
140 if (!result) {
141 PyErr_NoMemory();
142 return NULL;
143 }
144 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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 PyLongObject *result;
151 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 assert(src != NULL);
154 i = Py_SIZE(src);
155 if (i < 0)
156 i = -(i);
157 if (i < 2) {
158 sdigit ival = src->ob_digit[0];
159 if (Py_SIZE(src) < 0)
160 ival = -ival;
161 CHECK_SMALL_INT(ival);
162 }
163 result = _PyLong_New(i);
164 if (result != NULL) {
165 Py_SIZE(result) = Py_SIZE(src);
166 while (--i >= 0)
167 result->ob_digit[i] = src->ob_digit[i];
168 }
169 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000170}
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 PyLongObject *v;
178 unsigned long abs_ival;
179 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
180 int ndigits = 0;
181 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 if (ival < 0) {
186 /* 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;
189 sign = -1;
190 }
191 else {
192 abs_ival = (unsigned long)ival;
193 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* Fast path for single-digit ints */
196 if (!(abs_ival >> PyLong_SHIFT)) {
197 v = _PyLong_New(1);
198 if (v) {
199 Py_SIZE(v) = sign;
200 v->ob_digit[0] = Py_SAFE_DOWNCAST(
201 abs_ival, unsigned long, digit);
202 }
203 return (PyObject*)v;
204 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000205
Mark Dickinson249b8982009-04-27 19:41:00 +0000206#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* 2 digits */
208 if (!(abs_ival >> 2*PyLong_SHIFT)) {
209 v = _PyLong_New(2);
210 if (v) {
211 Py_SIZE(v) = 2*sign;
212 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);
216 }
217 return (PyObject*)v;
218 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000219#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 /* Larger numbers: loop to determine number of digits */
222 t = abs_ival;
223 while (t) {
224 ++ndigits;
225 t >>= PyLong_SHIFT;
226 }
227 v = _PyLong_New(ndigits);
228 if (v != NULL) {
229 digit *p = v->ob_digit;
230 Py_SIZE(v) = ndigits*sign;
231 t = abs_ival;
232 while (t) {
233 *p++ = Py_SAFE_DOWNCAST(
234 t & PyLong_MASK, unsigned long, digit);
235 t >>= PyLong_SHIFT;
236 }
237 }
238 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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyLongObject *v;
247 unsigned long t;
248 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (ival < PyLong_BASE)
251 return PyLong_FromLong(ival);
252 /* Count the number of Python digits. */
253 t = (unsigned long)ival;
254 while (t) {
255 ++ndigits;
256 t >>= PyLong_SHIFT;
257 }
258 v = _PyLong_New(ndigits);
259 if (v != NULL) {
260 digit *p = v->ob_digit;
261 Py_SIZE(v) = ndigits;
262 while (ival) {
263 *p++ = (digit)(ival & PyLong_MASK);
264 ival >>= PyLong_SHIFT;
265 }
266 }
267 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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 PyLongObject *v;
276 double frac;
277 int i, ndig, expo, neg;
278 neg = 0;
279 if (Py_IS_INFINITY(dval)) {
280 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000281 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return NULL;
283 }
284 if (Py_IS_NAN(dval)) {
285 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000286 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return NULL;
288 }
289 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)
295 return PyLong_FromLong(0L);
296 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
297 v = _PyLong_New(ndig);
298 if (v == NULL)
299 return NULL;
300 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
301 for (i = ndig; --i >= 0; ) {
302 digit bits = (digit)frac;
303 v->ob_digit[i] = bits;
304 frac = frac - (double)bits;
305 frac = ldexp(frac, PyLong_SHIFT);
306 }
307 if (neg)
308 Py_SIZE(v) = -(Py_SIZE(v));
309 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 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
322#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323
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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 /* This version by Tim Peters */
331 register PyLongObject *v;
332 unsigned long x, prev;
333 long res;
334 Py_ssize_t i;
335 int sign;
336 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 *overflow = 0;
339 if (vv == NULL) {
340 PyErr_BadInternalCall();
341 return -1;
342 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (!PyLong_Check(vv)) {
345 PyNumberMethods *nb;
346 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");
350 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 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 res = -1;
365 v = (PyLongObject *)vv;
366 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 switch (i) {
369 case -1:
370 res = -(sdigit)v->ob_digit[0];
371 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;
387 x = (x << PyLong_SHIFT) | v->ob_digit[i];
388 if ((x >> PyLong_SHIFT) != prev) {
389 *overflow = sign;
390 goto exit;
391 }
392 }
393 /* Haven't lost any bits, but casting to long requires extra
394 * care (see comment above).
395 */
396 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 {
403 *overflow = sign;
404 /* res is already set to -1 */
405 }
406 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000407 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (do_decref) {
409 Py_DECREF(vv);
410 }
411 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000412}
413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000415PyLong_AsLong(PyObject *obj)
416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 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;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000426}
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) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 register PyLongObject *v;
434 size_t x, prev;
435 Py_ssize_t i;
436 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (vv == NULL) {
439 PyErr_BadInternalCall();
440 return -1;
441 }
442 if (!PyLong_Check(vv)) {
443 PyErr_SetString(PyExc_TypeError, "an integer is required");
444 return -1;
445 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 v = (PyLongObject *)vv;
448 i = Py_SIZE(v);
449 switch (i) {
450 case -1: return -(sdigit)v->ob_digit[0];
451 case 0: return 0;
452 case 1: return v->ob_digit[0];
453 }
454 sign = 1;
455 x = 0;
456 if (i < 0) {
457 sign = -1;
458 i = -(i);
459 }
460 while (--i >= 0) {
461 prev = x;
462 x = (x << PyLong_SHIFT) | v->ob_digit[i];
463 if ((x >> PyLong_SHIFT) != prev)
464 goto overflow;
465 }
466 /* Haven't lost any bits, but casting to a signed type requires
467 * extra care (see comment above).
468 */
469 if (x <= (size_t)PY_SSIZE_T_MAX) {
470 return (Py_ssize_t)x * sign;
471 }
472 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
473 return PY_SSIZE_T_MIN;
474 }
475 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000476
Mark Dickinson22b20182010-05-10 21:27:53 +0000477 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyErr_SetString(PyExc_OverflowError,
479 "Python int too large to convert to C ssize_t");
480 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000481}
482
Guido van Rossumd8c80482002-08-13 00:24:58 +0000483/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000484 Returns -1 and sets an error condition if overflow occurs. */
485
486unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000487PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 register PyLongObject *v;
490 unsigned long x, prev;
491 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (vv == NULL) {
494 PyErr_BadInternalCall();
495 return (unsigned long)-1;
496 }
497 if (!PyLong_Check(vv)) {
498 PyErr_SetString(PyExc_TypeError, "an integer is required");
499 return (unsigned long)-1;
500 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 v = (PyLongObject *)vv;
503 i = Py_SIZE(v);
504 x = 0;
505 if (i < 0) {
506 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000507 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return (unsigned long) -1;
509 }
510 switch (i) {
511 case 0: return 0;
512 case 1: return v->ob_digit[0];
513 }
514 while (--i >= 0) {
515 prev = x;
516 x = (x << PyLong_SHIFT) | v->ob_digit[i];
517 if ((x >> PyLong_SHIFT) != prev) {
518 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000519 "python int too large to convert "
520 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return (unsigned long) -1;
522 }
523 }
524 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000525}
526
527/* Get a C unsigned long int from a long int object.
528 Returns -1 and sets an error condition if overflow occurs. */
529
530size_t
531PyLong_AsSize_t(PyObject *vv)
532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 register PyLongObject *v;
534 size_t x, prev;
535 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (vv == NULL) {
538 PyErr_BadInternalCall();
539 return (size_t) -1;
540 }
541 if (!PyLong_Check(vv)) {
542 PyErr_SetString(PyExc_TypeError, "an integer is required");
543 return (size_t)-1;
544 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 v = (PyLongObject *)vv;
547 i = Py_SIZE(v);
548 x = 0;
549 if (i < 0) {
550 PyErr_SetString(PyExc_OverflowError,
551 "can't convert negative value to size_t");
552 return (size_t) -1;
553 }
554 switch (i) {
555 case 0: return 0;
556 case 1: return v->ob_digit[0];
557 }
558 while (--i >= 0) {
559 prev = x;
560 x = (x << PyLong_SHIFT) | v->ob_digit[i];
561 if ((x >> PyLong_SHIFT) != prev) {
562 PyErr_SetString(PyExc_OverflowError,
563 "Python int too large to convert to C size_t");
564 return (unsigned long) -1;
565 }
566 }
567 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000568}
569
Thomas Hellera4ea6032003-04-17 18:55:45 +0000570/* Get a C unsigned long int from a long int object, ignoring the high bits.
571 Returns -1 and sets an error condition if an error occurs. */
572
Guido van Rossumddefaf32007-01-14 03:31:43 +0000573static unsigned long
574_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 register PyLongObject *v;
577 unsigned long x;
578 Py_ssize_t i;
579 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (vv == NULL || !PyLong_Check(vv)) {
582 PyErr_BadInternalCall();
583 return (unsigned long) -1;
584 }
585 v = (PyLongObject *)vv;
586 i = Py_SIZE(v);
587 switch (i) {
588 case 0: return 0;
589 case 1: return v->ob_digit[0];
590 }
591 sign = 1;
592 x = 0;
593 if (i < 0) {
594 sign = -1;
595 i = -i;
596 }
597 while (--i >= 0) {
598 x = (x << PyLong_SHIFT) | v->ob_digit[i];
599 }
600 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000601}
602
Guido van Rossumddefaf32007-01-14 03:31:43 +0000603unsigned long
604PyLong_AsUnsignedLongMask(register PyObject *op)
605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyNumberMethods *nb;
607 PyLongObject *lo;
608 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (op && PyLong_Check(op))
611 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
614 nb->nb_int == NULL) {
615 PyErr_SetString(PyExc_TypeError, "an integer is required");
616 return (unsigned long)-1;
617 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 lo = (PyLongObject*) (*nb->nb_int) (op);
620 if (lo == NULL)
621 return (unsigned long)-1;
622 if (PyLong_Check(lo)) {
623 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
624 Py_DECREF(lo);
625 if (PyErr_Occurred())
626 return (unsigned long)-1;
627 return val;
628 }
629 else
630 {
631 Py_DECREF(lo);
632 PyErr_SetString(PyExc_TypeError,
633 "nb_int should return int object");
634 return (unsigned long)-1;
635 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000636}
637
Tim Peters5b8132f2003-01-31 15:52:05 +0000638int
639_PyLong_Sign(PyObject *vv)
640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 assert(v != NULL);
644 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000647}
648
Tim Petersbaefd9e2003-01-28 20:37:45 +0000649size_t
650_PyLong_NumBits(PyObject *vv)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyLongObject *v = (PyLongObject *)vv;
653 size_t result = 0;
654 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 assert(v != NULL);
657 assert(PyLong_Check(v));
658 ndigits = ABS(Py_SIZE(v));
659 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
660 if (ndigits > 0) {
661 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 result = (ndigits - 1) * PyLong_SHIFT;
664 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
665 goto Overflow;
666 do {
667 ++result;
668 if (result == 0)
669 goto Overflow;
670 msd >>= 1;
671 } while (msd);
672 }
673 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000674
Mark Dickinson22b20182010-05-10 21:27:53 +0000675 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
677 "to express in a platform size_t");
678 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000679}
680
Tim Peters2a9b3672001-06-11 21:23:58 +0000681PyObject *
682_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000684{
Mark Dickinson22b20182010-05-10 21:27:53 +0000685 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 int incr; /* direction to move pstartbyte */
687 const unsigned char* pendbyte; /* MSB of bytes */
688 size_t numsignificantbytes; /* number of bytes that matter */
689 Py_ssize_t ndigits; /* number of Python long digits */
690 PyLongObject* v; /* result */
691 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (n == 0)
694 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (little_endian) {
697 pstartbyte = bytes;
698 pendbyte = bytes + n - 1;
699 incr = 1;
700 }
701 else {
702 pstartbyte = bytes + n - 1;
703 pendbyte = bytes;
704 incr = -1;
705 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (is_signed)
708 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* Compute numsignificantbytes. This consists of finding the most
711 significant byte. Leading 0 bytes are insignficant if the number
712 is positive, and leading 0xff bytes if negative. */
713 {
714 size_t i;
715 const unsigned char* p = pendbyte;
716 const int pincr = -incr; /* search MSB to LSB */
717 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 for (i = 0; i < n; ++i, p += pincr) {
720 if (*p != insignficant)
721 break;
722 }
723 numsignificantbytes = n - i;
724 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
725 actually has 2 significant bytes. OTOH, 0xff0001 ==
726 -0x00ffff, so we wouldn't *need* to bump it there; but we
727 do for 0xffff = -0x0001. To be safe without bothering to
728 check every case, bump it regardless. */
729 if (is_signed && numsignificantbytes < n)
730 ++numsignificantbytes;
731 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 /* How many Python long digits do we need? We have
734 8*numsignificantbytes bits, and each Python long digit has
735 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
736 /* catch overflow before it happens */
737 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
738 PyErr_SetString(PyExc_OverflowError,
739 "byte array too long to convert to int");
740 return NULL;
741 }
742 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
743 v = _PyLong_New(ndigits);
744 if (v == NULL)
745 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 /* Copy the bits over. The tricky parts are computing 2's-comp on
748 the fly for signed numbers, and dealing with the mismatch between
749 8-bit bytes and (probably) 15-bit Python digits.*/
750 {
751 size_t i;
752 twodigits carry = 1; /* for 2's-comp calculation */
753 twodigits accum = 0; /* sliding register */
754 unsigned int accumbits = 0; /* number of bits in accum */
755 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
758 twodigits thisbyte = *p;
759 /* Compute correction for 2's comp, if needed. */
760 if (is_signed) {
761 thisbyte = (0xff ^ thisbyte) + carry;
762 carry = thisbyte >> 8;
763 thisbyte &= 0xff;
764 }
765 /* Because we're going LSB to MSB, thisbyte is
766 more significant than what's already in accum,
767 so needs to be prepended to accum. */
768 accum |= (twodigits)thisbyte << accumbits;
769 accumbits += 8;
770 if (accumbits >= PyLong_SHIFT) {
771 /* There's enough to fill a Python digit. */
772 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000773 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 ++idigit;
775 accum >>= PyLong_SHIFT;
776 accumbits -= PyLong_SHIFT;
777 assert(accumbits < PyLong_SHIFT);
778 }
779 }
780 assert(accumbits < PyLong_SHIFT);
781 if (accumbits) {
782 assert(idigit < ndigits);
783 v->ob_digit[idigit] = (digit)accum;
784 ++idigit;
785 }
786 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_SIZE(v) = is_signed ? -idigit : idigit;
789 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000790}
791
792int
793_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 unsigned char* bytes, size_t n,
795 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000798 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000800 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
802 digit carry; /* for computing 2's-comp */
803 size_t j; /* # bytes filled */
804 unsigned char* p; /* pointer to next byte in bytes */
805 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (Py_SIZE(v) < 0) {
810 ndigits = -(Py_SIZE(v));
811 if (!is_signed) {
812 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000813 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 return -1;
815 }
816 do_twos_comp = 1;
817 }
818 else {
819 ndigits = Py_SIZE(v);
820 do_twos_comp = 0;
821 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (little_endian) {
824 p = bytes;
825 pincr = 1;
826 }
827 else {
828 p = bytes + n - 1;
829 pincr = -1;
830 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 /* Copy over all the Python digits.
833 It's crucial that every Python digit except for the MSD contribute
834 exactly PyLong_SHIFT bits to the total, so first assert that the long is
835 normalized. */
836 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
837 j = 0;
838 accum = 0;
839 accumbits = 0;
840 carry = do_twos_comp ? 1 : 0;
841 for (i = 0; i < ndigits; ++i) {
842 digit thisdigit = v->ob_digit[i];
843 if (do_twos_comp) {
844 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
845 carry = thisdigit >> PyLong_SHIFT;
846 thisdigit &= PyLong_MASK;
847 }
848 /* Because we're going LSB to MSB, thisdigit is more
849 significant than what's already in accum, so needs to be
850 prepended to accum. */
851 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* The most-significant digit may be (probably is) at least
854 partly empty. */
855 if (i == ndigits - 1) {
856 /* Count # of sign bits -- they needn't be stored,
857 * although for signed conversion we need later to
858 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 while (s != 0) {
861 s >>= 1;
862 accumbits++;
863 }
864 }
865 else
866 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 /* Store as many bytes as possible. */
869 while (accumbits >= 8) {
870 if (j >= n)
871 goto Overflow;
872 ++j;
873 *p = (unsigned char)(accum & 0xff);
874 p += pincr;
875 accumbits -= 8;
876 accum >>= 8;
877 }
878 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* Store the straggler (if any). */
881 assert(accumbits < 8);
882 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
883 if (accumbits > 0) {
884 if (j >= n)
885 goto Overflow;
886 ++j;
887 if (do_twos_comp) {
888 /* Fill leading bits of the byte with sign bits
889 (appropriately pretending that the long had an
890 infinite supply of sign bits). */
891 accum |= (~(twodigits)0) << accumbits;
892 }
893 *p = (unsigned char)(accum & 0xff);
894 p += pincr;
895 }
896 else if (j == n && n > 0 && is_signed) {
897 /* The main loop filled the byte array exactly, so the code
898 just above didn't get to ensure there's a sign bit, and the
899 loop below wouldn't add one either. Make sure a sign bit
900 exists. */
901 unsigned char msb = *(p - pincr);
902 int sign_bit_set = msb >= 0x80;
903 assert(accumbits == 0);
904 if (sign_bit_set == do_twos_comp)
905 return 0;
906 else
907 goto Overflow;
908 }
Tim Peters05607ad2001-06-13 21:01:27 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Fill remaining bytes with copies of the sign bit. */
911 {
912 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
913 for ( ; j < n; ++j, p += pincr)
914 *p = signbyte;
915 }
Tim Peters05607ad2001-06-13 21:01:27 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000918
Mark Dickinson22b20182010-05-10 21:27:53 +0000919 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
921 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000922
Tim Peters2a9b3672001-06-11 21:23:58 +0000923}
924
Guido van Rossum78694d91998-09-18 14:14:13 +0000925/* Create a new long (or int) object from a C pointer */
926
927PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000928PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000929{
Tim Peters70128a12001-06-16 08:48:40 +0000930#ifndef HAVE_LONG_LONG
931# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
932#endif
933#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000934# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000935#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* special-case null pointer */
937 if (!p)
938 return PyLong_FromLong(0);
939 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000940
Guido van Rossum78694d91998-09-18 14:14:13 +0000941}
942
943/* Get a C pointer from a long object (or an int object in some cases) */
944
945void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000946PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* This function will allow int or long objects. If vv is neither,
949 then the PyLong_AsLong*() functions will raise the exception:
950 PyExc_SystemError, "bad argument to internal function"
951 */
Tim Peters70128a12001-06-16 08:48:40 +0000952#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
956 x = PyLong_AsLong(vv);
957 else
958 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000959#else
Tim Peters70128a12001-06-16 08:48:40 +0000960
961#ifndef HAVE_LONG_LONG
962# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
963#endif
964#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000965# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000966#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
970 x = PyLong_AsLongLong(vv);
971 else
972 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000973
974#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (x == -1 && PyErr_Occurred())
977 return NULL;
978 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000979}
980
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000981#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000982
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000983/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000984 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000985 */
986
Tim Peterscf37dfc2001-06-14 18:42:50 +0000987#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000988#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000989
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000991
992PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000993PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyLongObject *v;
996 unsigned PY_LONG_LONG abs_ival;
997 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
998 int ndigits = 0;
999 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 CHECK_SMALL_INT(ival);
1002 if (ival < 0) {
1003 /* avoid signed overflow on negation; see comments
1004 in PyLong_FromLong above. */
1005 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1006 negative = 1;
1007 }
1008 else {
1009 abs_ival = (unsigned PY_LONG_LONG)ival;
1010 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 /* Count the number of Python digits.
1013 We used to pick 5 ("big enough for anything"), but that's a
1014 waste of time and space given that 5*15 = 75 bits are rarely
1015 needed. */
1016 t = abs_ival;
1017 while (t) {
1018 ++ndigits;
1019 t >>= PyLong_SHIFT;
1020 }
1021 v = _PyLong_New(ndigits);
1022 if (v != NULL) {
1023 digit *p = v->ob_digit;
1024 Py_SIZE(v) = negative ? -ndigits : ndigits;
1025 t = abs_ival;
1026 while (t) {
1027 *p++ = (digit)(t & PyLong_MASK);
1028 t >>= PyLong_SHIFT;
1029 }
1030 }
1031 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001032}
1033
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001034/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001035
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001036PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001037PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 PyLongObject *v;
1040 unsigned PY_LONG_LONG t;
1041 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (ival < PyLong_BASE)
1044 return PyLong_FromLong((long)ival);
1045 /* Count the number of Python digits. */
1046 t = (unsigned PY_LONG_LONG)ival;
1047 while (t) {
1048 ++ndigits;
1049 t >>= PyLong_SHIFT;
1050 }
1051 v = _PyLong_New(ndigits);
1052 if (v != NULL) {
1053 digit *p = v->ob_digit;
1054 Py_SIZE(v) = ndigits;
1055 while (ival) {
1056 *p++ = (digit)(ival & PyLong_MASK);
1057 ival >>= PyLong_SHIFT;
1058 }
1059 }
1060 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001061}
1062
Martin v. Löwis18e16552006-02-15 17:27:45 +00001063/* Create a new long int object from a C Py_ssize_t. */
1064
1065PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001066PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyLongObject *v;
1069 size_t abs_ival;
1070 size_t t; /* unsigned so >> doesn't propagate sign bit */
1071 int ndigits = 0;
1072 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 CHECK_SMALL_INT(ival);
1075 if (ival < 0) {
1076 /* avoid signed overflow when ival = SIZE_T_MIN */
1077 abs_ival = (size_t)(-1-ival)+1;
1078 negative = 1;
1079 }
1080 else {
1081 abs_ival = (size_t)ival;
1082 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* Count the number of Python digits. */
1085 t = abs_ival;
1086 while (t) {
1087 ++ndigits;
1088 t >>= PyLong_SHIFT;
1089 }
1090 v = _PyLong_New(ndigits);
1091 if (v != NULL) {
1092 digit *p = v->ob_digit;
1093 Py_SIZE(v) = negative ? -ndigits : ndigits;
1094 t = abs_ival;
1095 while (t) {
1096 *p++ = (digit)(t & PyLong_MASK);
1097 t >>= PyLong_SHIFT;
1098 }
1099 }
1100 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001101}
1102
1103/* Create a new long int object from a C size_t. */
1104
1105PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001106PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyLongObject *v;
1109 size_t t;
1110 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (ival < PyLong_BASE)
1113 return PyLong_FromLong((long)ival);
1114 /* Count the number of Python digits. */
1115 t = ival;
1116 while (t) {
1117 ++ndigits;
1118 t >>= PyLong_SHIFT;
1119 }
1120 v = _PyLong_New(ndigits);
1121 if (v != NULL) {
1122 digit *p = v->ob_digit;
1123 Py_SIZE(v) = ndigits;
1124 while (ival) {
1125 *p++ = (digit)(ival & PyLong_MASK);
1126 ival >>= PyLong_SHIFT;
1127 }
1128 }
1129 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001130}
1131
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001132/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001133 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001134
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001135PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001136PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyLongObject *v;
1139 PY_LONG_LONG bytes;
1140 int one = 1;
1141 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (vv == NULL) {
1144 PyErr_BadInternalCall();
1145 return -1;
1146 }
1147 if (!PyLong_Check(vv)) {
1148 PyNumberMethods *nb;
1149 PyObject *io;
1150 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1151 nb->nb_int == NULL) {
1152 PyErr_SetString(PyExc_TypeError, "an integer is required");
1153 return -1;
1154 }
1155 io = (*nb->nb_int) (vv);
1156 if (io == NULL)
1157 return -1;
1158 if (PyLong_Check(io)) {
1159 bytes = PyLong_AsLongLong(io);
1160 Py_DECREF(io);
1161 return bytes;
1162 }
1163 Py_DECREF(io);
1164 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1165 return -1;
1166 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 v = (PyLongObject*)vv;
1169 switch(Py_SIZE(v)) {
1170 case -1: return -(sdigit)v->ob_digit[0];
1171 case 0: return 0;
1172 case 1: return v->ob_digit[0];
1173 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001174 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1175 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1178 if (res < 0)
1179 return (PY_LONG_LONG)-1;
1180 else
1181 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001182}
1183
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001184/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001185 Return -1 and set an error if overflow occurs. */
1186
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001187unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001188PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 PyLongObject *v;
1191 unsigned PY_LONG_LONG bytes;
1192 int one = 1;
1193 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (vv == NULL || !PyLong_Check(vv)) {
1196 PyErr_BadInternalCall();
1197 return (unsigned PY_LONG_LONG)-1;
1198 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 v = (PyLongObject*)vv;
1201 switch(Py_SIZE(v)) {
1202 case 0: return 0;
1203 case 1: return v->ob_digit[0];
1204 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001205
Mark Dickinson22b20182010-05-10 21:27:53 +00001206 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1207 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1210 if (res < 0)
1211 return (unsigned PY_LONG_LONG)res;
1212 else
1213 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001214}
Tim Petersd1a7da62001-06-13 00:35:57 +00001215
Thomas Hellera4ea6032003-04-17 18:55:45 +00001216/* Get a C unsigned long int from a long int object, ignoring the high bits.
1217 Returns -1 and sets an error condition if an error occurs. */
1218
Guido van Rossumddefaf32007-01-14 03:31:43 +00001219static unsigned PY_LONG_LONG
1220_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 register PyLongObject *v;
1223 unsigned PY_LONG_LONG x;
1224 Py_ssize_t i;
1225 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (vv == NULL || !PyLong_Check(vv)) {
1228 PyErr_BadInternalCall();
1229 return (unsigned long) -1;
1230 }
1231 v = (PyLongObject *)vv;
1232 switch(Py_SIZE(v)) {
1233 case 0: return 0;
1234 case 1: return v->ob_digit[0];
1235 }
1236 i = Py_SIZE(v);
1237 sign = 1;
1238 x = 0;
1239 if (i < 0) {
1240 sign = -1;
1241 i = -i;
1242 }
1243 while (--i >= 0) {
1244 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1245 }
1246 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001247}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001248
1249unsigned PY_LONG_LONG
1250PyLong_AsUnsignedLongLongMask(register PyObject *op)
1251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyNumberMethods *nb;
1253 PyLongObject *lo;
1254 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (op && PyLong_Check(op))
1257 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1260 nb->nb_int == NULL) {
1261 PyErr_SetString(PyExc_TypeError, "an integer is required");
1262 return (unsigned PY_LONG_LONG)-1;
1263 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 lo = (PyLongObject*) (*nb->nb_int) (op);
1266 if (lo == NULL)
1267 return (unsigned PY_LONG_LONG)-1;
1268 if (PyLong_Check(lo)) {
1269 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1270 Py_DECREF(lo);
1271 if (PyErr_Occurred())
1272 return (unsigned PY_LONG_LONG)-1;
1273 return val;
1274 }
1275 else
1276 {
1277 Py_DECREF(lo);
1278 PyErr_SetString(PyExc_TypeError,
1279 "nb_int should return int object");
1280 return (unsigned PY_LONG_LONG)-1;
1281 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001282}
Tim Petersd1a7da62001-06-13 00:35:57 +00001283#undef IS_LITTLE_ENDIAN
1284
Mark Dickinson93f562c2010-01-30 10:30:15 +00001285/* Get a C long long int from a Python long or Python int object.
1286 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1287 on the sign of the result. Otherwise *overflow is 0.
1288
1289 For other errors (e.g., type error), returns -1 and sets an error
1290 condition.
1291*/
1292
1293PY_LONG_LONG
1294PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 /* This version by Tim Peters */
1297 register PyLongObject *v;
1298 unsigned PY_LONG_LONG x, prev;
1299 PY_LONG_LONG res;
1300 Py_ssize_t i;
1301 int sign;
1302 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 *overflow = 0;
1305 if (vv == NULL) {
1306 PyErr_BadInternalCall();
1307 return -1;
1308 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!PyLong_Check(vv)) {
1311 PyNumberMethods *nb;
1312 nb = vv->ob_type->tp_as_number;
1313 if (nb == NULL || nb->nb_int == NULL) {
1314 PyErr_SetString(PyExc_TypeError,
1315 "an integer is required");
1316 return -1;
1317 }
1318 vv = (*nb->nb_int) (vv);
1319 if (vv == NULL)
1320 return -1;
1321 do_decref = 1;
1322 if (!PyLong_Check(vv)) {
1323 Py_DECREF(vv);
1324 PyErr_SetString(PyExc_TypeError,
1325 "nb_int should return int object");
1326 return -1;
1327 }
1328 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 res = -1;
1331 v = (PyLongObject *)vv;
1332 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 switch (i) {
1335 case -1:
1336 res = -(sdigit)v->ob_digit[0];
1337 break;
1338 case 0:
1339 res = 0;
1340 break;
1341 case 1:
1342 res = v->ob_digit[0];
1343 break;
1344 default:
1345 sign = 1;
1346 x = 0;
1347 if (i < 0) {
1348 sign = -1;
1349 i = -(i);
1350 }
1351 while (--i >= 0) {
1352 prev = x;
1353 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1354 if ((x >> PyLong_SHIFT) != prev) {
1355 *overflow = sign;
1356 goto exit;
1357 }
1358 }
1359 /* Haven't lost any bits, but casting to long requires extra
1360 * care (see comment above).
1361 */
1362 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1363 res = (PY_LONG_LONG)x * sign;
1364 }
1365 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1366 res = PY_LLONG_MIN;
1367 }
1368 else {
1369 *overflow = sign;
1370 /* res is already set to -1 */
1371 }
1372 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001373 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 if (do_decref) {
1375 Py_DECREF(vv);
1376 }
1377 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001378}
1379
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001380#endif /* HAVE_LONG_LONG */
1381
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00001382#define CHECK_BINOP(v,w) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1384 Py_INCREF(Py_NotImplemented); \
1385 return Py_NotImplemented; \
1386 }
Neil Schemenauerba872e22001-01-04 01:46:03 +00001387
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001388/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1389 2**k if d is nonzero, else 0. */
1390
1391static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1393 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001394};
1395
1396static int
1397bits_in_digit(digit d)
1398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 int d_bits = 0;
1400 while (d >= 32) {
1401 d_bits += 6;
1402 d >>= 6;
1403 }
1404 d_bits += (int)BitLengthTable[d];
1405 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001406}
1407
Tim Peters877a2122002-08-12 05:09:36 +00001408/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1409 * is modified in place, by adding y to it. Carries are propagated as far as
1410 * x[m-1], and the remaining carry (0 or 1) is returned.
1411 */
1412static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001413v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 Py_ssize_t i;
1416 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 assert(m >= n);
1419 for (i = 0; i < n; ++i) {
1420 carry += x[i] + y[i];
1421 x[i] = carry & PyLong_MASK;
1422 carry >>= PyLong_SHIFT;
1423 assert((carry & 1) == carry);
1424 }
1425 for (; carry && i < m; ++i) {
1426 carry += x[i];
1427 x[i] = carry & PyLong_MASK;
1428 carry >>= PyLong_SHIFT;
1429 assert((carry & 1) == carry);
1430 }
1431 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001432}
1433
1434/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1435 * is modified in place, by subtracting y from it. Borrows are propagated as
1436 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1437 */
1438static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001439v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_ssize_t i;
1442 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 assert(m >= n);
1445 for (i = 0; i < n; ++i) {
1446 borrow = x[i] - y[i] - borrow;
1447 x[i] = borrow & PyLong_MASK;
1448 borrow >>= PyLong_SHIFT;
1449 borrow &= 1; /* keep only 1 sign bit */
1450 }
1451 for (; borrow && i < m; ++i) {
1452 borrow = x[i] - borrow;
1453 x[i] = borrow & PyLong_MASK;
1454 borrow >>= PyLong_SHIFT;
1455 borrow &= 1;
1456 }
1457 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001458}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001459
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001460/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1461 * result in z[0:m], and return the d bits shifted out of the top.
1462 */
1463static digit
1464v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 Py_ssize_t i;
1467 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 assert(0 <= d && d < PyLong_SHIFT);
1470 for (i=0; i < m; i++) {
1471 twodigits acc = (twodigits)a[i] << d | carry;
1472 z[i] = (digit)acc & PyLong_MASK;
1473 carry = (digit)(acc >> PyLong_SHIFT);
1474 }
1475 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001476}
1477
1478/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1479 * result in z[0:m], and return the d bits shifted out of the bottom.
1480 */
1481static digit
1482v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 Py_ssize_t i;
1485 digit carry = 0;
1486 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 assert(0 <= d && d < PyLong_SHIFT);
1489 for (i=m; i-- > 0;) {
1490 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1491 carry = (digit)acc & mask;
1492 z[i] = (digit)(acc >> d);
1493 }
1494 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001495}
1496
Tim Peters212e6142001-07-14 12:23:19 +00001497/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1498 in pout, and returning the remainder. pin and pout point at the LSD.
1499 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001500 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001501 immutable. */
1502
1503static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001504inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 assert(n > 0 && n <= PyLong_MASK);
1509 pin += size;
1510 pout += size;
1511 while (--size >= 0) {
1512 digit hi;
1513 rem = (rem << PyLong_SHIFT) | *--pin;
1514 *--pout = hi = (digit)(rem / n);
1515 rem -= (twodigits)hi * n;
1516 }
1517 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001518}
1519
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001520/* Divide a long integer by a digit, returning both the quotient
1521 (as function result) and the remainder (through *prem).
1522 The sign of a is ignored; n should not be zero. */
1523
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001524static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001525divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 const Py_ssize_t size = ABS(Py_SIZE(a));
1528 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 assert(n > 0 && n <= PyLong_MASK);
1531 z = _PyLong_New(size);
1532 if (z == NULL)
1533 return NULL;
1534 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1535 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001536}
1537
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001538/* Convert a long integer to a base 10 string. Returns a new non-shared
1539 string. (Return value is non-shared so that callers can modify the
1540 returned value if necessary.) */
1541
1542static PyObject *
1543long_to_decimal_string(PyObject *aa)
1544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 PyLongObject *scratch, *a;
1546 PyObject *str;
1547 Py_ssize_t size, strlen, size_a, i, j;
1548 digit *pout, *pin, rem, tenpow;
1549 Py_UNICODE *p;
1550 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 a = (PyLongObject *)aa;
1553 if (a == NULL || !PyLong_Check(a)) {
1554 PyErr_BadInternalCall();
1555 return NULL;
1556 }
1557 size_a = ABS(Py_SIZE(a));
1558 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* quick and dirty upper bound for the number of digits
1561 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 But log2(a) < size_a * PyLong_SHIFT, and
1566 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1567 > 3 * _PyLong_DECIMAL_SHIFT
1568 */
1569 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1570 PyErr_SetString(PyExc_OverflowError,
1571 "long is too large to format");
1572 return NULL;
1573 }
1574 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1575 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1576 scratch = _PyLong_New(size);
1577 if (scratch == NULL)
1578 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 /* convert array of base _PyLong_BASE digits in pin to an array of
1581 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1582 Volume 2 (3rd edn), section 4.4, Method 1b). */
1583 pin = a->ob_digit;
1584 pout = scratch->ob_digit;
1585 size = 0;
1586 for (i = size_a; --i >= 0; ) {
1587 digit hi = pin[i];
1588 for (j = 0; j < size; j++) {
1589 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1590 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1591 pout[j] = (digit)(z - (twodigits)hi *
1592 _PyLong_DECIMAL_BASE);
1593 }
1594 while (hi) {
1595 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1596 hi /= _PyLong_DECIMAL_BASE;
1597 }
1598 /* check for keyboard interrupt */
1599 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001600 Py_DECREF(scratch);
1601 return NULL;
1602 })
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 }
1604 /* pout should have at least one digit, so that the case when a = 0
1605 works correctly */
1606 if (size == 0)
1607 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 /* calculate exact length of output string, and allocate */
1610 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1611 tenpow = 10;
1612 rem = pout[size-1];
1613 while (rem >= tenpow) {
1614 tenpow *= 10;
1615 strlen++;
1616 }
1617 str = PyUnicode_FromUnicode(NULL, strlen);
1618 if (str == NULL) {
1619 Py_DECREF(scratch);
1620 return NULL;
1621 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 /* fill the string right-to-left */
1624 p = PyUnicode_AS_UNICODE(str) + strlen;
1625 *p = '\0';
1626 /* pout[0] through pout[size-2] contribute exactly
1627 _PyLong_DECIMAL_SHIFT digits each */
1628 for (i=0; i < size - 1; i++) {
1629 rem = pout[i];
1630 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1631 *--p = '0' + rem % 10;
1632 rem /= 10;
1633 }
1634 }
1635 /* pout[size-1]: always produce at least one decimal digit */
1636 rem = pout[i];
1637 do {
1638 *--p = '0' + rem % 10;
1639 rem /= 10;
1640 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* and sign */
1643 if (negative)
1644 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* check we've counted correctly */
1647 assert(p == PyUnicode_AS_UNICODE(str));
1648 Py_DECREF(scratch);
1649 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001650}
1651
Mark Dickinsoncd068122009-09-18 14:53:08 +00001652/* Convert a long int object to a string, using a given conversion base,
1653 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001654 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001655
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001656PyObject *
1657_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 register PyLongObject *a = (PyLongObject *)aa;
1660 PyObject *str;
1661 Py_ssize_t i, sz;
1662 Py_ssize_t size_a;
1663 Py_UNICODE *p, sign = '\0';
1664 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 assert(base == 2 || base == 8 || base == 10 || base == 16);
1667 if (base == 10)
1668 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (a == NULL || !PyLong_Check(a)) {
1671 PyErr_BadInternalCall();
1672 return NULL;
1673 }
1674 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 /* Compute a rough upper bound for the length of the string */
1677 switch (base) {
1678 case 16:
1679 bits = 4;
1680 break;
1681 case 8:
1682 bits = 3;
1683 break;
1684 case 2:
1685 bits = 1;
1686 break;
1687 default:
1688 assert(0); /* shouldn't ever get here */
1689 bits = 0; /* to silence gcc warning */
1690 }
1691 /* compute length of output string: allow 2 characters for prefix and
1692 1 for possible '-' sign. */
1693 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1694 PyErr_SetString(PyExc_OverflowError,
1695 "int is too large to format");
1696 return NULL;
1697 }
1698 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1699 is safe from overflow */
1700 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1701 assert(sz >= 0);
1702 str = PyUnicode_FromUnicode(NULL, sz);
1703 if (str == NULL)
1704 return NULL;
1705 p = PyUnicode_AS_UNICODE(str) + sz;
1706 *p = '\0';
1707 if (Py_SIZE(a) < 0)
1708 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (Py_SIZE(a) == 0) {
1711 *--p = '0';
1712 }
1713 else {
1714 /* JRH: special case for power-of-2 bases */
1715 twodigits accum = 0;
1716 int accumbits = 0; /* # of bits in accum */
1717 for (i = 0; i < size_a; ++i) {
1718 accum |= (twodigits)a->ob_digit[i] << accumbits;
1719 accumbits += PyLong_SHIFT;
1720 assert(accumbits >= bits);
1721 do {
1722 Py_UNICODE cdigit;
1723 cdigit = (Py_UNICODE)(accum & (base - 1));
1724 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1725 assert(p > PyUnicode_AS_UNICODE(str));
1726 *--p = cdigit;
1727 accumbits -= bits;
1728 accum >>= bits;
1729 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1730 }
1731 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 if (base == 16)
1734 *--p = 'x';
1735 else if (base == 8)
1736 *--p = 'o';
1737 else /* (base == 2) */
1738 *--p = 'b';
1739 *--p = '0';
1740 if (sign)
1741 *--p = sign;
1742 if (p != PyUnicode_AS_UNICODE(str)) {
1743 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1744 assert(p > q);
1745 do {
1746 } while ((*q++ = *p++) != '\0');
1747 q--;
1748 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1749 PyUnicode_AS_UNICODE(str)))) {
1750 Py_DECREF(str);
1751 return NULL;
1752 }
1753 }
1754 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001755}
1756
Thomas Wouters477c8d52006-05-27 19:21:47 +00001757/* Table of digit values for 8-bit string -> integer conversion.
1758 * '0' maps to 0, ..., '9' maps to 9.
1759 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1760 * All other indices map to 37.
1761 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001762 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001763 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001764unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1766 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1767 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1768 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1769 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1770 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1771 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1772 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1773 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1774 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1775 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1776 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1777 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1778 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1779 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1780 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001781};
1782
1783/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001784 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1785 * non-digit (which may be *str!). A normalized long is returned.
1786 * The point to this routine is that it takes time linear in the number of
1787 * string characters.
1788 */
1789static PyLongObject *
1790long_from_binary_base(char **str, int base)
1791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 char *p = *str;
1793 char *start = p;
1794 int bits_per_char;
1795 Py_ssize_t n;
1796 PyLongObject *z;
1797 twodigits accum;
1798 int bits_in_accum;
1799 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1802 n = base;
1803 for (bits_per_char = -1; n; ++bits_per_char)
1804 n >>= 1;
1805 /* n <- total # of bits needed, while setting p to end-of-string */
1806 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1807 ++p;
1808 *str = p;
1809 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1810 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1811 if (n / bits_per_char < p - start) {
1812 PyErr_SetString(PyExc_ValueError,
1813 "int string too large to convert");
1814 return NULL;
1815 }
1816 n = n / PyLong_SHIFT;
1817 z = _PyLong_New(n);
1818 if (z == NULL)
1819 return NULL;
1820 /* Read string from right, and fill in long from left; i.e.,
1821 * from least to most significant in both.
1822 */
1823 accum = 0;
1824 bits_in_accum = 0;
1825 pdigit = z->ob_digit;
1826 while (--p >= start) {
1827 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1828 assert(k >= 0 && k < base);
1829 accum |= (twodigits)k << bits_in_accum;
1830 bits_in_accum += bits_per_char;
1831 if (bits_in_accum >= PyLong_SHIFT) {
1832 *pdigit++ = (digit)(accum & PyLong_MASK);
1833 assert(pdigit - z->ob_digit <= n);
1834 accum >>= PyLong_SHIFT;
1835 bits_in_accum -= PyLong_SHIFT;
1836 assert(bits_in_accum < PyLong_SHIFT);
1837 }
1838 }
1839 if (bits_in_accum) {
1840 assert(bits_in_accum <= PyLong_SHIFT);
1841 *pdigit++ = (digit)accum;
1842 assert(pdigit - z->ob_digit <= n);
1843 }
1844 while (pdigit - z->ob_digit < n)
1845 *pdigit++ = 0;
1846 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001847}
1848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001849PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001850PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 int sign = 1, error_if_nonzero = 0;
1853 char *start, *orig_str = str;
1854 PyLongObject *z = NULL;
1855 PyObject *strobj;
1856 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if ((base != 0 && base < 2) || base > 36) {
1859 PyErr_SetString(PyExc_ValueError,
1860 "int() arg 2 must be >= 2 and <= 36");
1861 return NULL;
1862 }
1863 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1864 str++;
1865 if (*str == '+')
1866 ++str;
1867 else if (*str == '-') {
1868 ++str;
1869 sign = -1;
1870 }
1871 if (base == 0) {
1872 if (str[0] != '0')
1873 base = 10;
1874 else if (str[1] == 'x' || str[1] == 'X')
1875 base = 16;
1876 else if (str[1] == 'o' || str[1] == 'O')
1877 base = 8;
1878 else if (str[1] == 'b' || str[1] == 'B')
1879 base = 2;
1880 else {
1881 /* "old" (C-style) octal literal, now invalid.
1882 it might still be zero though */
1883 error_if_nonzero = 1;
1884 base = 10;
1885 }
1886 }
1887 if (str[0] == '0' &&
1888 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1889 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1890 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1891 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 start = str;
1894 if ((base & (base - 1)) == 0)
1895 z = long_from_binary_base(&str, base);
1896 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001897/***
1898Binary bases can be converted in time linear in the number of digits, because
1899Python's representation base is binary. Other bases (including decimal!) use
1900the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001901
Thomas Wouters477c8d52006-05-27 19:21:47 +00001902First some math: the largest integer that can be expressed in N base-B digits
1903is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1904case number of Python digits needed to hold it is the smallest integer n s.t.
1905
1906 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1907 BASE**n >= B**N [taking logs to base BASE]
1908 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1909
1910The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1911this quickly. A Python long with that much space is reserved near the start,
1912and the result is computed into it.
1913
1914The input string is actually treated as being in base base**i (i.e., i digits
1915are processed at a time), where two more static arrays hold:
1916
1917 convwidth_base[base] = the largest integer i such that base**i <= BASE
1918 convmultmax_base[base] = base ** convwidth_base[base]
1919
1920The first of these is the largest i such that i consecutive input digits
1921must fit in a single Python digit. The second is effectively the input
1922base we're really using.
1923
1924Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1925convmultmax_base[base], the result is "simply"
1926
1927 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1928
1929where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001930
1931Error analysis: as above, the number of Python digits `n` needed is worst-
1932case
1933
1934 n >= N * log(B)/log(BASE)
1935
1936where `N` is the number of input digits in base `B`. This is computed via
1937
1938 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1939
1940below. Two numeric concerns are how much space this can waste, and whether
1941the computed result can be too small. To be concrete, assume BASE = 2**15,
1942which is the default (and it's unlikely anyone changes that).
1943
1944Waste isn't a problem: provided the first input digit isn't 0, the difference
1945between the worst-case input with N digits and the smallest input with N
1946digits is about a factor of B, but B is small compared to BASE so at most
1947one allocated Python digit can remain unused on that count. If
1948N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1949and adding 1 returns a result 1 larger than necessary. However, that can't
1950happen: whenever B is a power of 2, long_from_binary_base() is called
1951instead, and it's impossible for B**i to be an integer power of 2**15 when
1952B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1953an exact integer when B is not a power of 2, since B**i has a prime factor
1954other than 2 in that case, but (2**15)**j's only prime factor is 2).
1955
1956The computed result can be too small if the true value of N*log(B)/log(BASE)
1957is a little bit larger than an exact integer, but due to roundoff errors (in
1958computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1959yields a numeric result a little less than that integer. Unfortunately, "how
1960close can a transcendental function get to an integer over some range?"
1961questions are generally theoretically intractable. Computer analysis via
1962continued fractions is practical: expand log(B)/log(BASE) via continued
1963fractions, giving a sequence i/j of "the best" rational approximations. Then
1964j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1965we can get very close to being in trouble, but very rarely. For example,
196676573 is a denominator in one of the continued-fraction approximations to
1967log(10)/log(2**15), and indeed:
1968
1969 >>> log(10)/log(2**15)*76573
1970 16958.000000654003
1971
1972is very close to an integer. If we were working with IEEE single-precision,
1973rounding errors could kill us. Finding worst cases in IEEE double-precision
1974requires better-than-double-precision log() functions, and Tim didn't bother.
1975Instead the code checks to see whether the allocated space is enough as each
1976new Python digit is added, and copies the whole thing to a larger long if not.
1977This should happen extremely rarely, and in fact I don't have a test case
1978that triggers it(!). Instead the code was tested by artificially allocating
1979just 1 digit at the start, so that the copying code was exercised for every
1980digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001981***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 register twodigits c; /* current input character */
1983 Py_ssize_t size_z;
1984 int i;
1985 int convwidth;
1986 twodigits convmultmax, convmult;
1987 digit *pz, *pzstop;
1988 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 static double log_base_BASE[37] = {0.0e0,};
1991 static int convwidth_base[37] = {0,};
1992 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (log_base_BASE[base] == 0.0) {
1995 twodigits convmax = base;
1996 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997
Mark Dickinson22b20182010-05-10 21:27:53 +00001998 log_base_BASE[base] = (log((double)base) /
1999 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 for (;;) {
2001 twodigits next = convmax * base;
2002 if (next > PyLong_BASE)
2003 break;
2004 convmax = next;
2005 ++i;
2006 }
2007 convmultmax_base[base] = convmax;
2008 assert(i > 0);
2009 convwidth_base[base] = i;
2010 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* Find length of the string of numeric characters. */
2013 scan = str;
2014 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2015 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 /* Create a long object that can contain the largest possible
2018 * integer with this base and length. Note that there's no
2019 * need to initialize z->ob_digit -- no slot is read up before
2020 * being stored into.
2021 */
2022 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2023 /* Uncomment next line to test exceedingly rare copy code */
2024 /* size_z = 1; */
2025 assert(size_z > 0);
2026 z = _PyLong_New(size_z);
2027 if (z == NULL)
2028 return NULL;
2029 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* `convwidth` consecutive input digits are treated as a single
2032 * digit in base `convmultmax`.
2033 */
2034 convwidth = convwidth_base[base];
2035 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 /* Work ;-) */
2038 while (str < scan) {
2039 /* grab up to convwidth digits from the input string */
2040 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2041 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2042 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002043 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 assert(c < PyLong_BASE);
2045 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 convmult = convmultmax;
2048 /* Calculate the shift only if we couldn't get
2049 * convwidth digits.
2050 */
2051 if (i != convwidth) {
2052 convmult = base;
2053 for ( ; i > 1; --i)
2054 convmult *= base;
2055 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 /* Multiply z by convmult, and add c. */
2058 pz = z->ob_digit;
2059 pzstop = pz + Py_SIZE(z);
2060 for (; pz < pzstop; ++pz) {
2061 c += (twodigits)*pz * convmult;
2062 *pz = (digit)(c & PyLong_MASK);
2063 c >>= PyLong_SHIFT;
2064 }
2065 /* carry off the current end? */
2066 if (c) {
2067 assert(c < PyLong_BASE);
2068 if (Py_SIZE(z) < size_z) {
2069 *pz = (digit)c;
2070 ++Py_SIZE(z);
2071 }
2072 else {
2073 PyLongObject *tmp;
2074 /* Extremely rare. Get more space. */
2075 assert(Py_SIZE(z) == size_z);
2076 tmp = _PyLong_New(size_z + 1);
2077 if (tmp == NULL) {
2078 Py_DECREF(z);
2079 return NULL;
2080 }
2081 memcpy(tmp->ob_digit,
2082 z->ob_digit,
2083 sizeof(digit) * size_z);
2084 Py_DECREF(z);
2085 z = tmp;
2086 z->ob_digit[size_z] = (digit)c;
2087 ++size_z;
2088 }
2089 }
2090 }
2091 }
2092 if (z == NULL)
2093 return NULL;
2094 if (error_if_nonzero) {
2095 /* reset the base to 0, else the exception message
2096 doesn't make too much sense */
2097 base = 0;
2098 if (Py_SIZE(z) != 0)
2099 goto onError;
2100 /* there might still be other problems, therefore base
2101 remains zero here for the same reason */
2102 }
2103 if (str == start)
2104 goto onError;
2105 if (sign < 0)
2106 Py_SIZE(z) = -(Py_SIZE(z));
2107 while (*str && isspace(Py_CHARMASK(*str)))
2108 str++;
2109 if (*str != '\0')
2110 goto onError;
2111 if (pend)
2112 *pend = str;
2113 long_normalize(z);
2114 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002115
Mark Dickinson22b20182010-05-10 21:27:53 +00002116 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 Py_XDECREF(z);
2118 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2119 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2120 if (strobj == NULL)
2121 return NULL;
2122 PyErr_Format(PyExc_ValueError,
2123 "invalid literal for int() with base %d: %R",
2124 base, strobj);
2125 Py_DECREF(strobj);
2126 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002127}
2128
2129PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002130PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 PyObject *result;
2133 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (buffer == NULL)
2136 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2139 PyMem_FREE(buffer);
2140 return NULL;
2141 }
2142 result = PyLong_FromString(buffer, NULL, base);
2143 PyMem_FREE(buffer);
2144 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002145}
2146
Tim Peters9f688bf2000-07-07 15:53:28 +00002147/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002148static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002150static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002151
2152/* Long division with remainder, top-level routine */
2153
Guido van Rossume32e0141992-01-19 16:31:05 +00002154static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002155long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2159 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (size_b == 0) {
2162 PyErr_SetString(PyExc_ZeroDivisionError,
2163 "integer division or modulo by zero");
2164 return -1;
2165 }
2166 if (size_a < size_b ||
2167 (size_a == size_b &&
2168 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2169 /* |a| < |b|. */
2170 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2171 if (*pdiv == NULL)
2172 return -1;
2173 Py_INCREF(a);
2174 *prem = (PyLongObject *) a;
2175 return 0;
2176 }
2177 if (size_b == 1) {
2178 digit rem = 0;
2179 z = divrem1(a, b->ob_digit[0], &rem);
2180 if (z == NULL)
2181 return -1;
2182 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2183 if (*prem == NULL) {
2184 Py_DECREF(z);
2185 return -1;
2186 }
2187 }
2188 else {
2189 z = x_divrem(a, b, prem);
2190 if (z == NULL)
2191 return -1;
2192 }
2193 /* Set the signs.
2194 The quotient z has the sign of a*b;
2195 the remainder r has the sign of a,
2196 so a = b*z + r. */
2197 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2198 NEGATE(z);
2199 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2200 NEGATE(*prem);
2201 *pdiv = maybe_small_long(z);
2202 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002203}
2204
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002205/* Unsigned long division with remainder -- the algorithm. The arguments v1
2206 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002207
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002208static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002209x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyLongObject *v, *w, *a;
2212 Py_ssize_t i, k, size_v, size_w;
2213 int d;
2214 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2215 twodigits vv;
2216 sdigit zhi;
2217 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2220 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2221 handle the special case when the initial estimate q for a quotient
2222 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2223 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 /* allocate space; w will also be used to hold the final remainder */
2226 size_v = ABS(Py_SIZE(v1));
2227 size_w = ABS(Py_SIZE(w1));
2228 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2229 v = _PyLong_New(size_v+1);
2230 if (v == NULL) {
2231 *prem = NULL;
2232 return NULL;
2233 }
2234 w = _PyLong_New(size_w);
2235 if (w == NULL) {
2236 Py_DECREF(v);
2237 *prem = NULL;
2238 return NULL;
2239 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2242 shift v1 left by the same amount. Results go into w and v. */
2243 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2244 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2245 assert(carry == 0);
2246 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2247 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2248 v->ob_digit[size_v] = carry;
2249 size_v++;
2250 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2253 at most (and usually exactly) k = size_v - size_w digits. */
2254 k = size_v - size_w;
2255 assert(k >= 0);
2256 a = _PyLong_New(k);
2257 if (a == NULL) {
2258 Py_DECREF(w);
2259 Py_DECREF(v);
2260 *prem = NULL;
2261 return NULL;
2262 }
2263 v0 = v->ob_digit;
2264 w0 = w->ob_digit;
2265 wm1 = w0[size_w-1];
2266 wm2 = w0[size_w-2];
2267 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2268 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2269 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002272 Py_DECREF(a);
2273 Py_DECREF(w);
2274 Py_DECREF(v);
2275 *prem = NULL;
2276 return NULL;
2277 })
Tim Peters5af4e6c2002-08-12 02:31:19 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* estimate quotient digit q; may overestimate by 1 (rare) */
2280 vtop = vk[size_w];
2281 assert(vtop <= wm1);
2282 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2283 q = (digit)(vv / wm1);
2284 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2285 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2286 | vk[size_w-2])) {
2287 --q;
2288 r += wm1;
2289 if (r >= PyLong_BASE)
2290 break;
2291 }
2292 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2295 zhi = 0;
2296 for (i = 0; i < size_w; ++i) {
2297 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2298 -PyLong_BASE * q <= z < PyLong_BASE */
2299 z = (sdigit)vk[i] + zhi -
2300 (stwodigits)q * (stwodigits)w0[i];
2301 vk[i] = (digit)z & PyLong_MASK;
2302 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002303 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* add w back if q was too large (this branch taken rarely) */
2307 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2308 if ((sdigit)vtop + zhi < 0) {
2309 carry = 0;
2310 for (i = 0; i < size_w; ++i) {
2311 carry += vk[i] + w0[i];
2312 vk[i] = carry & PyLong_MASK;
2313 carry >>= PyLong_SHIFT;
2314 }
2315 --q;
2316 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 /* store quotient digit */
2319 assert(q < PyLong_BASE);
2320 *--ak = q;
2321 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* unshift remainder; we reuse w to store the result */
2324 carry = v_rshift(w0, v0, size_w, d);
2325 assert(carry==0);
2326 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 *prem = long_normalize(w);
2329 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330}
2331
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002332/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2333 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2334 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2335 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2336 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2337 -1.0. */
2338
2339/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2340#if DBL_MANT_DIG == 53
2341#define EXP2_DBL_MANT_DIG 9007199254740992.0
2342#else
2343#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2344#endif
2345
2346double
2347_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2350 /* See below for why x_digits is always large enough. */
2351 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2352 double dx;
2353 /* Correction term for round-half-to-even rounding. For a digit x,
2354 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2355 multiple of 4, rounding ties to a multiple of 8. */
2356 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 a_size = ABS(Py_SIZE(a));
2359 if (a_size == 0) {
2360 /* Special case for 0: significand 0.0, exponent 0. */
2361 *e = 0;
2362 return 0.0;
2363 }
2364 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2365 /* The following is an overflow-free version of the check
2366 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2367 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2368 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2369 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002370 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2374 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Number of digits needed for result: write // for floor division.
2377 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2386 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2389 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2390 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 in both cases.
2397 */
2398 if (a_bits <= DBL_MANT_DIG + 2) {
2399 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2400 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2401 x_size = 0;
2402 while (x_size < shift_digits)
2403 x_digits[x_size++] = 0;
2404 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2405 (int)shift_bits);
2406 x_size += a_size;
2407 x_digits[x_size++] = rem;
2408 }
2409 else {
2410 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2411 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2412 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2413 a_size - shift_digits, (int)shift_bits);
2414 x_size = a_size - shift_digits;
2415 /* For correct rounding below, we need the least significant
2416 bit of x to be 'sticky' for this shift: if any of the bits
2417 shifted out was nonzero, we set the least significant bit
2418 of x. */
2419 if (rem)
2420 x_digits[0] |= 1;
2421 else
2422 while (shift_digits > 0)
2423 if (a->ob_digit[--shift_digits]) {
2424 x_digits[0] |= 1;
2425 break;
2426 }
2427 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002428 assert(1 <= x_size &&
2429 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 /* Round, and convert to double. */
2432 x_digits[0] += half_even_correction[x_digits[0] & 7];
2433 dx = x_digits[--x_size];
2434 while (x_size > 0)
2435 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* Rescale; make correction if result is 1.0. */
2438 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2439 if (dx == 1.0) {
2440 if (a_bits == PY_SSIZE_T_MAX)
2441 goto overflow;
2442 dx = 0.5;
2443 a_bits += 1;
2444 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 *e = a_bits;
2447 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002448
2449 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* exponent > PY_SSIZE_T_MAX */
2451 PyErr_SetString(PyExc_OverflowError,
2452 "huge integer: number of bits overflows a Py_ssize_t");
2453 *e = 0;
2454 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002455}
2456
2457/* Get a C double from a long int object. Rounds to the nearest double,
2458 using the round-half-to-even rule in the case of a tie. */
2459
2460double
2461PyLong_AsDouble(PyObject *v)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 Py_ssize_t exponent;
2464 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 if (v == NULL || !PyLong_Check(v)) {
2467 PyErr_BadInternalCall();
2468 return -1.0;
2469 }
2470 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2471 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2472 PyErr_SetString(PyExc_OverflowError,
2473 "long int too large to convert to float");
2474 return -1.0;
2475 }
2476 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002477}
2478
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002479/* Methods */
2480
2481static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002482long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002485}
2486
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002487static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002488long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (Py_SIZE(a) != Py_SIZE(b)) {
2493 sign = Py_SIZE(a) - Py_SIZE(b);
2494 }
2495 else {
2496 Py_ssize_t i = ABS(Py_SIZE(a));
2497 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2498 ;
2499 if (i < 0)
2500 sign = 0;
2501 else {
2502 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2503 if (Py_SIZE(a) < 0)
2504 sign = -sign;
2505 }
2506 }
2507 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002508}
2509
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002510#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002512
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002513static PyObject *
2514long_richcompare(PyObject *self, PyObject *other, int op)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 int result;
2517 PyObject *v;
2518 CHECK_BINOP(self, other);
2519 if (self == other)
2520 result = 0;
2521 else
2522 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2523 /* Convert the return value to a Boolean */
2524 switch (op) {
2525 case Py_EQ:
2526 v = TEST_COND(result == 0);
2527 break;
2528 case Py_NE:
2529 v = TEST_COND(result != 0);
2530 break;
2531 case Py_LE:
2532 v = TEST_COND(result <= 0);
2533 break;
2534 case Py_GE:
2535 v = TEST_COND(result >= 0);
2536 break;
2537 case Py_LT:
2538 v = TEST_COND(result == -1);
2539 break;
2540 case Py_GT:
2541 v = TEST_COND(result == 1);
2542 break;
2543 default:
2544 PyErr_BadArgument();
2545 return NULL;
2546 }
2547 Py_INCREF(v);
2548 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002549}
2550
Guido van Rossum9bfef441993-03-29 10:43:31 +00002551static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002552long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 unsigned long x;
2555 Py_ssize_t i;
2556 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 i = Py_SIZE(v);
2559 switch(i) {
2560 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2561 case 0: return 0;
2562 case 1: return v->ob_digit[0];
2563 }
2564 sign = 1;
2565 x = 0;
2566 if (i < 0) {
2567 sign = -1;
2568 i = -(i);
2569 }
2570 /* The following loop produces a C unsigned long x such that x is
2571 congruent to the absolute value of v modulo ULONG_MAX. The
2572 resulting x is nonzero if and only if v is. */
2573 while (--i >= 0) {
2574 /* Force a native long #-bits (32 or 64) circular shift */
2575 x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
2576 x += v->ob_digit[i];
2577 /* If the addition above overflowed we compensate by
2578 incrementing. This preserves the value modulo
2579 ULONG_MAX. */
2580 if (x < v->ob_digit[i])
2581 x++;
2582 }
2583 x = x * sign;
2584 if (x == (unsigned long)-1)
2585 x = (unsigned long)-2;
2586 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002587}
2588
2589
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002590/* Add the absolute values of two long integers. */
2591
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002592static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002593x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2596 PyLongObject *z;
2597 Py_ssize_t i;
2598 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 /* Ensure a is the larger of the two: */
2601 if (size_a < size_b) {
2602 { PyLongObject *temp = a; a = b; b = temp; }
2603 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002604 size_a = size_b;
2605 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 }
2607 z = _PyLong_New(size_a+1);
2608 if (z == NULL)
2609 return NULL;
2610 for (i = 0; i < size_b; ++i) {
2611 carry += a->ob_digit[i] + b->ob_digit[i];
2612 z->ob_digit[i] = carry & PyLong_MASK;
2613 carry >>= PyLong_SHIFT;
2614 }
2615 for (; i < size_a; ++i) {
2616 carry += a->ob_digit[i];
2617 z->ob_digit[i] = carry & PyLong_MASK;
2618 carry >>= PyLong_SHIFT;
2619 }
2620 z->ob_digit[i] = carry;
2621 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002622}
2623
2624/* Subtract the absolute values of two integers. */
2625
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002626static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002627x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2630 PyLongObject *z;
2631 Py_ssize_t i;
2632 int sign = 1;
2633 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 /* Ensure a is the larger of the two: */
2636 if (size_a < size_b) {
2637 sign = -1;
2638 { PyLongObject *temp = a; a = b; b = temp; }
2639 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002640 size_a = size_b;
2641 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 }
2643 else if (size_a == size_b) {
2644 /* Find highest digit where a and b differ: */
2645 i = size_a;
2646 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2647 ;
2648 if (i < 0)
2649 return (PyLongObject *)PyLong_FromLong(0);
2650 if (a->ob_digit[i] < b->ob_digit[i]) {
2651 sign = -1;
2652 { PyLongObject *temp = a; a = b; b = temp; }
2653 }
2654 size_a = size_b = i+1;
2655 }
2656 z = _PyLong_New(size_a);
2657 if (z == NULL)
2658 return NULL;
2659 for (i = 0; i < size_b; ++i) {
2660 /* The following assumes unsigned arithmetic
2661 works module 2**N for some N>PyLong_SHIFT. */
2662 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2663 z->ob_digit[i] = borrow & PyLong_MASK;
2664 borrow >>= PyLong_SHIFT;
2665 borrow &= 1; /* Keep only one sign bit */
2666 }
2667 for (; i < size_a; ++i) {
2668 borrow = a->ob_digit[i] - borrow;
2669 z->ob_digit[i] = borrow & PyLong_MASK;
2670 borrow >>= PyLong_SHIFT;
2671 borrow &= 1; /* Keep only one sign bit */
2672 }
2673 assert(borrow == 0);
2674 if (sign < 0)
2675 NEGATE(z);
2676 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002677}
2678
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002679static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002680long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2687 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2688 MEDIUM_VALUE(b));
2689 return result;
2690 }
2691 if (Py_SIZE(a) < 0) {
2692 if (Py_SIZE(b) < 0) {
2693 z = x_add(a, b);
2694 if (z != NULL && Py_SIZE(z) != 0)
2695 Py_SIZE(z) = -(Py_SIZE(z));
2696 }
2697 else
2698 z = x_sub(b, a);
2699 }
2700 else {
2701 if (Py_SIZE(b) < 0)
2702 z = x_sub(a, b);
2703 else
2704 z = x_add(a, b);
2705 }
2706 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002707}
2708
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002709static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002710long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2717 PyObject* r;
2718 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2719 return r;
2720 }
2721 if (Py_SIZE(a) < 0) {
2722 if (Py_SIZE(b) < 0)
2723 z = x_sub(a, b);
2724 else
2725 z = x_add(a, b);
2726 if (z != NULL && Py_SIZE(z) != 0)
2727 Py_SIZE(z) = -(Py_SIZE(z));
2728 }
2729 else {
2730 if (Py_SIZE(b) < 0)
2731 z = x_add(a, b);
2732 else
2733 z = x_sub(a, b);
2734 }
2735 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002736}
2737
Tim Peters5af4e6c2002-08-12 02:31:19 +00002738/* Grade school multiplication, ignoring the signs.
2739 * Returns the absolute value of the product, or NULL if error.
2740 */
2741static PyLongObject *
2742x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 PyLongObject *z;
2745 Py_ssize_t size_a = ABS(Py_SIZE(a));
2746 Py_ssize_t size_b = ABS(Py_SIZE(b));
2747 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 z = _PyLong_New(size_a + size_b);
2750 if (z == NULL)
2751 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2754 if (a == b) {
2755 /* Efficient squaring per HAC, Algorithm 14.16:
2756 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2757 * Gives slightly less than a 2x speedup when a == b,
2758 * via exploiting that each entry in the multiplication
2759 * pyramid appears twice (except for the size_a squares).
2760 */
2761 for (i = 0; i < size_a; ++i) {
2762 twodigits carry;
2763 twodigits f = a->ob_digit[i];
2764 digit *pz = z->ob_digit + (i << 1);
2765 digit *pa = a->ob_digit + i + 1;
2766 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002769 Py_DECREF(z);
2770 return NULL;
2771 })
Tim Peters0973b992004-08-29 22:16:50 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 carry = *pz + f * f;
2774 *pz++ = (digit)(carry & PyLong_MASK);
2775 carry >>= PyLong_SHIFT;
2776 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 /* Now f is added in twice in each column of the
2779 * pyramid it appears. Same as adding f<<1 once.
2780 */
2781 f <<= 1;
2782 while (pa < paend) {
2783 carry += *pz + *pa++ * f;
2784 *pz++ = (digit)(carry & PyLong_MASK);
2785 carry >>= PyLong_SHIFT;
2786 assert(carry <= (PyLong_MASK << 1));
2787 }
2788 if (carry) {
2789 carry += *pz;
2790 *pz++ = (digit)(carry & PyLong_MASK);
2791 carry >>= PyLong_SHIFT;
2792 }
2793 if (carry)
2794 *pz += (digit)(carry & PyLong_MASK);
2795 assert((carry >> PyLong_SHIFT) == 0);
2796 }
2797 }
2798 else { /* a is not the same as b -- gradeschool long mult */
2799 for (i = 0; i < size_a; ++i) {
2800 twodigits carry = 0;
2801 twodigits f = a->ob_digit[i];
2802 digit *pz = z->ob_digit + i;
2803 digit *pb = b->ob_digit;
2804 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002807 Py_DECREF(z);
2808 return NULL;
2809 })
Tim Peters0973b992004-08-29 22:16:50 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 while (pb < pbend) {
2812 carry += *pz + *pb++ * f;
2813 *pz++ = (digit)(carry & PyLong_MASK);
2814 carry >>= PyLong_SHIFT;
2815 assert(carry <= PyLong_MASK);
2816 }
2817 if (carry)
2818 *pz += (digit)(carry & PyLong_MASK);
2819 assert((carry >> PyLong_SHIFT) == 0);
2820 }
2821 }
2822 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002823}
2824
2825/* A helper for Karatsuba multiplication (k_mul).
2826 Takes a long "n" and an integer "size" representing the place to
2827 split, and sets low and high such that abs(n) == (high << size) + low,
2828 viewing the shift as being by digits. The sign bit is ignored, and
2829 the return values are >= 0.
2830 Returns 0 on success, -1 on failure.
2831*/
2832static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002833kmul_split(PyLongObject *n,
2834 Py_ssize_t size,
2835 PyLongObject **high,
2836 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 PyLongObject *hi, *lo;
2839 Py_ssize_t size_lo, size_hi;
2840 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 size_lo = MIN(size_n, size);
2843 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 if ((hi = _PyLong_New(size_hi)) == NULL)
2846 return -1;
2847 if ((lo = _PyLong_New(size_lo)) == NULL) {
2848 Py_DECREF(hi);
2849 return -1;
2850 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2853 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 *high = long_normalize(hi);
2856 *low = long_normalize(lo);
2857 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002858}
2859
Tim Peters60004642002-08-12 22:01:34 +00002860static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2861
Tim Peters5af4e6c2002-08-12 02:31:19 +00002862/* Karatsuba multiplication. Ignores the input signs, and returns the
2863 * absolute value of the product (or NULL if error).
2864 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2865 */
2866static PyLongObject *
2867k_mul(PyLongObject *a, PyLongObject *b)
2868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 Py_ssize_t asize = ABS(Py_SIZE(a));
2870 Py_ssize_t bsize = ABS(Py_SIZE(b));
2871 PyLongObject *ah = NULL;
2872 PyLongObject *al = NULL;
2873 PyLongObject *bh = NULL;
2874 PyLongObject *bl = NULL;
2875 PyLongObject *ret = NULL;
2876 PyLongObject *t1, *t2, *t3;
2877 Py_ssize_t shift; /* the number of digits we split off */
2878 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2881 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2882 * Then the original product is
2883 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2884 * By picking X to be a power of 2, "*X" is just shifting, and it's
2885 * been reduced to 3 multiplies on numbers half the size.
2886 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 /* We want to split based on the larger number; fiddle so that b
2889 * is largest.
2890 */
2891 if (asize > bsize) {
2892 t1 = a;
2893 a = b;
2894 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 i = asize;
2897 asize = bsize;
2898 bsize = i;
2899 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 /* Use gradeschool math when either number is too small. */
2902 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2903 if (asize <= i) {
2904 if (asize == 0)
2905 return (PyLongObject *)PyLong_FromLong(0);
2906 else
2907 return x_mul(a, b);
2908 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 /* If a is small compared to b, splitting on b gives a degenerate
2911 * case with ah==0, and Karatsuba may be (even much) less efficient
2912 * than "grade school" then. However, we can still win, by viewing
2913 * b as a string of "big digits", each of width a->ob_size. That
2914 * leads to a sequence of balanced calls to k_mul.
2915 */
2916 if (2 * asize <= bsize)
2917 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 /* Split a & b into hi & lo pieces. */
2920 shift = bsize >> 1;
2921 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2922 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 if (a == b) {
2925 bh = ah;
2926 bl = al;
2927 Py_INCREF(bh);
2928 Py_INCREF(bl);
2929 }
2930 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 /* The plan:
2933 * 1. Allocate result space (asize + bsize digits: that's always
2934 * enough).
2935 * 2. Compute ah*bh, and copy into result at 2*shift.
2936 * 3. Compute al*bl, and copy into result at 0. Note that this
2937 * can't overlap with #2.
2938 * 4. Subtract al*bl from the result, starting at shift. This may
2939 * underflow (borrow out of the high digit), but we don't care:
2940 * we're effectively doing unsigned arithmetic mod
2941 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2942 * borrows and carries out of the high digit can be ignored.
2943 * 5. Subtract ah*bh from the result, starting at shift.
2944 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2945 * at shift.
2946 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 /* 1. Allocate result space. */
2949 ret = _PyLong_New(asize + bsize);
2950 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002951#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 /* Fill with trash, to catch reference to uninitialized digits. */
2953 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002954#endif
Tim Peters44121a62002-08-12 06:17:58 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2957 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2958 assert(Py_SIZE(t1) >= 0);
2959 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2960 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2961 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 /* Zero-out the digits higher than the ah*bh copy. */
2964 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2965 if (i)
2966 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2967 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 /* 3. t2 <- al*bl, and copy into the low digits. */
2970 if ((t2 = k_mul(al, bl)) == NULL) {
2971 Py_DECREF(t1);
2972 goto fail;
2973 }
2974 assert(Py_SIZE(t2) >= 0);
2975 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2976 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 /* Zero out remaining digits. */
2979 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
2980 if (i)
2981 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
2984 * because it's fresher in cache.
2985 */
2986 i = Py_SIZE(ret) - shift; /* # digits after shift */
2987 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
2988 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00002989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
2991 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
2994 if ((t1 = x_add(ah, al)) == NULL) goto fail;
2995 Py_DECREF(ah);
2996 Py_DECREF(al);
2997 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 if (a == b) {
3000 t2 = t1;
3001 Py_INCREF(t2);
3002 }
3003 else if ((t2 = x_add(bh, bl)) == NULL) {
3004 Py_DECREF(t1);
3005 goto fail;
3006 }
3007 Py_DECREF(bh);
3008 Py_DECREF(bl);
3009 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 t3 = k_mul(t1, t2);
3012 Py_DECREF(t1);
3013 Py_DECREF(t2);
3014 if (t3 == NULL) goto fail;
3015 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 /* Add t3. It's not obvious why we can't run out of room here.
3018 * See the (*) comment after this function.
3019 */
3020 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3021 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003024
Mark Dickinson22b20182010-05-10 21:27:53 +00003025 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 Py_XDECREF(ret);
3027 Py_XDECREF(ah);
3028 Py_XDECREF(al);
3029 Py_XDECREF(bh);
3030 Py_XDECREF(bl);
3031 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003032}
3033
Tim Petersd6974a52002-08-13 20:37:51 +00003034/* (*) Why adding t3 can't "run out of room" above.
3035
Tim Petersab86c2b2002-08-15 20:06:00 +00003036Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3037to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003038
Tim Petersab86c2b2002-08-15 20:06:00 +000030391. For any integer i, i = c(i/2) + f(i/2). In particular,
3040 bsize = c(bsize/2) + f(bsize/2).
30412. shift = f(bsize/2)
30423. asize <= bsize
30434. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3044 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003045
Tim Petersab86c2b2002-08-15 20:06:00 +00003046We allocated asize + bsize result digits, and add t3 into them at an offset
3047of shift. This leaves asize+bsize-shift allocated digit positions for t3
3048to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3049asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003050
Tim Petersab86c2b2002-08-15 20:06:00 +00003051bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3052at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003053
Tim Petersab86c2b2002-08-15 20:06:00 +00003054If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3055digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3056most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003057
Tim Petersab86c2b2002-08-15 20:06:00 +00003058The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003059
Tim Petersab86c2b2002-08-15 20:06:00 +00003060 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003061
Tim Petersab86c2b2002-08-15 20:06:00 +00003062and we have asize + c(bsize/2) available digit positions. We need to show
3063this is always enough. An instance of c(bsize/2) cancels out in both, so
3064the question reduces to whether asize digits is enough to hold
3065(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3066then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3067asize 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 +00003068digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003069asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003070c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3071is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3072bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003073
Tim Peters48d52c02002-08-14 17:07:32 +00003074Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3075clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3076ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003077*/
3078
Tim Peters60004642002-08-12 22:01:34 +00003079/* b has at least twice the digits of a, and a is big enough that Karatsuba
3080 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3081 * of slices, each with a->ob_size digits, and multiply the slices by a,
3082 * one at a time. This gives k_mul balanced inputs to work with, and is
3083 * also cache-friendly (we compute one double-width slice of the result
3084 * at a time, then move on, never bactracking except for the helpful
3085 * single-width slice overlap between successive partial sums).
3086 */
3087static PyLongObject *
3088k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 const Py_ssize_t asize = ABS(Py_SIZE(a));
3091 Py_ssize_t bsize = ABS(Py_SIZE(b));
3092 Py_ssize_t nbdone; /* # of b digits already multiplied */
3093 PyLongObject *ret;
3094 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 assert(asize > KARATSUBA_CUTOFF);
3097 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 /* Allocate result space, and zero it out. */
3100 ret = _PyLong_New(asize + bsize);
3101 if (ret == NULL)
3102 return NULL;
3103 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 /* Successive slices of b are copied into bslice. */
3106 bslice = _PyLong_New(asize);
3107 if (bslice == NULL)
3108 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 nbdone = 0;
3111 while (bsize > 0) {
3112 PyLongObject *product;
3113 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 /* Multiply the next slice of b by a. */
3116 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3117 nbtouse * sizeof(digit));
3118 Py_SIZE(bslice) = nbtouse;
3119 product = k_mul(a, bslice);
3120 if (product == NULL)
3121 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 /* Add into result. */
3124 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3125 product->ob_digit, Py_SIZE(product));
3126 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 bsize -= nbtouse;
3129 nbdone += nbtouse;
3130 }
Tim Peters60004642002-08-12 22:01:34 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 Py_DECREF(bslice);
3133 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003134
Mark Dickinson22b20182010-05-10 21:27:53 +00003135 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 Py_DECREF(ret);
3137 Py_XDECREF(bslice);
3138 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003139}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003140
3141static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003142long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* fast path for single-digit multiplication */
3149 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3150 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003151#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003153#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* if we don't have long long then we're almost certainly
3155 using 15-bit digits, so v will fit in a long. In the
3156 unlikely event that we're using 30-bit digits on a platform
3157 without long long, a large v will just cause us to fall
3158 through to the general multiplication code below. */
3159 if (v >= LONG_MIN && v <= LONG_MAX)
3160 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003161#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 z = k_mul(a, b);
3165 /* Negate if exactly one of the inputs is negative. */
3166 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3167 NEGATE(z);
3168 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003169}
3170
Guido van Rossume32e0141992-01-19 16:31:05 +00003171/* The / and % operators are now defined in terms of divmod().
3172 The expression a mod b has the value a - b*floor(a/b).
3173 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003174 |a| by |b|, with the sign of a. This is also expressed
3175 as a - b*trunc(a/b), if trunc truncates towards zero.
3176 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 a b a rem b a mod b
3178 13 10 3 3
3179 -13 10 -3 7
3180 13 -10 3 -7
3181 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003182 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003183 have different signs. We then subtract one from the 'div'
3184 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003185
Tim Peters47e52ee2004-08-30 02:44:38 +00003186/* Compute
3187 * *pdiv, *pmod = divmod(v, w)
3188 * NULL can be passed for pdiv or pmod, in which case that part of
3189 * the result is simply thrown away. The caller owns a reference to
3190 * each of these it requests (does not pass NULL for).
3191 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003192static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003193l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 if (long_divrem(v, w, &div, &mod) < 0)
3199 return -1;
3200 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3201 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3202 PyLongObject *temp;
3203 PyLongObject *one;
3204 temp = (PyLongObject *) long_add(mod, w);
3205 Py_DECREF(mod);
3206 mod = temp;
3207 if (mod == NULL) {
3208 Py_DECREF(div);
3209 return -1;
3210 }
3211 one = (PyLongObject *) PyLong_FromLong(1L);
3212 if (one == NULL ||
3213 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3214 Py_DECREF(mod);
3215 Py_DECREF(div);
3216 Py_XDECREF(one);
3217 return -1;
3218 }
3219 Py_DECREF(one);
3220 Py_DECREF(div);
3221 div = temp;
3222 }
3223 if (pdiv != NULL)
3224 *pdiv = div;
3225 else
3226 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 if (pmod != NULL)
3229 *pmod = mod;
3230 else
3231 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003234}
3235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003236static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003237long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 CHECK_BINOP(a, b);
3242 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3243 div = NULL;
3244 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003245}
3246
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003247/* PyLong/PyLong -> float, with correctly rounded result. */
3248
3249#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3250#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003252static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003253long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 PyLongObject *a, *b, *x;
3256 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3257 digit mask, low;
3258 int inexact, negate, a_is_small, b_is_small;
3259 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 CHECK_BINOP(v, w);
3262 a = (PyLongObject *)v;
3263 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 /*
3266 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3269 1. choose a suitable integer 'shift'
3270 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3271 3. adjust x for correct rounding
3272 4. convert x to a double dx with the same value
3273 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3278 returns either 0.0 or -0.0, depending on the sign of b. For a and
3279 b both nonzero, ignore signs of a and b, and add the sign back in
3280 at the end. Now write a_bits and b_bits for the bit lengths of a
3281 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3282 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3287 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3288 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3289 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 1. The integer 'shift' is chosen so that x has the right number of
3294 bits for a double, plus two or three extra bits that will be used
3295 in the rounding decisions. Writing a_bits and b_bits for the
3296 number of significant bits in a and b respectively, a
3297 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 This is fine in the usual case, but if a/b is smaller than the
3302 smallest normal float then it can lead to double rounding on an
3303 IEEE 754 platform, giving incorrectly rounded results. So we
3304 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 2. The quantity x is computed by first shifting a (left -shift bits
3309 if shift <= 0, right shift bits if shift > 0) and then dividing by
3310 b. For both the shift and the division, we keep track of whether
3311 the result is inexact, in a flag 'inexact'; this information is
3312 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 With the choice of shift above, together with our assumption that
3315 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3316 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3319 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 For float representability, we need x/2**extra_bits <
3324 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3325 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 To round, we just modify the bottom digit of x in-place; this can
3330 end up giving a digit with value > PyLONG_MASK, but that's not a
3331 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 With the original choices for shift above, extra_bits will always
3334 be 2 or 3. Then rounding under the round-half-to-even rule, we
3335 round up iff the most significant of the extra bits is 1, and
3336 either: (a) the computation of x in step 2 had an inexact result,
3337 or (b) at least one other of the extra bits is 1, or (c) the least
3338 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 4. Conversion to a double is straightforward; all floating-point
3341 operations involved in the conversion are exact, so there's no
3342 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3345 The result will always be exactly representable as a double, except
3346 in the case that it overflows. To avoid dependence on the exact
3347 behaviour of ldexp on overflow, we check for overflow before
3348 applying ldexp. The result of ldexp is adjusted for sign before
3349 returning.
3350 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 /* Reduce to case where a and b are both positive. */
3353 a_size = ABS(Py_SIZE(a));
3354 b_size = ABS(Py_SIZE(b));
3355 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3356 if (b_size == 0) {
3357 PyErr_SetString(PyExc_ZeroDivisionError,
3358 "division by zero");
3359 goto error;
3360 }
3361 if (a_size == 0)
3362 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* Fast path for a and b small (exactly representable in a double).
3365 Relies on floating-point division being correctly rounded; results
3366 may be subject to double rounding on x86 machines that operate with
3367 the x87 FPU set to 64-bit precision. */
3368 a_is_small = a_size <= MANT_DIG_DIGITS ||
3369 (a_size == MANT_DIG_DIGITS+1 &&
3370 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3371 b_is_small = b_size <= MANT_DIG_DIGITS ||
3372 (b_size == MANT_DIG_DIGITS+1 &&
3373 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3374 if (a_is_small && b_is_small) {
3375 double da, db;
3376 da = a->ob_digit[--a_size];
3377 while (a_size > 0)
3378 da = da * PyLong_BASE + a->ob_digit[--a_size];
3379 db = b->ob_digit[--b_size];
3380 while (b_size > 0)
3381 db = db * PyLong_BASE + b->ob_digit[--b_size];
3382 result = da / db;
3383 goto success;
3384 }
Tim Peterse2a60002001-09-04 06:17:36 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* Catch obvious cases of underflow and overflow */
3387 diff = a_size - b_size;
3388 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3389 /* Extreme overflow */
3390 goto overflow;
3391 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3392 /* Extreme underflow */
3393 goto underflow_or_zero;
3394 /* Next line is now safe from overflowing a Py_ssize_t */
3395 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3396 bits_in_digit(b->ob_digit[b_size - 1]);
3397 /* Now diff = a_bits - b_bits. */
3398 if (diff > DBL_MAX_EXP)
3399 goto overflow;
3400 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3401 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 /* Choose value for shift; see comments for step 1 above. */
3404 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 /* x = abs(a * 2**-shift) */
3409 if (shift <= 0) {
3410 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3411 digit rem;
3412 /* x = a << -shift */
3413 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3414 /* In practice, it's probably impossible to end up
3415 here. Both a and b would have to be enormous,
3416 using close to SIZE_T_MAX bytes of memory each. */
3417 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003418 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 goto error;
3420 }
3421 x = _PyLong_New(a_size + shift_digits + 1);
3422 if (x == NULL)
3423 goto error;
3424 for (i = 0; i < shift_digits; i++)
3425 x->ob_digit[i] = 0;
3426 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3427 a_size, -shift % PyLong_SHIFT);
3428 x->ob_digit[a_size + shift_digits] = rem;
3429 }
3430 else {
3431 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3432 digit rem;
3433 /* x = a >> shift */
3434 assert(a_size >= shift_digits);
3435 x = _PyLong_New(a_size - shift_digits);
3436 if (x == NULL)
3437 goto error;
3438 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3439 a_size - shift_digits, shift % PyLong_SHIFT);
3440 /* set inexact if any of the bits shifted out is nonzero */
3441 if (rem)
3442 inexact = 1;
3443 while (!inexact && shift_digits > 0)
3444 if (a->ob_digit[--shift_digits])
3445 inexact = 1;
3446 }
3447 long_normalize(x);
3448 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3451 reference to x, so it's safe to modify it in-place. */
3452 if (b_size == 1) {
3453 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3454 b->ob_digit[0]);
3455 long_normalize(x);
3456 if (rem)
3457 inexact = 1;
3458 }
3459 else {
3460 PyLongObject *div, *rem;
3461 div = x_divrem(x, b, &rem);
3462 Py_DECREF(x);
3463 x = div;
3464 if (x == NULL)
3465 goto error;
3466 if (Py_SIZE(rem))
3467 inexact = 1;
3468 Py_DECREF(rem);
3469 }
3470 x_size = ABS(Py_SIZE(x));
3471 assert(x_size > 0); /* result of division is never zero */
3472 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 /* The number of extra bits that have to be rounded away. */
3475 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3476 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 /* Round by directly modifying the low digit of x. */
3479 mask = (digit)1 << (extra_bits - 1);
3480 low = x->ob_digit[0] | inexact;
3481 if (low & mask && low & (3*mask-1))
3482 low += mask;
3483 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 /* Convert x to a double dx; the conversion is exact. */
3486 dx = x->ob_digit[--x_size];
3487 while (x_size > 0)
3488 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3489 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 /* Check whether ldexp result will overflow a double. */
3492 if (shift + x_bits >= DBL_MAX_EXP &&
3493 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3494 goto overflow;
3495 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003496
3497 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003499
3500 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003502
3503 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 PyErr_SetString(PyExc_OverflowError,
3505 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003506 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003508}
3509
3510static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003511long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 CHECK_BINOP(a, b);
3516
3517 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3518 mod = NULL;
3519 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003520}
3521
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003522static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003523long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 PyLongObject *div, *mod;
3526 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3531 return NULL;
3532 }
3533 z = PyTuple_New(2);
3534 if (z != NULL) {
3535 PyTuple_SetItem(z, 0, (PyObject *) div);
3536 PyTuple_SetItem(z, 1, (PyObject *) mod);
3537 }
3538 else {
3539 Py_DECREF(div);
3540 Py_DECREF(mod);
3541 }
3542 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003543}
3544
Tim Peters47e52ee2004-08-30 02:44:38 +00003545/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003546static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003547long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3550 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 PyLongObject *z = NULL; /* accumulated result */
3553 Py_ssize_t i, j, k; /* counters */
3554 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 /* 5-ary values. If the exponent is large enough, table is
3557 * precomputed so that table[i] == a**i % c for i in range(32).
3558 */
3559 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3560 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 /* a, b, c = v, w, x */
3563 CHECK_BINOP(v, w);
3564 a = (PyLongObject*)v; Py_INCREF(a);
3565 b = (PyLongObject*)w; Py_INCREF(b);
3566 if (PyLong_Check(x)) {
3567 c = (PyLongObject *)x;
3568 Py_INCREF(x);
3569 }
3570 else if (x == Py_None)
3571 c = NULL;
3572 else {
3573 Py_DECREF(a);
3574 Py_DECREF(b);
3575 Py_INCREF(Py_NotImplemented);
3576 return Py_NotImplemented;
3577 }
Tim Peters4c483c42001-09-05 06:24:58 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3580 if (c) {
3581 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003582 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 goto Error;
3584 }
3585 else {
3586 /* else return a float. This works because we know
3587 that this calls float_pow() which converts its
3588 arguments to double. */
3589 Py_DECREF(a);
3590 Py_DECREF(b);
3591 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3592 }
3593 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 if (c) {
3596 /* if modulus == 0:
3597 raise ValueError() */
3598 if (Py_SIZE(c) == 0) {
3599 PyErr_SetString(PyExc_ValueError,
3600 "pow() 3rd argument cannot be 0");
3601 goto Error;
3602 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 /* if modulus < 0:
3605 negativeOutput = True
3606 modulus = -modulus */
3607 if (Py_SIZE(c) < 0) {
3608 negativeOutput = 1;
3609 temp = (PyLongObject *)_PyLong_Copy(c);
3610 if (temp == NULL)
3611 goto Error;
3612 Py_DECREF(c);
3613 c = temp;
3614 temp = NULL;
3615 NEGATE(c);
3616 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 /* if modulus == 1:
3619 return 0 */
3620 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3621 z = (PyLongObject *)PyLong_FromLong(0L);
3622 goto Done;
3623 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 /* if base < 0:
3626 base = base % modulus
3627 Having the base positive just makes things easier. */
3628 if (Py_SIZE(a) < 0) {
3629 if (l_divmod(a, c, NULL, &temp) < 0)
3630 goto Error;
3631 Py_DECREF(a);
3632 a = temp;
3633 temp = NULL;
3634 }
3635 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 /* At this point a, b, and c are guaranteed non-negative UNLESS
3638 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 z = (PyLongObject *)PyLong_FromLong(1L);
3641 if (z == NULL)
3642 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 /* Perform a modular reduction, X = X % c, but leave X alone if c
3645 * is NULL.
3646 */
3647#define REDUCE(X) \
3648 if (c != NULL) { \
3649 if (l_divmod(X, c, NULL, &temp) < 0) \
3650 goto Error; \
3651 Py_XDECREF(X); \
3652 X = temp; \
3653 temp = NULL; \
3654 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 /* Multiply two values, then reduce the result:
3657 result = X*Y % c. If c is NULL, skip the mod. */
3658#define MULT(X, Y, result) \
3659{ \
3660 temp = (PyLongObject *)long_mul(X, Y); \
3661 if (temp == NULL) \
3662 goto Error; \
3663 Py_XDECREF(result); \
3664 result = temp; \
3665 temp = NULL; \
3666 REDUCE(result) \
Tim Peters47e52ee2004-08-30 02:44:38 +00003667}
3668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3670 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3671 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3672 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3673 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
3676 MULT(z, z, z)
3677 if (bi & j)
3678 MULT(z, a, z)
3679 }
3680 }
3681 }
3682 else {
3683 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3684 Py_INCREF(z); /* still holds 1L */
3685 table[0] = z;
3686 for (i = 1; i < 32; ++i)
3687 MULT(table[i-1], a, table[i])
Tim Peters47e52ee2004-08-30 02:44:38 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3690 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3693 const int index = (bi >> j) & 0x1f;
3694 for (k = 0; k < 5; ++k)
3695 MULT(z, z, z)
3696 if (index)
3697 MULT(z, table[index], z)
3698 }
3699 }
3700 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 if (negativeOutput && (Py_SIZE(z) != 0)) {
3703 temp = (PyLongObject *)long_sub(z, c);
3704 if (temp == NULL)
3705 goto Error;
3706 Py_DECREF(z);
3707 z = temp;
3708 temp = NULL;
3709 }
3710 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003711
Mark Dickinson22b20182010-05-10 21:27:53 +00003712 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 if (z != NULL) {
3714 Py_DECREF(z);
3715 z = NULL;
3716 }
3717 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003718 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3720 for (i = 0; i < 32; ++i)
3721 Py_XDECREF(table[i]);
3722 }
3723 Py_DECREF(a);
3724 Py_DECREF(b);
3725 Py_XDECREF(c);
3726 Py_XDECREF(temp);
3727 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003728}
3729
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003730static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003731long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003733 /* Implement ~x as -(x+1) */
3734 PyLongObject *x;
3735 PyLongObject *w;
3736 if (ABS(Py_SIZE(v)) <=1)
3737 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3738 w = (PyLongObject *)PyLong_FromLong(1L);
3739 if (w == NULL)
3740 return NULL;
3741 x = (PyLongObject *) long_add(v, w);
3742 Py_DECREF(w);
3743 if (x == NULL)
3744 return NULL;
3745 Py_SIZE(x) = -(Py_SIZE(x));
3746 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003747}
3748
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003749static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003750long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 PyLongObject *z;
3753 if (ABS(Py_SIZE(v)) <= 1)
3754 return PyLong_FromLong(-MEDIUM_VALUE(v));
3755 z = (PyLongObject *)_PyLong_Copy(v);
3756 if (z != NULL)
3757 Py_SIZE(z) = -(Py_SIZE(v));
3758 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003759}
3760
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003761static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003762long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 if (Py_SIZE(v) < 0)
3765 return long_neg(v);
3766 else
3767 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003768}
3769
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003770static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003771long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003774}
3775
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003776static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003777long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 PyLongObject *z = NULL;
3780 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3781 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003785 if (Py_SIZE(a) < 0) {
3786 /* Right shifting negative numbers is harder */
3787 PyLongObject *a1, *a2;
3788 a1 = (PyLongObject *) long_invert(a);
3789 if (a1 == NULL)
3790 goto rshift_error;
3791 a2 = (PyLongObject *) long_rshift(a1, b);
3792 Py_DECREF(a1);
3793 if (a2 == NULL)
3794 goto rshift_error;
3795 z = (PyLongObject *) long_invert(a2);
3796 Py_DECREF(a2);
3797 }
3798 else {
3799 shiftby = PyLong_AsSsize_t((PyObject *)b);
3800 if (shiftby == -1L && PyErr_Occurred())
3801 goto rshift_error;
3802 if (shiftby < 0) {
3803 PyErr_SetString(PyExc_ValueError,
3804 "negative shift count");
3805 goto rshift_error;
3806 }
3807 wordshift = shiftby / PyLong_SHIFT;
3808 newsize = ABS(Py_SIZE(a)) - wordshift;
3809 if (newsize <= 0)
3810 return PyLong_FromLong(0);
3811 loshift = shiftby % PyLong_SHIFT;
3812 hishift = PyLong_SHIFT - loshift;
3813 lomask = ((digit)1 << hishift) - 1;
3814 himask = PyLong_MASK ^ lomask;
3815 z = _PyLong_New(newsize);
3816 if (z == NULL)
3817 goto rshift_error;
3818 if (Py_SIZE(a) < 0)
3819 Py_SIZE(z) = -(Py_SIZE(z));
3820 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3821 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3822 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003823 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 }
3825 z = long_normalize(z);
3826 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003827 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003829
Guido van Rossumc6913e71991-11-19 20:26:46 +00003830}
3831
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003832static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003833long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 /* This version due to Tim Peters */
3836 PyLongObject *a = (PyLongObject*)v;
3837 PyLongObject *b = (PyLongObject*)w;
3838 PyLongObject *z = NULL;
3839 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3840 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 shiftby = PyLong_AsSsize_t((PyObject *)b);
3845 if (shiftby == -1L && PyErr_Occurred())
3846 goto lshift_error;
3847 if (shiftby < 0) {
3848 PyErr_SetString(PyExc_ValueError, "negative shift count");
3849 goto lshift_error;
3850 }
3851 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3852 wordshift = shiftby / PyLong_SHIFT;
3853 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003855 oldsize = ABS(Py_SIZE(a));
3856 newsize = oldsize + wordshift;
3857 if (remshift)
3858 ++newsize;
3859 z = _PyLong_New(newsize);
3860 if (z == NULL)
3861 goto lshift_error;
3862 if (Py_SIZE(a) < 0)
3863 NEGATE(z);
3864 for (i = 0; i < wordshift; i++)
3865 z->ob_digit[i] = 0;
3866 accum = 0;
3867 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3868 accum |= (twodigits)a->ob_digit[j] << remshift;
3869 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3870 accum >>= PyLong_SHIFT;
3871 }
3872 if (remshift)
3873 z->ob_digit[newsize-1] = (digit)accum;
3874 else
3875 assert(!accum);
3876 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003877 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003879}
3880
Mark Dickinson27a87a22009-10-25 20:43:34 +00003881/* Compute two's complement of digit vector a[0:m], writing result to
3882 z[0:m]. The digit vector a need not be normalized, but should not
3883 be entirely zero. a and z may point to the same digit vector. */
3884
3885static void
3886v_complement(digit *z, digit *a, Py_ssize_t m)
3887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 Py_ssize_t i;
3889 digit carry = 1;
3890 for (i = 0; i < m; ++i) {
3891 carry += a[i] ^ PyLong_MASK;
3892 z[i] = carry & PyLong_MASK;
3893 carry >>= PyLong_SHIFT;
3894 }
3895 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003896}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003897
3898/* Bitwise and/xor/or operations */
3899
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003900static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003901long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003903 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 int nega, negb, negz;
3906 Py_ssize_t size_a, size_b, size_z, i;
3907 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 /* Bitwise operations for negative numbers operate as though
3910 on a two's complement representation. So convert arguments
3911 from sign-magnitude to two's complement, and convert the
3912 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 /* If a is negative, replace it by its two's complement. */
3915 size_a = ABS(Py_SIZE(a));
3916 nega = Py_SIZE(a) < 0;
3917 if (nega) {
3918 z = _PyLong_New(size_a);
3919 if (z == NULL)
3920 return NULL;
3921 v_complement(z->ob_digit, a->ob_digit, size_a);
3922 a = z;
3923 }
3924 else
3925 /* Keep reference count consistent. */
3926 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 /* Same for b. */
3929 size_b = ABS(Py_SIZE(b));
3930 negb = Py_SIZE(b) < 0;
3931 if (negb) {
3932 z = _PyLong_New(size_b);
3933 if (z == NULL) {
3934 Py_DECREF(a);
3935 return NULL;
3936 }
3937 v_complement(z->ob_digit, b->ob_digit, size_b);
3938 b = z;
3939 }
3940 else
3941 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 /* Swap a and b if necessary to ensure size_a >= size_b. */
3944 if (size_a < size_b) {
3945 z = a; a = b; b = z;
3946 size_z = size_a; size_a = size_b; size_b = size_z;
3947 negz = nega; nega = negb; negb = negz;
3948 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 /* JRH: The original logic here was to allocate the result value (z)
3951 as the longer of the two operands. However, there are some cases
3952 where the result is guaranteed to be shorter than that: AND of two
3953 positives, OR of two negatives: use the shorter number. AND with
3954 mixed signs: use the positive number. OR with mixed signs: use the
3955 negative number.
3956 */
3957 switch (op) {
3958 case '^':
3959 negz = nega ^ negb;
3960 size_z = size_a;
3961 break;
3962 case '&':
3963 negz = nega & negb;
3964 size_z = negb ? size_a : size_b;
3965 break;
3966 case '|':
3967 negz = nega | negb;
3968 size_z = negb ? size_b : size_a;
3969 break;
3970 default:
3971 PyErr_BadArgument();
3972 return NULL;
3973 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* We allow an extra digit if z is negative, to make sure that
3976 the final two's complement of z doesn't overflow. */
3977 z = _PyLong_New(size_z + negz);
3978 if (z == NULL) {
3979 Py_DECREF(a);
3980 Py_DECREF(b);
3981 return NULL;
3982 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003984 /* Compute digits for overlap of a and b. */
3985 switch(op) {
3986 case '&':
3987 for (i = 0; i < size_b; ++i)
3988 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
3989 break;
3990 case '|':
3991 for (i = 0; i < size_b; ++i)
3992 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
3993 break;
3994 case '^':
3995 for (i = 0; i < size_b; ++i)
3996 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
3997 break;
3998 default:
3999 PyErr_BadArgument();
4000 return NULL;
4001 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 /* Copy any remaining digits of a, inverting if necessary. */
4004 if (op == '^' && negb)
4005 for (; i < size_z; ++i)
4006 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4007 else if (i < size_z)
4008 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4009 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 /* Complement result if negative. */
4012 if (negz) {
4013 Py_SIZE(z) = -(Py_SIZE(z));
4014 z->ob_digit[size_z] = PyLong_MASK;
4015 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4016 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 Py_DECREF(a);
4019 Py_DECREF(b);
4020 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004021}
4022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004023static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004024long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 PyObject *c;
4027 CHECK_BINOP(a, b);
4028 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4029 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004030}
4031
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004032static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004033long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 PyObject *c;
4036 CHECK_BINOP(a, b);
4037 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4038 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004039}
4040
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004041static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004042long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 PyObject *c;
4045 CHECK_BINOP(a, b);
4046 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4047 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004048}
4049
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004050static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004051long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 if (PyLong_CheckExact(v))
4054 Py_INCREF(v);
4055 else
4056 v = _PyLong_Copy((PyLongObject *)v);
4057 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004058}
4059
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004060static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004061long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 double result;
4064 result = PyLong_AsDouble(v);
4065 if (result == -1.0 && PyErr_Occurred())
4066 return NULL;
4067 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004068}
4069
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004070static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004071long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004072
Tim Peters6d6c1a32001-08-02 04:15:00 +00004073static PyObject *
4074long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 PyObject *x = NULL;
4077 int base = -909; /* unlikely! */
4078 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 if (type != &PyLong_Type)
4081 return long_subtype_new(type, args, kwds); /* Wimp out */
4082 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
4083 &x, &base))
4084 return NULL;
4085 if (x == NULL)
4086 return PyLong_FromLong(0L);
4087 if (base == -909)
4088 return PyNumber_Long(x);
4089 else if (PyUnicode_Check(x))
4090 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4091 PyUnicode_GET_SIZE(x),
4092 base);
4093 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4094 /* Since PyLong_FromString doesn't have a length parameter,
4095 * check here for possible NULs in the string. */
4096 char *string;
4097 Py_ssize_t size = Py_SIZE(x);
4098 if (PyByteArray_Check(x))
4099 string = PyByteArray_AS_STRING(x);
4100 else
4101 string = PyBytes_AS_STRING(x);
4102 if (strlen(string) != (size_t)size) {
4103 /* We only see this if there's a null byte in x,
4104 x is a bytes or buffer, *and* a base is given. */
4105 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004106 "invalid literal for int() with base %d: %R",
4107 base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 return NULL;
4109 }
4110 return PyLong_FromString(string, NULL, base);
4111 }
4112 else {
4113 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004114 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 return NULL;
4116 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004117}
4118
Guido van Rossumbef14172001-08-29 15:47:46 +00004119/* Wimpy, slow approach to tp_new calls for subtypes of long:
4120 first create a regular long from whatever arguments we got,
4121 then allocate a subtype instance and initialize it from
4122 the regular long. The regular long is then thrown away.
4123*/
4124static PyObject *
4125long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 PyLongObject *tmp, *newobj;
4128 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 assert(PyType_IsSubtype(type, &PyLong_Type));
4131 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4132 if (tmp == NULL)
4133 return NULL;
4134 assert(PyLong_CheckExact(tmp));
4135 n = Py_SIZE(tmp);
4136 if (n < 0)
4137 n = -n;
4138 newobj = (PyLongObject *)type->tp_alloc(type, n);
4139 if (newobj == NULL) {
4140 Py_DECREF(tmp);
4141 return NULL;
4142 }
4143 assert(PyLong_Check(newobj));
4144 Py_SIZE(newobj) = Py_SIZE(tmp);
4145 for (i = 0; i < n; i++)
4146 newobj->ob_digit[i] = tmp->ob_digit[i];
4147 Py_DECREF(tmp);
4148 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004149}
4150
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004151static PyObject *
4152long_getnewargs(PyLongObject *v)
4153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004155}
4156
Guido van Rossumb43daf72007-08-01 18:08:08 +00004157static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004158long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004160}
4161
4162static PyObject *
4163long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004165}
4166
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004167static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004168long__format__(PyObject *self, PyObject *args)
4169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4173 return NULL;
4174 return _PyLong_FormatAdvanced(self,
4175 PyUnicode_AS_UNICODE(format_spec),
4176 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004177}
4178
Eric Smith8c663262007-08-25 02:26:07 +00004179static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004180long_round(PyObject *self, PyObject *args)
4181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 PyObject *o_ndigits=NULL, *temp;
4183 PyLongObject *pow=NULL, *q=NULL, *r=NULL, *ndigits=NULL, *one;
4184 int errcode;
4185 digit q_mod_4;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004187 /* Notes on the algorithm: to round to the nearest 10**n (n positive),
4188 the straightforward method is:
Mark Dickinson1124e712009-01-28 21:25:58 +00004189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 (1) divide by 10**n
4191 (2) round to nearest integer (round to even in case of tie)
4192 (3) multiply result by 10**n.
Mark Dickinson1124e712009-01-28 21:25:58 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 But the rounding step involves examining the fractional part of the
4195 quotient to see whether it's greater than 0.5 or not. Since we
4196 want to do the whole calculation in integer arithmetic, it's
4197 simpler to do:
Mark Dickinson1124e712009-01-28 21:25:58 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 (1) divide by (10**n)/2
4200 (2) round to nearest multiple of 2 (multiple of 4 in case of tie)
4201 (3) multiply result by (10**n)/2.
Mark Dickinson1124e712009-01-28 21:25:58 +00004202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 Then all we need to know about the fractional part of the quotient
4204 arising in step (2) is whether it's zero or not.
Mark Dickinson1124e712009-01-28 21:25:58 +00004205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 Doing both a multiplication and division is wasteful, and is easily
4207 avoided if we just figure out how much to adjust the original input
4208 by to do the rounding.
Mark Dickinson1124e712009-01-28 21:25:58 +00004209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004210 Here's the whole algorithm expressed in Python.
Mark Dickinson1124e712009-01-28 21:25:58 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 def round(self, ndigits = None):
4213 """round(int, int) -> int"""
4214 if ndigits is None or ndigits >= 0:
4215 return self
4216 pow = 10**-ndigits >> 1
4217 q, r = divmod(self, pow)
4218 self -= r
4219 if (q & 1 != 0):
4220 if (q & 2 == r == 0):
4221 self -= pow
4222 else:
4223 self += pow
4224 return self
Mark Dickinson1124e712009-01-28 21:25:58 +00004225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 */
4227 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4228 return NULL;
4229 if (o_ndigits == NULL)
4230 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 ndigits = (PyLongObject *)PyNumber_Index(o_ndigits);
4233 if (ndigits == NULL)
4234 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 if (Py_SIZE(ndigits) >= 0) {
4237 Py_DECREF(ndigits);
4238 return long_long(self);
4239 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 Py_INCREF(self); /* to keep refcounting simple */
4242 /* we now own references to self, ndigits */
Mark Dickinson1124e712009-01-28 21:25:58 +00004243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 /* pow = 10 ** -ndigits >> 1 */
4245 pow = (PyLongObject *)PyLong_FromLong(10L);
4246 if (pow == NULL)
4247 goto error;
4248 temp = long_neg(ndigits);
4249 Py_DECREF(ndigits);
4250 ndigits = (PyLongObject *)temp;
4251 if (ndigits == NULL)
4252 goto error;
4253 temp = long_pow((PyObject *)pow, (PyObject *)ndigits, Py_None);
4254 Py_DECREF(pow);
4255 pow = (PyLongObject *)temp;
4256 if (pow == NULL)
4257 goto error;
4258 assert(PyLong_Check(pow)); /* check long_pow returned a long */
4259 one = (PyLongObject *)PyLong_FromLong(1L);
4260 if (one == NULL)
4261 goto error;
4262 temp = long_rshift(pow, one);
4263 Py_DECREF(one);
4264 Py_DECREF(pow);
4265 pow = (PyLongObject *)temp;
4266 if (pow == NULL)
4267 goto error;
Mark Dickinson1124e712009-01-28 21:25:58 +00004268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 /* q, r = divmod(self, pow) */
4270 errcode = l_divmod((PyLongObject *)self, pow, &q, &r);
4271 if (errcode == -1)
4272 goto error;
Mark Dickinson1124e712009-01-28 21:25:58 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 /* self -= r */
4275 temp = long_sub((PyLongObject *)self, r);
4276 Py_DECREF(self);
4277 self = temp;
4278 if (self == NULL)
4279 goto error;
Mark Dickinson1124e712009-01-28 21:25:58 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 /* get value of quotient modulo 4 */
4282 if (Py_SIZE(q) == 0)
4283 q_mod_4 = 0;
4284 else if (Py_SIZE(q) > 0)
4285 q_mod_4 = q->ob_digit[0] & 3;
4286 else
4287 q_mod_4 = (PyLong_BASE-q->ob_digit[0]) & 3;
Mark Dickinson1124e712009-01-28 21:25:58 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 if ((q_mod_4 & 1) == 1) {
4290 /* q is odd; round self up or down by adding or subtracting pow */
4291 if (q_mod_4 == 1 && Py_SIZE(r) == 0)
4292 temp = (PyObject *)long_sub((PyLongObject *)self, pow);
4293 else
4294 temp = (PyObject *)long_add((PyLongObject *)self, pow);
4295 Py_DECREF(self);
4296 self = temp;
4297 if (self == NULL)
4298 goto error;
4299 }
4300 Py_DECREF(q);
4301 Py_DECREF(r);
4302 Py_DECREF(pow);
4303 Py_DECREF(ndigits);
4304 return self;
Mark Dickinson1124e712009-01-28 21:25:58 +00004305
4306 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 Py_XDECREF(q);
4308 Py_XDECREF(r);
4309 Py_XDECREF(pow);
4310 Py_XDECREF(self);
4311 Py_XDECREF(ndigits);
4312 return NULL;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004313}
4314
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004315static PyObject *
4316long_sizeof(PyLongObject *v)
4317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004318 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4321 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004322}
4323
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004324static PyObject *
4325long_bit_length(PyLongObject *v)
4326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 PyLongObject *result, *x, *y;
4328 Py_ssize_t ndigits, msd_bits = 0;
4329 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 assert(v != NULL);
4332 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 ndigits = ABS(Py_SIZE(v));
4335 if (ndigits == 0)
4336 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004338 msd = v->ob_digit[ndigits-1];
4339 while (msd >= 32) {
4340 msd_bits += 6;
4341 msd >>= 6;
4342 }
4343 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4346 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 /* expression above may overflow; use Python integers instead */
4349 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4350 if (result == NULL)
4351 return NULL;
4352 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4353 if (x == NULL)
4354 goto error;
4355 y = (PyLongObject *)long_mul(result, x);
4356 Py_DECREF(x);
4357 if (y == NULL)
4358 goto error;
4359 Py_DECREF(result);
4360 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4363 if (x == NULL)
4364 goto error;
4365 y = (PyLongObject *)long_add(result, x);
4366 Py_DECREF(x);
4367 if (y == NULL)
4368 goto error;
4369 Py_DECREF(result);
4370 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004373
Mark Dickinson22b20182010-05-10 21:27:53 +00004374 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 Py_DECREF(result);
4376 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004377}
4378
4379PyDoc_STRVAR(long_bit_length_doc,
4380"int.bit_length() -> int\n\
4381\n\
4382Number of bits necessary to represent self in binary.\n\
4383>>> bin(37)\n\
4384'0b100101'\n\
4385>>> (37).bit_length()\n\
43866");
4387
Christian Heimes53876d92008-04-19 00:31:39 +00004388#if 0
4389static PyObject *
4390long_is_finite(PyObject *v)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004393}
4394#endif
4395
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004396
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004397static PyObject *
4398long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 PyObject *byteorder_str;
4401 PyObject *is_signed_obj = NULL;
4402 Py_ssize_t length;
4403 int little_endian;
4404 int is_signed;
4405 PyObject *bytes;
4406 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4409 &length, &byteorder_str,
4410 &is_signed_obj))
4411 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 if (args != NULL && Py_SIZE(args) > 2) {
4414 PyErr_SetString(PyExc_TypeError,
4415 "'signed' is a keyword-only argument");
4416 return NULL;
4417 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4420 little_endian = 1;
4421 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4422 little_endian = 0;
4423 else {
4424 PyErr_SetString(PyExc_ValueError,
4425 "byteorder must be either 'little' or 'big'");
4426 return NULL;
4427 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 if (is_signed_obj != NULL) {
4430 int cmp = PyObject_IsTrue(is_signed_obj);
4431 if (cmp < 0)
4432 return NULL;
4433 is_signed = cmp ? 1 : 0;
4434 }
4435 else {
4436 /* If the signed argument was omitted, use False as the
4437 default. */
4438 is_signed = 0;
4439 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 if (length < 0) {
4442 PyErr_SetString(PyExc_ValueError,
4443 "length argument must be non-negative");
4444 return NULL;
4445 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 bytes = PyBytes_FromStringAndSize(NULL, length);
4448 if (bytes == NULL)
4449 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4452 length, little_endian, is_signed) < 0) {
4453 Py_DECREF(bytes);
4454 return NULL;
4455 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004458}
4459
Mark Dickinson078c2532010-01-30 18:06:17 +00004460PyDoc_STRVAR(long_to_bytes_doc,
4461"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004462\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004463Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004464\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004466raised if the integer is not representable with the given number of\n\
4467bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004468\n\
4469The byteorder argument determines the byte order used to represent the\n\
4470integer. If byteorder is 'big', the most significant byte is at the\n\
4471beginning of the byte array. If byteorder is 'little', the most\n\
4472significant byte is at the end of the byte array. To request the native\n\
4473byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4474\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004475The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004477is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004478
4479static PyObject *
4480long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 PyObject *byteorder_str;
4483 PyObject *is_signed_obj = NULL;
4484 int little_endian;
4485 int is_signed;
4486 PyObject *obj;
4487 PyObject *bytes;
4488 PyObject *long_obj;
4489 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4492 &obj, &byteorder_str,
4493 &is_signed_obj))
4494 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004496 if (args != NULL && Py_SIZE(args) > 2) {
4497 PyErr_SetString(PyExc_TypeError,
4498 "'signed' is a keyword-only argument");
4499 return NULL;
4500 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4503 little_endian = 1;
4504 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4505 little_endian = 0;
4506 else {
4507 PyErr_SetString(PyExc_ValueError,
4508 "byteorder must be either 'little' or 'big'");
4509 return NULL;
4510 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 if (is_signed_obj != NULL) {
4513 int cmp = PyObject_IsTrue(is_signed_obj);
4514 if (cmp < 0)
4515 return NULL;
4516 is_signed = cmp ? 1 : 0;
4517 }
4518 else {
4519 /* If the signed argument was omitted, use False as the
4520 default. */
4521 is_signed = 0;
4522 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 bytes = PyObject_Bytes(obj);
4525 if (bytes == NULL)
4526 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 long_obj = _PyLong_FromByteArray(
4529 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4530 little_endian, is_signed);
4531 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 /* If from_bytes() was used on subclass, allocate new subclass
4534 * instance, initialize it with decoded long value and return it.
4535 */
4536 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4537 PyLongObject *newobj;
4538 int i;
4539 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 newobj = (PyLongObject *)type->tp_alloc(type, n);
4542 if (newobj == NULL) {
4543 Py_DECREF(long_obj);
4544 return NULL;
4545 }
4546 assert(PyLong_Check(newobj));
4547 Py_SIZE(newobj) = Py_SIZE(long_obj);
4548 for (i = 0; i < n; i++) {
4549 newobj->ob_digit[i] =
4550 ((PyLongObject *)long_obj)->ob_digit[i];
4551 }
4552 Py_DECREF(long_obj);
4553 return (PyObject *)newobj;
4554 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004557}
4558
Mark Dickinson078c2532010-01-30 18:06:17 +00004559PyDoc_STRVAR(long_from_bytes_doc,
4560"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4561\n\
4562Return the integer represented by the given array of bytes.\n\
4563\n\
4564The bytes argument must either support the buffer protocol or be an\n\
4565iterable object producing bytes. Bytes and bytearray are examples of\n\
4566built-in objects that support the buffer protocol.\n\
4567\n\
4568The byteorder argument determines the byte order used to represent the\n\
4569integer. If byteorder is 'big', the most significant byte is at the\n\
4570beginning of the byte array. If byteorder is 'little', the most\n\
4571significant byte is at the end of the byte array. To request the native\n\
4572byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4573\n\
4574The signed keyword-only argument indicates whether two's complement is\n\
4575used to represent the integer.");
4576
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004577static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4579 "Returns self, the complex conjugate of any int."},
4580 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4581 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004582#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4584 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004585#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 {"to_bytes", (PyCFunction)long_to_bytes,
4587 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4588 {"from_bytes", (PyCFunction)long_from_bytes,
4589 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4590 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4591 "Truncating an Integral returns itself."},
4592 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4593 "Flooring an Integral returns itself."},
4594 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4595 "Ceiling of an Integral returns itself."},
4596 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4597 "Rounding an Integral returns itself.\n"
4598 "Rounding with an ndigits argument also returns an integer."},
4599 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4600 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4601 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4602 "Returns size in memory, in bytes"},
4603 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004604};
4605
Guido van Rossumb43daf72007-08-01 18:08:08 +00004606static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004607 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004608 (getter)long_long, (setter)NULL,
4609 "the real part of a complex number",
4610 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004611 {"imag",
4612 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004613 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004614 NULL},
4615 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004616 (getter)long_long, (setter)NULL,
4617 "the numerator of a rational number in lowest terms",
4618 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004619 {"denominator",
4620 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004621 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004622 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004623 {NULL} /* Sentinel */
4624};
4625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004626PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004627"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004628\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004629Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004630point argument will be truncated towards zero (this does not include a\n\
4631string representation of a floating point number!) When converting a\n\
4632string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004633converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004634
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004635static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004636 (binaryfunc)long_add, /*nb_add*/
4637 (binaryfunc)long_sub, /*nb_subtract*/
4638 (binaryfunc)long_mul, /*nb_multiply*/
4639 long_mod, /*nb_remainder*/
4640 long_divmod, /*nb_divmod*/
4641 long_pow, /*nb_power*/
4642 (unaryfunc)long_neg, /*nb_negative*/
4643 (unaryfunc)long_long, /*tp_positive*/
4644 (unaryfunc)long_abs, /*tp_absolute*/
4645 (inquiry)long_bool, /*tp_bool*/
4646 (unaryfunc)long_invert, /*nb_invert*/
4647 long_lshift, /*nb_lshift*/
4648 (binaryfunc)long_rshift, /*nb_rshift*/
4649 long_and, /*nb_and*/
4650 long_xor, /*nb_xor*/
4651 long_or, /*nb_or*/
4652 long_long, /*nb_int*/
4653 0, /*nb_reserved*/
4654 long_float, /*nb_float*/
4655 0, /* nb_inplace_add */
4656 0, /* nb_inplace_subtract */
4657 0, /* nb_inplace_multiply */
4658 0, /* nb_inplace_remainder */
4659 0, /* nb_inplace_power */
4660 0, /* nb_inplace_lshift */
4661 0, /* nb_inplace_rshift */
4662 0, /* nb_inplace_and */
4663 0, /* nb_inplace_xor */
4664 0, /* nb_inplace_or */
4665 long_div, /* nb_floor_divide */
4666 long_true_divide, /* nb_true_divide */
4667 0, /* nb_inplace_floor_divide */
4668 0, /* nb_inplace_true_divide */
4669 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004670};
4671
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004672PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4674 "int", /* tp_name */
4675 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4676 sizeof(digit), /* tp_itemsize */
4677 long_dealloc, /* tp_dealloc */
4678 0, /* tp_print */
4679 0, /* tp_getattr */
4680 0, /* tp_setattr */
4681 0, /* tp_reserved */
4682 long_to_decimal_string, /* tp_repr */
4683 &long_as_number, /* tp_as_number */
4684 0, /* tp_as_sequence */
4685 0, /* tp_as_mapping */
4686 (hashfunc)long_hash, /* tp_hash */
4687 0, /* tp_call */
4688 long_to_decimal_string, /* tp_str */
4689 PyObject_GenericGetAttr, /* tp_getattro */
4690 0, /* tp_setattro */
4691 0, /* tp_as_buffer */
4692 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4693 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4694 long_doc, /* tp_doc */
4695 0, /* tp_traverse */
4696 0, /* tp_clear */
4697 long_richcompare, /* tp_richcompare */
4698 0, /* tp_weaklistoffset */
4699 0, /* tp_iter */
4700 0, /* tp_iternext */
4701 long_methods, /* tp_methods */
4702 0, /* tp_members */
4703 long_getset, /* tp_getset */
4704 0, /* tp_base */
4705 0, /* tp_dict */
4706 0, /* tp_descr_get */
4707 0, /* tp_descr_set */
4708 0, /* tp_dictoffset */
4709 0, /* tp_init */
4710 0, /* tp_alloc */
4711 long_new, /* tp_new */
4712 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004713};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004714
Mark Dickinsonbd792642009-03-18 20:06:12 +00004715static PyTypeObject Int_InfoType;
4716
4717PyDoc_STRVAR(int_info__doc__,
4718"sys.int_info\n\
4719\n\
4720A struct sequence that holds information about Python's\n\
4721internal representation of integers. The attributes are read only.");
4722
4723static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004725 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004727};
4728
4729static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 "sys.int_info", /* name */
4731 int_info__doc__, /* doc */
4732 int_info_fields, /* fields */
4733 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004734};
4735
4736PyObject *
4737PyLong_GetInfo(void)
4738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 PyObject* int_info;
4740 int field = 0;
4741 int_info = PyStructSequence_New(&Int_InfoType);
4742 if (int_info == NULL)
4743 return NULL;
4744 PyStructSequence_SET_ITEM(int_info, field++,
4745 PyLong_FromLong(PyLong_SHIFT));
4746 PyStructSequence_SET_ITEM(int_info, field++,
4747 PyLong_FromLong(sizeof(digit)));
4748 if (PyErr_Occurred()) {
4749 Py_CLEAR(int_info);
4750 return NULL;
4751 }
4752 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004753}
4754
Guido van Rossumddefaf32007-01-14 03:31:43 +00004755int
4756_PyLong_Init(void)
4757{
4758#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 int ival, size;
4760 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4763 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4764 if (Py_TYPE(v) == &PyLong_Type) {
4765 /* The element is already initialized, most likely
4766 * the Python interpreter was initialized before.
4767 */
4768 Py_ssize_t refcnt;
4769 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4772 _Py_NewReference(op);
4773 /* _Py_NewReference sets the ref count to 1 but
4774 * the ref count might be larger. Set the refcnt
4775 * to the original refcnt + 1 */
4776 Py_REFCNT(op) = refcnt + 1;
4777 assert(Py_SIZE(op) == size);
4778 assert(v->ob_digit[0] == abs(ival));
4779 }
4780 else {
4781 PyObject_INIT(v, &PyLong_Type);
4782 }
4783 Py_SIZE(v) = size;
4784 v->ob_digit[0] = abs(ival);
4785 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004786#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 /* initialize int_info */
4788 if (Int_InfoType.tp_name == 0)
4789 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004792}
4793
4794void
4795PyLong_Fini(void)
4796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 /* Integers are currently statically allocated. Py_DECREF is not
4798 needed, but Python must forget about the reference or multiple
4799 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004800#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 int i;
4802 PyLongObject *v = small_ints;
4803 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4804 _Py_DEC_REFTOTAL;
4805 _Py_ForgetReference((PyObject*)v);
4806 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004807#endif
4808}