blob: e8a728489b605621fcae31c090bdf459761c9f36 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
33int quick_int_allocs, quick_neg_int_allocs;
34#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
159 sdigit ival = src->ob_digit[0];
160 if (Py_SIZE(src) < 0)
161 ival = -ival;
162 CHECK_SMALL_INT(ival);
163 }
164 result = _PyLong_New(i);
165 if (result != NULL) {
166 Py_SIZE(result) = Py_SIZE(src);
167 while (--i >= 0)
168 result->ob_digit[i] = src->ob_digit[i];
169 }
170 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000171}
172
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000173/* Create a new long int object from a C long int */
174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000176PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyLongObject *v;
179 unsigned long abs_ival;
180 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
181 int ndigits = 0;
182 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (ival < 0) {
187 /* negate: can't write this as abs_ival = -ival since that
188 invokes undefined behaviour when ival is LONG_MIN */
189 abs_ival = 0U-(unsigned long)ival;
190 sign = -1;
191 }
192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Fast path for single-digit ints */
197 if (!(abs_ival >> PyLong_SHIFT)) {
198 v = _PyLong_New(1);
199 if (v) {
200 Py_SIZE(v) = sign;
201 v->ob_digit[0] = Py_SAFE_DOWNCAST(
202 abs_ival, unsigned long, digit);
203 }
204 return (PyObject*)v;
205 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206
Mark Dickinson249b8982009-04-27 19:41:00 +0000207#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* 2 digits */
209 if (!(abs_ival >> 2*PyLong_SHIFT)) {
210 v = _PyLong_New(2);
211 if (v) {
212 Py_SIZE(v) = 2*sign;
213 v->ob_digit[0] = Py_SAFE_DOWNCAST(
214 abs_ival & PyLong_MASK, unsigned long, digit);
215 v->ob_digit[1] = Py_SAFE_DOWNCAST(
216 abs_ival >> PyLong_SHIFT, unsigned long, digit);
217 }
218 return (PyObject*)v;
219 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000220#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 /* Larger numbers: loop to determine number of digits */
223 t = abs_ival;
224 while (t) {
225 ++ndigits;
226 t >>= PyLong_SHIFT;
227 }
228 v = _PyLong_New(ndigits);
229 if (v != NULL) {
230 digit *p = v->ob_digit;
231 Py_SIZE(v) = ndigits*sign;
232 t = abs_ival;
233 while (t) {
234 *p++ = Py_SAFE_DOWNCAST(
235 t & PyLong_MASK, unsigned long, digit);
236 t >>= PyLong_SHIFT;
237 }
238 }
239 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240}
241
Guido van Rossum53756b11997-01-03 17:14:46 +0000242/* Create a new long int object from a C unsigned long int */
243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000245PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyLongObject *v;
248 unsigned long t;
249 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (ival < PyLong_BASE)
252 return PyLong_FromLong(ival);
253 /* Count the number of Python digits. */
254 t = (unsigned long)ival;
255 while (t) {
256 ++ndigits;
257 t >>= PyLong_SHIFT;
258 }
259 v = _PyLong_New(ndigits);
260 if (v != NULL) {
261 digit *p = v->ob_digit;
262 Py_SIZE(v) = ndigits;
263 while (ival) {
264 *p++ = (digit)(ival & PyLong_MASK);
265 ival >>= PyLong_SHIFT;
266 }
267 }
268 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000269}
270
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271/* Create a new long int object from a C double */
272
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 PyLongObject *v;
277 double frac;
278 int i, ndig, expo, neg;
279 neg = 0;
280 if (Py_IS_INFINITY(dval)) {
281 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000282 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
284 }
285 if (Py_IS_NAN(dval)) {
286 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000287 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return NULL;
289 }
290 if (dval < 0.0) {
291 neg = 1;
292 dval = -dval;
293 }
294 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
295 if (expo <= 0)
296 return PyLong_FromLong(0L);
297 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
298 v = _PyLong_New(ndig);
299 if (v == NULL)
300 return NULL;
301 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
302 for (i = ndig; --i >= 0; ) {
303 digit bits = (digit)frac;
304 v->ob_digit[i] = bits;
305 frac = frac - (double)bits;
306 frac = ldexp(frac, PyLong_SHIFT);
307 }
308 if (neg)
309 Py_SIZE(v) = -(Py_SIZE(v));
310 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000311}
312
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
314 * anything about what happens when a signed integer operation overflows,
315 * and some compilers think they're doing you a favor by being "clever"
316 * then. The bit pattern for the largest postive signed long is
317 * (unsigned long)LONG_MAX, and for the smallest negative signed long
318 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
319 * However, some other compilers warn about applying unary minus to an
320 * unsigned operand. Hence the weird "0-".
321 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
323#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000325/* Get a C long int from a long int object.
326 Returns -1 and sets an error condition if overflow occurs. */
327
328long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000329PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* This version by Tim Peters */
332 register PyLongObject *v;
333 unsigned long x, prev;
334 long res;
335 Py_ssize_t i;
336 int sign;
337 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 *overflow = 0;
340 if (vv == NULL) {
341 PyErr_BadInternalCall();
342 return -1;
343 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (!PyLong_Check(vv)) {
346 PyNumberMethods *nb;
347 nb = vv->ob_type->tp_as_number;
348 if (nb == NULL || nb->nb_int == NULL) {
349 PyErr_SetString(PyExc_TypeError,
350 "an integer is required");
351 return -1;
352 }
353 vv = (*nb->nb_int) (vv);
354 if (vv == NULL)
355 return -1;
356 do_decref = 1;
357 if (!PyLong_Check(vv)) {
358 Py_DECREF(vv);
359 PyErr_SetString(PyExc_TypeError,
360 "nb_int should return int object");
361 return -1;
362 }
363 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 res = -1;
366 v = (PyLongObject *)vv;
367 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 switch (i) {
370 case -1:
371 res = -(sdigit)v->ob_digit[0];
372 break;
373 case 0:
374 res = 0;
375 break;
376 case 1:
377 res = v->ob_digit[0];
378 break;
379 default:
380 sign = 1;
381 x = 0;
382 if (i < 0) {
383 sign = -1;
384 i = -(i);
385 }
386 while (--i >= 0) {
387 prev = x;
388 x = (x << PyLong_SHIFT) | v->ob_digit[i];
389 if ((x >> PyLong_SHIFT) != prev) {
390 *overflow = sign;
391 goto exit;
392 }
393 }
394 /* Haven't lost any bits, but casting to long requires extra
395 * care (see comment above).
396 */
397 if (x <= (unsigned long)LONG_MAX) {
398 res = (long)x * sign;
399 }
400 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
401 res = LONG_MIN;
402 }
403 else {
404 *overflow = sign;
405 /* res is already set to -1 */
406 }
407 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000408 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (do_decref) {
410 Py_DECREF(vv);
411 }
412 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000413}
414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000416PyLong_AsLong(PyObject *obj)
417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 int overflow;
419 long result = PyLong_AsLongAndOverflow(obj, &overflow);
420 if (overflow) {
421 /* XXX: could be cute and give a different
422 message for overflow == -1 */
423 PyErr_SetString(PyExc_OverflowError,
424 "Python int too large to convert to C long");
425 }
426 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000427}
428
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000429/* Get a Py_ssize_t from a long int object.
430 Returns -1 and sets an error condition if overflow occurs. */
431
432Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000433PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 register PyLongObject *v;
435 size_t x, prev;
436 Py_ssize_t i;
437 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (vv == NULL) {
440 PyErr_BadInternalCall();
441 return -1;
442 }
443 if (!PyLong_Check(vv)) {
444 PyErr_SetString(PyExc_TypeError, "an integer is required");
445 return -1;
446 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 v = (PyLongObject *)vv;
449 i = Py_SIZE(v);
450 switch (i) {
451 case -1: return -(sdigit)v->ob_digit[0];
452 case 0: return 0;
453 case 1: return v->ob_digit[0];
454 }
455 sign = 1;
456 x = 0;
457 if (i < 0) {
458 sign = -1;
459 i = -(i);
460 }
461 while (--i >= 0) {
462 prev = x;
463 x = (x << PyLong_SHIFT) | v->ob_digit[i];
464 if ((x >> PyLong_SHIFT) != prev)
465 goto overflow;
466 }
467 /* Haven't lost any bits, but casting to a signed type requires
468 * extra care (see comment above).
469 */
470 if (x <= (size_t)PY_SSIZE_T_MAX) {
471 return (Py_ssize_t)x * sign;
472 }
473 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
474 return PY_SSIZE_T_MIN;
475 }
476 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000477
Mark Dickinson22b20182010-05-10 21:27:53 +0000478 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyErr_SetString(PyExc_OverflowError,
480 "Python int too large to convert to C ssize_t");
481 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000482}
483
Guido van Rossumd8c80482002-08-13 00:24:58 +0000484/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000485 Returns -1 and sets an error condition if overflow occurs. */
486
487unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000488PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 register PyLongObject *v;
491 unsigned long x, prev;
492 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (vv == NULL) {
495 PyErr_BadInternalCall();
496 return (unsigned long)-1;
497 }
498 if (!PyLong_Check(vv)) {
499 PyErr_SetString(PyExc_TypeError, "an integer is required");
500 return (unsigned long)-1;
501 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 v = (PyLongObject *)vv;
504 i = Py_SIZE(v);
505 x = 0;
506 if (i < 0) {
507 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000508 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return (unsigned long) -1;
510 }
511 switch (i) {
512 case 0: return 0;
513 case 1: return v->ob_digit[0];
514 }
515 while (--i >= 0) {
516 prev = x;
517 x = (x << PyLong_SHIFT) | v->ob_digit[i];
518 if ((x >> PyLong_SHIFT) != prev) {
519 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000520 "python int too large to convert "
521 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return (unsigned long) -1;
523 }
524 }
525 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000526}
527
528/* Get a C unsigned long int from a long int object.
529 Returns -1 and sets an error condition if overflow occurs. */
530
531size_t
532PyLong_AsSize_t(PyObject *vv)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 register PyLongObject *v;
535 size_t x, prev;
536 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (vv == NULL) {
539 PyErr_BadInternalCall();
540 return (size_t) -1;
541 }
542 if (!PyLong_Check(vv)) {
543 PyErr_SetString(PyExc_TypeError, "an integer is required");
544 return (size_t)-1;
545 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 v = (PyLongObject *)vv;
548 i = Py_SIZE(v);
549 x = 0;
550 if (i < 0) {
551 PyErr_SetString(PyExc_OverflowError,
552 "can't convert negative value to size_t");
553 return (size_t) -1;
554 }
555 switch (i) {
556 case 0: return 0;
557 case 1: return v->ob_digit[0];
558 }
559 while (--i >= 0) {
560 prev = x;
561 x = (x << PyLong_SHIFT) | v->ob_digit[i];
562 if ((x >> PyLong_SHIFT) != prev) {
563 PyErr_SetString(PyExc_OverflowError,
564 "Python int too large to convert to C size_t");
565 return (unsigned long) -1;
566 }
567 }
568 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000569}
570
Thomas Hellera4ea6032003-04-17 18:55:45 +0000571/* Get a C unsigned long int from a long int object, ignoring the high bits.
572 Returns -1 and sets an error condition if an error occurs. */
573
Guido van Rossumddefaf32007-01-14 03:31:43 +0000574static unsigned long
575_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 register PyLongObject *v;
578 unsigned long x;
579 Py_ssize_t i;
580 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if (vv == NULL || !PyLong_Check(vv)) {
583 PyErr_BadInternalCall();
584 return (unsigned long) -1;
585 }
586 v = (PyLongObject *)vv;
587 i = Py_SIZE(v);
588 switch (i) {
589 case 0: return 0;
590 case 1: return v->ob_digit[0];
591 }
592 sign = 1;
593 x = 0;
594 if (i < 0) {
595 sign = -1;
596 i = -i;
597 }
598 while (--i >= 0) {
599 x = (x << PyLong_SHIFT) | v->ob_digit[i];
600 }
601 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000602}
603
Guido van Rossumddefaf32007-01-14 03:31:43 +0000604unsigned long
605PyLong_AsUnsignedLongMask(register PyObject *op)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyNumberMethods *nb;
608 PyLongObject *lo;
609 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (op && PyLong_Check(op))
612 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
615 nb->nb_int == NULL) {
616 PyErr_SetString(PyExc_TypeError, "an integer is required");
617 return (unsigned long)-1;
618 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 lo = (PyLongObject*) (*nb->nb_int) (op);
621 if (lo == NULL)
622 return (unsigned long)-1;
623 if (PyLong_Check(lo)) {
624 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
625 Py_DECREF(lo);
626 if (PyErr_Occurred())
627 return (unsigned long)-1;
628 return val;
629 }
630 else
631 {
632 Py_DECREF(lo);
633 PyErr_SetString(PyExc_TypeError,
634 "nb_int should return int object");
635 return (unsigned long)-1;
636 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000637}
638
Tim Peters5b8132f2003-01-31 15:52:05 +0000639int
640_PyLong_Sign(PyObject *vv)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 assert(v != NULL);
645 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000648}
649
Tim Petersbaefd9e2003-01-28 20:37:45 +0000650size_t
651_PyLong_NumBits(PyObject *vv)
652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 PyLongObject *v = (PyLongObject *)vv;
654 size_t result = 0;
655 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 assert(v != NULL);
658 assert(PyLong_Check(v));
659 ndigits = ABS(Py_SIZE(v));
660 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
661 if (ndigits > 0) {
662 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 result = (ndigits - 1) * PyLong_SHIFT;
665 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
666 goto Overflow;
667 do {
668 ++result;
669 if (result == 0)
670 goto Overflow;
671 msd >>= 1;
672 } while (msd);
673 }
674 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000675
Mark Dickinson22b20182010-05-10 21:27:53 +0000676 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
678 "to express in a platform size_t");
679 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000680}
681
Tim Peters2a9b3672001-06-11 21:23:58 +0000682PyObject *
683_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000685{
Mark Dickinson22b20182010-05-10 21:27:53 +0000686 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 int incr; /* direction to move pstartbyte */
688 const unsigned char* pendbyte; /* MSB of bytes */
689 size_t numsignificantbytes; /* number of bytes that matter */
690 Py_ssize_t ndigits; /* number of Python long digits */
691 PyLongObject* v; /* result */
692 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (n == 0)
695 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (little_endian) {
698 pstartbyte = bytes;
699 pendbyte = bytes + n - 1;
700 incr = 1;
701 }
702 else {
703 pstartbyte = bytes + n - 1;
704 pendbyte = bytes;
705 incr = -1;
706 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (is_signed)
709 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Compute numsignificantbytes. This consists of finding the most
712 significant byte. Leading 0 bytes are insignficant if the number
713 is positive, and leading 0xff bytes if negative. */
714 {
715 size_t i;
716 const unsigned char* p = pendbyte;
717 const int pincr = -incr; /* search MSB to LSB */
718 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 for (i = 0; i < n; ++i, p += pincr) {
721 if (*p != insignficant)
722 break;
723 }
724 numsignificantbytes = n - i;
725 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
726 actually has 2 significant bytes. OTOH, 0xff0001 ==
727 -0x00ffff, so we wouldn't *need* to bump it there; but we
728 do for 0xffff = -0x0001. To be safe without bothering to
729 check every case, bump it regardless. */
730 if (is_signed && numsignificantbytes < n)
731 ++numsignificantbytes;
732 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 /* How many Python long digits do we need? We have
735 8*numsignificantbytes bits, and each Python long digit has
736 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
737 /* catch overflow before it happens */
738 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
739 PyErr_SetString(PyExc_OverflowError,
740 "byte array too long to convert to int");
741 return NULL;
742 }
743 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
744 v = _PyLong_New(ndigits);
745 if (v == NULL)
746 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 /* Copy the bits over. The tricky parts are computing 2's-comp on
749 the fly for signed numbers, and dealing with the mismatch between
750 8-bit bytes and (probably) 15-bit Python digits.*/
751 {
752 size_t i;
753 twodigits carry = 1; /* for 2's-comp calculation */
754 twodigits accum = 0; /* sliding register */
755 unsigned int accumbits = 0; /* number of bits in accum */
756 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
759 twodigits thisbyte = *p;
760 /* Compute correction for 2's comp, if needed. */
761 if (is_signed) {
762 thisbyte = (0xff ^ thisbyte) + carry;
763 carry = thisbyte >> 8;
764 thisbyte &= 0xff;
765 }
766 /* Because we're going LSB to MSB, thisbyte is
767 more significant than what's already in accum,
768 so needs to be prepended to accum. */
769 accum |= (twodigits)thisbyte << accumbits;
770 accumbits += 8;
771 if (accumbits >= PyLong_SHIFT) {
772 /* There's enough to fill a Python digit. */
773 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000774 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 ++idigit;
776 accum >>= PyLong_SHIFT;
777 accumbits -= PyLong_SHIFT;
778 assert(accumbits < PyLong_SHIFT);
779 }
780 }
781 assert(accumbits < PyLong_SHIFT);
782 if (accumbits) {
783 assert(idigit < ndigits);
784 v->ob_digit[idigit] = (digit)accum;
785 ++idigit;
786 }
787 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_SIZE(v) = is_signed ? -idigit : idigit;
790 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000791}
792
793int
794_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 unsigned char* bytes, size_t n,
796 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000799 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000801 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
803 digit carry; /* for computing 2's-comp */
804 size_t j; /* # bytes filled */
805 unsigned char* p; /* pointer to next byte in bytes */
806 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (Py_SIZE(v) < 0) {
811 ndigits = -(Py_SIZE(v));
812 if (!is_signed) {
813 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000814 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return -1;
816 }
817 do_twos_comp = 1;
818 }
819 else {
820 ndigits = Py_SIZE(v);
821 do_twos_comp = 0;
822 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (little_endian) {
825 p = bytes;
826 pincr = 1;
827 }
828 else {
829 p = bytes + n - 1;
830 pincr = -1;
831 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 /* Copy over all the Python digits.
834 It's crucial that every Python digit except for the MSD contribute
835 exactly PyLong_SHIFT bits to the total, so first assert that the long is
836 normalized. */
837 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
838 j = 0;
839 accum = 0;
840 accumbits = 0;
841 carry = do_twos_comp ? 1 : 0;
842 for (i = 0; i < ndigits; ++i) {
843 digit thisdigit = v->ob_digit[i];
844 if (do_twos_comp) {
845 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
846 carry = thisdigit >> PyLong_SHIFT;
847 thisdigit &= PyLong_MASK;
848 }
849 /* Because we're going LSB to MSB, thisdigit is more
850 significant than what's already in accum, so needs to be
851 prepended to accum. */
852 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 /* The most-significant digit may be (probably is) at least
855 partly empty. */
856 if (i == ndigits - 1) {
857 /* Count # of sign bits -- they needn't be stored,
858 * although for signed conversion we need later to
859 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 while (s != 0) {
862 s >>= 1;
863 accumbits++;
864 }
865 }
866 else
867 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 /* Store as many bytes as possible. */
870 while (accumbits >= 8) {
871 if (j >= n)
872 goto Overflow;
873 ++j;
874 *p = (unsigned char)(accum & 0xff);
875 p += pincr;
876 accumbits -= 8;
877 accum >>= 8;
878 }
879 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Store the straggler (if any). */
882 assert(accumbits < 8);
883 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
884 if (accumbits > 0) {
885 if (j >= n)
886 goto Overflow;
887 ++j;
888 if (do_twos_comp) {
889 /* Fill leading bits of the byte with sign bits
890 (appropriately pretending that the long had an
891 infinite supply of sign bits). */
892 accum |= (~(twodigits)0) << accumbits;
893 }
894 *p = (unsigned char)(accum & 0xff);
895 p += pincr;
896 }
897 else if (j == n && n > 0 && is_signed) {
898 /* The main loop filled the byte array exactly, so the code
899 just above didn't get to ensure there's a sign bit, and the
900 loop below wouldn't add one either. Make sure a sign bit
901 exists. */
902 unsigned char msb = *(p - pincr);
903 int sign_bit_set = msb >= 0x80;
904 assert(accumbits == 0);
905 if (sign_bit_set == do_twos_comp)
906 return 0;
907 else
908 goto Overflow;
909 }
Tim Peters05607ad2001-06-13 21:01:27 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 /* Fill remaining bytes with copies of the sign bit. */
912 {
913 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
914 for ( ; j < n; ++j, p += pincr)
915 *p = signbyte;
916 }
Tim Peters05607ad2001-06-13 21:01:27 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000919
Mark Dickinson22b20182010-05-10 21:27:53 +0000920 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
922 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000923
Tim Peters2a9b3672001-06-11 21:23:58 +0000924}
925
Guido van Rossum78694d91998-09-18 14:14:13 +0000926/* Create a new long (or int) object from a C pointer */
927
928PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000929PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000930{
Tim Peters70128a12001-06-16 08:48:40 +0000931#ifndef HAVE_LONG_LONG
932# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
933#endif
934#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000935# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000936#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 /* special-case null pointer */
938 if (!p)
939 return PyLong_FromLong(0);
940 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000941
Guido van Rossum78694d91998-09-18 14:14:13 +0000942}
943
944/* Get a C pointer from a long object (or an int object in some cases) */
945
946void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000947PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* This function will allow int or long objects. If vv is neither,
950 then the PyLong_AsLong*() functions will raise the exception:
951 PyExc_SystemError, "bad argument to internal function"
952 */
Tim Peters70128a12001-06-16 08:48:40 +0000953#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
957 x = PyLong_AsLong(vv);
958 else
959 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000960#else
Tim Peters70128a12001-06-16 08:48:40 +0000961
962#ifndef HAVE_LONG_LONG
963# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
964#endif
965#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000966# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000967#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
971 x = PyLong_AsLongLong(vv);
972 else
973 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000974
975#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (x == -1 && PyErr_Occurred())
978 return NULL;
979 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000980}
981
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000982#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000983
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000984/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000985 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000986 */
987
Tim Peterscf37dfc2001-06-14 18:42:50 +0000988#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000989#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000990
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000991/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000992
993PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000994PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyLongObject *v;
997 unsigned PY_LONG_LONG abs_ival;
998 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
999 int ndigits = 0;
1000 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 CHECK_SMALL_INT(ival);
1003 if (ival < 0) {
1004 /* avoid signed overflow on negation; see comments
1005 in PyLong_FromLong above. */
1006 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1007 negative = 1;
1008 }
1009 else {
1010 abs_ival = (unsigned PY_LONG_LONG)ival;
1011 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* Count the number of Python digits.
1014 We used to pick 5 ("big enough for anything"), but that's a
1015 waste of time and space given that 5*15 = 75 bits are rarely
1016 needed. */
1017 t = abs_ival;
1018 while (t) {
1019 ++ndigits;
1020 t >>= PyLong_SHIFT;
1021 }
1022 v = _PyLong_New(ndigits);
1023 if (v != NULL) {
1024 digit *p = v->ob_digit;
1025 Py_SIZE(v) = negative ? -ndigits : ndigits;
1026 t = abs_ival;
1027 while (t) {
1028 *p++ = (digit)(t & PyLong_MASK);
1029 t >>= PyLong_SHIFT;
1030 }
1031 }
1032 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001033}
1034
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001035/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001036
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001038PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyLongObject *v;
1041 unsigned PY_LONG_LONG t;
1042 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (ival < PyLong_BASE)
1045 return PyLong_FromLong((long)ival);
1046 /* Count the number of Python digits. */
1047 t = (unsigned PY_LONG_LONG)ival;
1048 while (t) {
1049 ++ndigits;
1050 t >>= PyLong_SHIFT;
1051 }
1052 v = _PyLong_New(ndigits);
1053 if (v != NULL) {
1054 digit *p = v->ob_digit;
1055 Py_SIZE(v) = ndigits;
1056 while (ival) {
1057 *p++ = (digit)(ival & PyLong_MASK);
1058 ival >>= PyLong_SHIFT;
1059 }
1060 }
1061 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001062}
1063
Martin v. Löwis18e16552006-02-15 17:27:45 +00001064/* Create a new long int object from a C Py_ssize_t. */
1065
1066PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001067PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyLongObject *v;
1070 size_t abs_ival;
1071 size_t t; /* unsigned so >> doesn't propagate sign bit */
1072 int ndigits = 0;
1073 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 CHECK_SMALL_INT(ival);
1076 if (ival < 0) {
1077 /* avoid signed overflow when ival = SIZE_T_MIN */
1078 abs_ival = (size_t)(-1-ival)+1;
1079 negative = 1;
1080 }
1081 else {
1082 abs_ival = (size_t)ival;
1083 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Count the number of Python digits. */
1086 t = abs_ival;
1087 while (t) {
1088 ++ndigits;
1089 t >>= PyLong_SHIFT;
1090 }
1091 v = _PyLong_New(ndigits);
1092 if (v != NULL) {
1093 digit *p = v->ob_digit;
1094 Py_SIZE(v) = negative ? -ndigits : ndigits;
1095 t = abs_ival;
1096 while (t) {
1097 *p++ = (digit)(t & PyLong_MASK);
1098 t >>= PyLong_SHIFT;
1099 }
1100 }
1101 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102}
1103
1104/* Create a new long int object from a C size_t. */
1105
1106PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001107PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyLongObject *v;
1110 size_t t;
1111 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (ival < PyLong_BASE)
1114 return PyLong_FromLong((long)ival);
1115 /* Count the number of Python digits. */
1116 t = ival;
1117 while (t) {
1118 ++ndigits;
1119 t >>= PyLong_SHIFT;
1120 }
1121 v = _PyLong_New(ndigits);
1122 if (v != NULL) {
1123 digit *p = v->ob_digit;
1124 Py_SIZE(v) = ndigits;
1125 while (ival) {
1126 *p++ = (digit)(ival & PyLong_MASK);
1127 ival >>= PyLong_SHIFT;
1128 }
1129 }
1130 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131}
1132
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001133/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001134 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001135
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001136PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001137PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyLongObject *v;
1140 PY_LONG_LONG bytes;
1141 int one = 1;
1142 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (vv == NULL) {
1145 PyErr_BadInternalCall();
1146 return -1;
1147 }
1148 if (!PyLong_Check(vv)) {
1149 PyNumberMethods *nb;
1150 PyObject *io;
1151 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1152 nb->nb_int == NULL) {
1153 PyErr_SetString(PyExc_TypeError, "an integer is required");
1154 return -1;
1155 }
1156 io = (*nb->nb_int) (vv);
1157 if (io == NULL)
1158 return -1;
1159 if (PyLong_Check(io)) {
1160 bytes = PyLong_AsLongLong(io);
1161 Py_DECREF(io);
1162 return bytes;
1163 }
1164 Py_DECREF(io);
1165 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1166 return -1;
1167 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 v = (PyLongObject*)vv;
1170 switch(Py_SIZE(v)) {
1171 case -1: return -(sdigit)v->ob_digit[0];
1172 case 0: return 0;
1173 case 1: return v->ob_digit[0];
1174 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001175 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1176 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1179 if (res < 0)
1180 return (PY_LONG_LONG)-1;
1181 else
1182 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183}
1184
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001185/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001186 Return -1 and set an error if overflow occurs. */
1187
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001188unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001189PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 PyLongObject *v;
1192 unsigned PY_LONG_LONG bytes;
1193 int one = 1;
1194 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (vv == NULL || !PyLong_Check(vv)) {
1197 PyErr_BadInternalCall();
1198 return (unsigned PY_LONG_LONG)-1;
1199 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 v = (PyLongObject*)vv;
1202 switch(Py_SIZE(v)) {
1203 case 0: return 0;
1204 case 1: return v->ob_digit[0];
1205 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001206
Mark Dickinson22b20182010-05-10 21:27:53 +00001207 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1208 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1211 if (res < 0)
1212 return (unsigned PY_LONG_LONG)res;
1213 else
1214 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215}
Tim Petersd1a7da62001-06-13 00:35:57 +00001216
Thomas Hellera4ea6032003-04-17 18:55:45 +00001217/* Get a C unsigned long int from a long int object, ignoring the high bits.
1218 Returns -1 and sets an error condition if an error occurs. */
1219
Guido van Rossumddefaf32007-01-14 03:31:43 +00001220static unsigned PY_LONG_LONG
1221_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 register PyLongObject *v;
1224 unsigned PY_LONG_LONG x;
1225 Py_ssize_t i;
1226 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (vv == NULL || !PyLong_Check(vv)) {
1229 PyErr_BadInternalCall();
1230 return (unsigned long) -1;
1231 }
1232 v = (PyLongObject *)vv;
1233 switch(Py_SIZE(v)) {
1234 case 0: return 0;
1235 case 1: return v->ob_digit[0];
1236 }
1237 i = Py_SIZE(v);
1238 sign = 1;
1239 x = 0;
1240 if (i < 0) {
1241 sign = -1;
1242 i = -i;
1243 }
1244 while (--i >= 0) {
1245 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1246 }
1247 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001248}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001249
1250unsigned PY_LONG_LONG
1251PyLong_AsUnsignedLongLongMask(register PyObject *op)
1252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyNumberMethods *nb;
1254 PyLongObject *lo;
1255 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (op && PyLong_Check(op))
1258 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1261 nb->nb_int == NULL) {
1262 PyErr_SetString(PyExc_TypeError, "an integer is required");
1263 return (unsigned PY_LONG_LONG)-1;
1264 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 lo = (PyLongObject*) (*nb->nb_int) (op);
1267 if (lo == NULL)
1268 return (unsigned PY_LONG_LONG)-1;
1269 if (PyLong_Check(lo)) {
1270 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1271 Py_DECREF(lo);
1272 if (PyErr_Occurred())
1273 return (unsigned PY_LONG_LONG)-1;
1274 return val;
1275 }
1276 else
1277 {
1278 Py_DECREF(lo);
1279 PyErr_SetString(PyExc_TypeError,
1280 "nb_int should return int object");
1281 return (unsigned PY_LONG_LONG)-1;
1282 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001283}
Tim Petersd1a7da62001-06-13 00:35:57 +00001284#undef IS_LITTLE_ENDIAN
1285
Mark Dickinson93f562c2010-01-30 10:30:15 +00001286/* Get a C long long int from a Python long or Python int object.
1287 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1288 on the sign of the result. Otherwise *overflow is 0.
1289
1290 For other errors (e.g., type error), returns -1 and sets an error
1291 condition.
1292*/
1293
1294PY_LONG_LONG
1295PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* This version by Tim Peters */
1298 register PyLongObject *v;
1299 unsigned PY_LONG_LONG x, prev;
1300 PY_LONG_LONG res;
1301 Py_ssize_t i;
1302 int sign;
1303 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 *overflow = 0;
1306 if (vv == NULL) {
1307 PyErr_BadInternalCall();
1308 return -1;
1309 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (!PyLong_Check(vv)) {
1312 PyNumberMethods *nb;
1313 nb = vv->ob_type->tp_as_number;
1314 if (nb == NULL || nb->nb_int == NULL) {
1315 PyErr_SetString(PyExc_TypeError,
1316 "an integer is required");
1317 return -1;
1318 }
1319 vv = (*nb->nb_int) (vv);
1320 if (vv == NULL)
1321 return -1;
1322 do_decref = 1;
1323 if (!PyLong_Check(vv)) {
1324 Py_DECREF(vv);
1325 PyErr_SetString(PyExc_TypeError,
1326 "nb_int should return int object");
1327 return -1;
1328 }
1329 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 res = -1;
1332 v = (PyLongObject *)vv;
1333 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 switch (i) {
1336 case -1:
1337 res = -(sdigit)v->ob_digit[0];
1338 break;
1339 case 0:
1340 res = 0;
1341 break;
1342 case 1:
1343 res = v->ob_digit[0];
1344 break;
1345 default:
1346 sign = 1;
1347 x = 0;
1348 if (i < 0) {
1349 sign = -1;
1350 i = -(i);
1351 }
1352 while (--i >= 0) {
1353 prev = x;
1354 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1355 if ((x >> PyLong_SHIFT) != prev) {
1356 *overflow = sign;
1357 goto exit;
1358 }
1359 }
1360 /* Haven't lost any bits, but casting to long requires extra
1361 * care (see comment above).
1362 */
1363 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1364 res = (PY_LONG_LONG)x * sign;
1365 }
1366 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1367 res = PY_LLONG_MIN;
1368 }
1369 else {
1370 *overflow = sign;
1371 /* res is already set to -1 */
1372 }
1373 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001374 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 if (do_decref) {
1376 Py_DECREF(vv);
1377 }
1378 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001379}
1380
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001381#endif /* HAVE_LONG_LONG */
1382
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001383#define CHECK_BINOP(v,w) \
1384 do { \
1385 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1386 Py_INCREF(Py_NotImplemented); \
1387 return Py_NotImplemented; \
1388 } \
1389 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001390
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001391/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1392 2**k if d is nonzero, else 0. */
1393
1394static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1396 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001397};
1398
1399static int
1400bits_in_digit(digit d)
1401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 int d_bits = 0;
1403 while (d >= 32) {
1404 d_bits += 6;
1405 d >>= 6;
1406 }
1407 d_bits += (int)BitLengthTable[d];
1408 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001409}
1410
Tim Peters877a2122002-08-12 05:09:36 +00001411/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1412 * is modified in place, by adding y to it. Carries are propagated as far as
1413 * x[m-1], and the remaining carry (0 or 1) is returned.
1414 */
1415static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001416v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 Py_ssize_t i;
1419 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 assert(m >= n);
1422 for (i = 0; i < n; ++i) {
1423 carry += x[i] + y[i];
1424 x[i] = carry & PyLong_MASK;
1425 carry >>= PyLong_SHIFT;
1426 assert((carry & 1) == carry);
1427 }
1428 for (; carry && i < m; ++i) {
1429 carry += x[i];
1430 x[i] = carry & PyLong_MASK;
1431 carry >>= PyLong_SHIFT;
1432 assert((carry & 1) == carry);
1433 }
1434 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001435}
1436
1437/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1438 * is modified in place, by subtracting y from it. Borrows are propagated as
1439 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1440 */
1441static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001442v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 Py_ssize_t i;
1445 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 assert(m >= n);
1448 for (i = 0; i < n; ++i) {
1449 borrow = x[i] - y[i] - borrow;
1450 x[i] = borrow & PyLong_MASK;
1451 borrow >>= PyLong_SHIFT;
1452 borrow &= 1; /* keep only 1 sign bit */
1453 }
1454 for (; borrow && i < m; ++i) {
1455 borrow = x[i] - borrow;
1456 x[i] = borrow & PyLong_MASK;
1457 borrow >>= PyLong_SHIFT;
1458 borrow &= 1;
1459 }
1460 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001461}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001462
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001463/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1464 * result in z[0:m], and return the d bits shifted out of the top.
1465 */
1466static digit
1467v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 Py_ssize_t i;
1470 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 assert(0 <= d && d < PyLong_SHIFT);
1473 for (i=0; i < m; i++) {
1474 twodigits acc = (twodigits)a[i] << d | carry;
1475 z[i] = (digit)acc & PyLong_MASK;
1476 carry = (digit)(acc >> PyLong_SHIFT);
1477 }
1478 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001479}
1480
1481/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1482 * result in z[0:m], and return the d bits shifted out of the bottom.
1483 */
1484static digit
1485v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 Py_ssize_t i;
1488 digit carry = 0;
1489 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 assert(0 <= d && d < PyLong_SHIFT);
1492 for (i=m; i-- > 0;) {
1493 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1494 carry = (digit)acc & mask;
1495 z[i] = (digit)(acc >> d);
1496 }
1497 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001498}
1499
Tim Peters212e6142001-07-14 12:23:19 +00001500/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1501 in pout, and returning the remainder. pin and pout point at the LSD.
1502 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001503 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001504 immutable. */
1505
1506static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001507inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 assert(n > 0 && n <= PyLong_MASK);
1512 pin += size;
1513 pout += size;
1514 while (--size >= 0) {
1515 digit hi;
1516 rem = (rem << PyLong_SHIFT) | *--pin;
1517 *--pout = hi = (digit)(rem / n);
1518 rem -= (twodigits)hi * n;
1519 }
1520 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001521}
1522
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001523/* Divide a long integer by a digit, returning both the quotient
1524 (as function result) and the remainder (through *prem).
1525 The sign of a is ignored; n should not be zero. */
1526
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001527static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001528divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 const Py_ssize_t size = ABS(Py_SIZE(a));
1531 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 assert(n > 0 && n <= PyLong_MASK);
1534 z = _PyLong_New(size);
1535 if (z == NULL)
1536 return NULL;
1537 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1538 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001539}
1540
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001541/* Convert a long integer to a base 10 string. Returns a new non-shared
1542 string. (Return value is non-shared so that callers can modify the
1543 returned value if necessary.) */
1544
1545static PyObject *
1546long_to_decimal_string(PyObject *aa)
1547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 PyLongObject *scratch, *a;
1549 PyObject *str;
1550 Py_ssize_t size, strlen, size_a, i, j;
1551 digit *pout, *pin, rem, tenpow;
1552 Py_UNICODE *p;
1553 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 a = (PyLongObject *)aa;
1556 if (a == NULL || !PyLong_Check(a)) {
1557 PyErr_BadInternalCall();
1558 return NULL;
1559 }
1560 size_a = ABS(Py_SIZE(a));
1561 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 /* quick and dirty upper bound for the number of digits
1564 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 But log2(a) < size_a * PyLong_SHIFT, and
1569 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1570 > 3 * _PyLong_DECIMAL_SHIFT
1571 */
1572 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1573 PyErr_SetString(PyExc_OverflowError,
1574 "long is too large to format");
1575 return NULL;
1576 }
1577 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1578 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1579 scratch = _PyLong_New(size);
1580 if (scratch == NULL)
1581 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* convert array of base _PyLong_BASE digits in pin to an array of
1584 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1585 Volume 2 (3rd edn), section 4.4, Method 1b). */
1586 pin = a->ob_digit;
1587 pout = scratch->ob_digit;
1588 size = 0;
1589 for (i = size_a; --i >= 0; ) {
1590 digit hi = pin[i];
1591 for (j = 0; j < size; j++) {
1592 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1593 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1594 pout[j] = (digit)(z - (twodigits)hi *
1595 _PyLong_DECIMAL_BASE);
1596 }
1597 while (hi) {
1598 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1599 hi /= _PyLong_DECIMAL_BASE;
1600 }
1601 /* check for keyboard interrupt */
1602 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001603 Py_DECREF(scratch);
1604 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001605 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 }
1607 /* pout should have at least one digit, so that the case when a = 0
1608 works correctly */
1609 if (size == 0)
1610 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 /* calculate exact length of output string, and allocate */
1613 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1614 tenpow = 10;
1615 rem = pout[size-1];
1616 while (rem >= tenpow) {
1617 tenpow *= 10;
1618 strlen++;
1619 }
1620 str = PyUnicode_FromUnicode(NULL, strlen);
1621 if (str == NULL) {
1622 Py_DECREF(scratch);
1623 return NULL;
1624 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* fill the string right-to-left */
1627 p = PyUnicode_AS_UNICODE(str) + strlen;
1628 *p = '\0';
1629 /* pout[0] through pout[size-2] contribute exactly
1630 _PyLong_DECIMAL_SHIFT digits each */
1631 for (i=0; i < size - 1; i++) {
1632 rem = pout[i];
1633 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1634 *--p = '0' + rem % 10;
1635 rem /= 10;
1636 }
1637 }
1638 /* pout[size-1]: always produce at least one decimal digit */
1639 rem = pout[i];
1640 do {
1641 *--p = '0' + rem % 10;
1642 rem /= 10;
1643 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 /* and sign */
1646 if (negative)
1647 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 /* check we've counted correctly */
1650 assert(p == PyUnicode_AS_UNICODE(str));
1651 Py_DECREF(scratch);
1652 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001653}
1654
Mark Dickinsoncd068122009-09-18 14:53:08 +00001655/* Convert a long int object to a string, using a given conversion base,
1656 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001657 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001658
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001659PyObject *
1660_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 register PyLongObject *a = (PyLongObject *)aa;
1663 PyObject *str;
1664 Py_ssize_t i, sz;
1665 Py_ssize_t size_a;
1666 Py_UNICODE *p, sign = '\0';
1667 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 assert(base == 2 || base == 8 || base == 10 || base == 16);
1670 if (base == 10)
1671 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 if (a == NULL || !PyLong_Check(a)) {
1674 PyErr_BadInternalCall();
1675 return NULL;
1676 }
1677 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 /* Compute a rough upper bound for the length of the string */
1680 switch (base) {
1681 case 16:
1682 bits = 4;
1683 break;
1684 case 8:
1685 bits = 3;
1686 break;
1687 case 2:
1688 bits = 1;
1689 break;
1690 default:
1691 assert(0); /* shouldn't ever get here */
1692 bits = 0; /* to silence gcc warning */
1693 }
1694 /* compute length of output string: allow 2 characters for prefix and
1695 1 for possible '-' sign. */
1696 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1697 PyErr_SetString(PyExc_OverflowError,
1698 "int is too large to format");
1699 return NULL;
1700 }
1701 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1702 is safe from overflow */
1703 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1704 assert(sz >= 0);
1705 str = PyUnicode_FromUnicode(NULL, sz);
1706 if (str == NULL)
1707 return NULL;
1708 p = PyUnicode_AS_UNICODE(str) + sz;
1709 *p = '\0';
1710 if (Py_SIZE(a) < 0)
1711 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 if (Py_SIZE(a) == 0) {
1714 *--p = '0';
1715 }
1716 else {
1717 /* JRH: special case for power-of-2 bases */
1718 twodigits accum = 0;
1719 int accumbits = 0; /* # of bits in accum */
1720 for (i = 0; i < size_a; ++i) {
1721 accum |= (twodigits)a->ob_digit[i] << accumbits;
1722 accumbits += PyLong_SHIFT;
1723 assert(accumbits >= bits);
1724 do {
1725 Py_UNICODE cdigit;
1726 cdigit = (Py_UNICODE)(accum & (base - 1));
1727 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1728 assert(p > PyUnicode_AS_UNICODE(str));
1729 *--p = cdigit;
1730 accumbits -= bits;
1731 accum >>= bits;
1732 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1733 }
1734 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (base == 16)
1737 *--p = 'x';
1738 else if (base == 8)
1739 *--p = 'o';
1740 else /* (base == 2) */
1741 *--p = 'b';
1742 *--p = '0';
1743 if (sign)
1744 *--p = sign;
1745 if (p != PyUnicode_AS_UNICODE(str)) {
1746 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1747 assert(p > q);
1748 do {
1749 } while ((*q++ = *p++) != '\0');
1750 q--;
1751 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1752 PyUnicode_AS_UNICODE(str)))) {
1753 Py_DECREF(str);
1754 return NULL;
1755 }
1756 }
1757 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001758}
1759
Thomas Wouters477c8d52006-05-27 19:21:47 +00001760/* Table of digit values for 8-bit string -> integer conversion.
1761 * '0' maps to 0, ..., '9' maps to 9.
1762 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1763 * All other indices map to 37.
1764 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001765 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001766 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001767unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1769 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1770 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1771 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1772 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1773 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1774 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1775 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
1781 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1782 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1783 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784};
1785
1786/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001787 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1788 * non-digit (which may be *str!). A normalized long is returned.
1789 * The point to this routine is that it takes time linear in the number of
1790 * string characters.
1791 */
1792static PyLongObject *
1793long_from_binary_base(char **str, int base)
1794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 char *p = *str;
1796 char *start = p;
1797 int bits_per_char;
1798 Py_ssize_t n;
1799 PyLongObject *z;
1800 twodigits accum;
1801 int bits_in_accum;
1802 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1805 n = base;
1806 for (bits_per_char = -1; n; ++bits_per_char)
1807 n >>= 1;
1808 /* n <- total # of bits needed, while setting p to end-of-string */
1809 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1810 ++p;
1811 *str = p;
1812 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1813 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1814 if (n / bits_per_char < p - start) {
1815 PyErr_SetString(PyExc_ValueError,
1816 "int string too large to convert");
1817 return NULL;
1818 }
1819 n = n / PyLong_SHIFT;
1820 z = _PyLong_New(n);
1821 if (z == NULL)
1822 return NULL;
1823 /* Read string from right, and fill in long from left; i.e.,
1824 * from least to most significant in both.
1825 */
1826 accum = 0;
1827 bits_in_accum = 0;
1828 pdigit = z->ob_digit;
1829 while (--p >= start) {
1830 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1831 assert(k >= 0 && k < base);
1832 accum |= (twodigits)k << bits_in_accum;
1833 bits_in_accum += bits_per_char;
1834 if (bits_in_accum >= PyLong_SHIFT) {
1835 *pdigit++ = (digit)(accum & PyLong_MASK);
1836 assert(pdigit - z->ob_digit <= n);
1837 accum >>= PyLong_SHIFT;
1838 bits_in_accum -= PyLong_SHIFT;
1839 assert(bits_in_accum < PyLong_SHIFT);
1840 }
1841 }
1842 if (bits_in_accum) {
1843 assert(bits_in_accum <= PyLong_SHIFT);
1844 *pdigit++ = (digit)accum;
1845 assert(pdigit - z->ob_digit <= n);
1846 }
1847 while (pdigit - z->ob_digit < n)
1848 *pdigit++ = 0;
1849 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001850}
1851
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001852PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001853PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 int sign = 1, error_if_nonzero = 0;
1856 char *start, *orig_str = str;
1857 PyLongObject *z = NULL;
1858 PyObject *strobj;
1859 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if ((base != 0 && base < 2) || base > 36) {
1862 PyErr_SetString(PyExc_ValueError,
1863 "int() arg 2 must be >= 2 and <= 36");
1864 return NULL;
1865 }
1866 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1867 str++;
1868 if (*str == '+')
1869 ++str;
1870 else if (*str == '-') {
1871 ++str;
1872 sign = -1;
1873 }
1874 if (base == 0) {
1875 if (str[0] != '0')
1876 base = 10;
1877 else if (str[1] == 'x' || str[1] == 'X')
1878 base = 16;
1879 else if (str[1] == 'o' || str[1] == 'O')
1880 base = 8;
1881 else if (str[1] == 'b' || str[1] == 'B')
1882 base = 2;
1883 else {
1884 /* "old" (C-style) octal literal, now invalid.
1885 it might still be zero though */
1886 error_if_nonzero = 1;
1887 base = 10;
1888 }
1889 }
1890 if (str[0] == '0' &&
1891 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1892 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1893 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1894 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 start = str;
1897 if ((base & (base - 1)) == 0)
1898 z = long_from_binary_base(&str, base);
1899 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001900/***
1901Binary bases can be converted in time linear in the number of digits, because
1902Python's representation base is binary. Other bases (including decimal!) use
1903the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001904
Thomas Wouters477c8d52006-05-27 19:21:47 +00001905First some math: the largest integer that can be expressed in N base-B digits
1906is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1907case number of Python digits needed to hold it is the smallest integer n s.t.
1908
1909 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1910 BASE**n >= B**N [taking logs to base BASE]
1911 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1912
1913The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1914this quickly. A Python long with that much space is reserved near the start,
1915and the result is computed into it.
1916
1917The input string is actually treated as being in base base**i (i.e., i digits
1918are processed at a time), where two more static arrays hold:
1919
1920 convwidth_base[base] = the largest integer i such that base**i <= BASE
1921 convmultmax_base[base] = base ** convwidth_base[base]
1922
1923The first of these is the largest i such that i consecutive input digits
1924must fit in a single Python digit. The second is effectively the input
1925base we're really using.
1926
1927Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1928convmultmax_base[base], the result is "simply"
1929
1930 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1931
1932where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001933
1934Error analysis: as above, the number of Python digits `n` needed is worst-
1935case
1936
1937 n >= N * log(B)/log(BASE)
1938
1939where `N` is the number of input digits in base `B`. This is computed via
1940
1941 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1942
1943below. Two numeric concerns are how much space this can waste, and whether
1944the computed result can be too small. To be concrete, assume BASE = 2**15,
1945which is the default (and it's unlikely anyone changes that).
1946
1947Waste isn't a problem: provided the first input digit isn't 0, the difference
1948between the worst-case input with N digits and the smallest input with N
1949digits is about a factor of B, but B is small compared to BASE so at most
1950one allocated Python digit can remain unused on that count. If
1951N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1952and adding 1 returns a result 1 larger than necessary. However, that can't
1953happen: whenever B is a power of 2, long_from_binary_base() is called
1954instead, and it's impossible for B**i to be an integer power of 2**15 when
1955B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1956an exact integer when B is not a power of 2, since B**i has a prime factor
1957other than 2 in that case, but (2**15)**j's only prime factor is 2).
1958
1959The computed result can be too small if the true value of N*log(B)/log(BASE)
1960is a little bit larger than an exact integer, but due to roundoff errors (in
1961computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1962yields a numeric result a little less than that integer. Unfortunately, "how
1963close can a transcendental function get to an integer over some range?"
1964questions are generally theoretically intractable. Computer analysis via
1965continued fractions is practical: expand log(B)/log(BASE) via continued
1966fractions, giving a sequence i/j of "the best" rational approximations. Then
1967j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1968we can get very close to being in trouble, but very rarely. For example,
196976573 is a denominator in one of the continued-fraction approximations to
1970log(10)/log(2**15), and indeed:
1971
1972 >>> log(10)/log(2**15)*76573
1973 16958.000000654003
1974
1975is very close to an integer. If we were working with IEEE single-precision,
1976rounding errors could kill us. Finding worst cases in IEEE double-precision
1977requires better-than-double-precision log() functions, and Tim didn't bother.
1978Instead the code checks to see whether the allocated space is enough as each
1979new Python digit is added, and copies the whole thing to a larger long if not.
1980This should happen extremely rarely, and in fact I don't have a test case
1981that triggers it(!). Instead the code was tested by artificially allocating
1982just 1 digit at the start, so that the copying code was exercised for every
1983digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001984***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 register twodigits c; /* current input character */
1986 Py_ssize_t size_z;
1987 int i;
1988 int convwidth;
1989 twodigits convmultmax, convmult;
1990 digit *pz, *pzstop;
1991 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 static double log_base_BASE[37] = {0.0e0,};
1994 static int convwidth_base[37] = {0,};
1995 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (log_base_BASE[base] == 0.0) {
1998 twodigits convmax = base;
1999 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000
Mark Dickinson22b20182010-05-10 21:27:53 +00002001 log_base_BASE[base] = (log((double)base) /
2002 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 for (;;) {
2004 twodigits next = convmax * base;
2005 if (next > PyLong_BASE)
2006 break;
2007 convmax = next;
2008 ++i;
2009 }
2010 convmultmax_base[base] = convmax;
2011 assert(i > 0);
2012 convwidth_base[base] = i;
2013 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Find length of the string of numeric characters. */
2016 scan = str;
2017 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2018 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Create a long object that can contain the largest possible
2021 * integer with this base and length. Note that there's no
2022 * need to initialize z->ob_digit -- no slot is read up before
2023 * being stored into.
2024 */
2025 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2026 /* Uncomment next line to test exceedingly rare copy code */
2027 /* size_z = 1; */
2028 assert(size_z > 0);
2029 z = _PyLong_New(size_z);
2030 if (z == NULL)
2031 return NULL;
2032 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 /* `convwidth` consecutive input digits are treated as a single
2035 * digit in base `convmultmax`.
2036 */
2037 convwidth = convwidth_base[base];
2038 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* Work ;-) */
2041 while (str < scan) {
2042 /* grab up to convwidth digits from the input string */
2043 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2044 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2045 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002046 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 assert(c < PyLong_BASE);
2048 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 convmult = convmultmax;
2051 /* Calculate the shift only if we couldn't get
2052 * convwidth digits.
2053 */
2054 if (i != convwidth) {
2055 convmult = base;
2056 for ( ; i > 1; --i)
2057 convmult *= base;
2058 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* Multiply z by convmult, and add c. */
2061 pz = z->ob_digit;
2062 pzstop = pz + Py_SIZE(z);
2063 for (; pz < pzstop; ++pz) {
2064 c += (twodigits)*pz * convmult;
2065 *pz = (digit)(c & PyLong_MASK);
2066 c >>= PyLong_SHIFT;
2067 }
2068 /* carry off the current end? */
2069 if (c) {
2070 assert(c < PyLong_BASE);
2071 if (Py_SIZE(z) < size_z) {
2072 *pz = (digit)c;
2073 ++Py_SIZE(z);
2074 }
2075 else {
2076 PyLongObject *tmp;
2077 /* Extremely rare. Get more space. */
2078 assert(Py_SIZE(z) == size_z);
2079 tmp = _PyLong_New(size_z + 1);
2080 if (tmp == NULL) {
2081 Py_DECREF(z);
2082 return NULL;
2083 }
2084 memcpy(tmp->ob_digit,
2085 z->ob_digit,
2086 sizeof(digit) * size_z);
2087 Py_DECREF(z);
2088 z = tmp;
2089 z->ob_digit[size_z] = (digit)c;
2090 ++size_z;
2091 }
2092 }
2093 }
2094 }
2095 if (z == NULL)
2096 return NULL;
2097 if (error_if_nonzero) {
2098 /* reset the base to 0, else the exception message
2099 doesn't make too much sense */
2100 base = 0;
2101 if (Py_SIZE(z) != 0)
2102 goto onError;
2103 /* there might still be other problems, therefore base
2104 remains zero here for the same reason */
2105 }
2106 if (str == start)
2107 goto onError;
2108 if (sign < 0)
2109 Py_SIZE(z) = -(Py_SIZE(z));
2110 while (*str && isspace(Py_CHARMASK(*str)))
2111 str++;
2112 if (*str != '\0')
2113 goto onError;
2114 if (pend)
2115 *pend = str;
2116 long_normalize(z);
2117 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002118
Mark Dickinson22b20182010-05-10 21:27:53 +00002119 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 Py_XDECREF(z);
2121 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2122 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2123 if (strobj == NULL)
2124 return NULL;
2125 PyErr_Format(PyExc_ValueError,
2126 "invalid literal for int() with base %d: %R",
2127 base, strobj);
2128 Py_DECREF(strobj);
2129 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002130}
2131
2132PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002133PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 PyObject *result;
2136 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (buffer == NULL)
2139 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2142 PyMem_FREE(buffer);
2143 return NULL;
2144 }
2145 result = PyLong_FromString(buffer, NULL, base);
2146 PyMem_FREE(buffer);
2147 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002148}
2149
Tim Peters9f688bf2000-07-07 15:53:28 +00002150/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002153static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002154
2155/* Long division with remainder, top-level routine */
2156
Guido van Rossume32e0141992-01-19 16:31:05 +00002157static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002158long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2162 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (size_b == 0) {
2165 PyErr_SetString(PyExc_ZeroDivisionError,
2166 "integer division or modulo by zero");
2167 return -1;
2168 }
2169 if (size_a < size_b ||
2170 (size_a == size_b &&
2171 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2172 /* |a| < |b|. */
2173 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2174 if (*pdiv == NULL)
2175 return -1;
2176 Py_INCREF(a);
2177 *prem = (PyLongObject *) a;
2178 return 0;
2179 }
2180 if (size_b == 1) {
2181 digit rem = 0;
2182 z = divrem1(a, b->ob_digit[0], &rem);
2183 if (z == NULL)
2184 return -1;
2185 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2186 if (*prem == NULL) {
2187 Py_DECREF(z);
2188 return -1;
2189 }
2190 }
2191 else {
2192 z = x_divrem(a, b, prem);
2193 if (z == NULL)
2194 return -1;
2195 }
2196 /* Set the signs.
2197 The quotient z has the sign of a*b;
2198 the remainder r has the sign of a,
2199 so a = b*z + r. */
2200 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2201 NEGATE(z);
2202 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2203 NEGATE(*prem);
2204 *pdiv = maybe_small_long(z);
2205 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002206}
2207
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002208/* Unsigned long division with remainder -- the algorithm. The arguments v1
2209 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002211static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002212x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyLongObject *v, *w, *a;
2215 Py_ssize_t i, k, size_v, size_w;
2216 int d;
2217 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2218 twodigits vv;
2219 sdigit zhi;
2220 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2223 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2224 handle the special case when the initial estimate q for a quotient
2225 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2226 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* allocate space; w will also be used to hold the final remainder */
2229 size_v = ABS(Py_SIZE(v1));
2230 size_w = ABS(Py_SIZE(w1));
2231 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2232 v = _PyLong_New(size_v+1);
2233 if (v == NULL) {
2234 *prem = NULL;
2235 return NULL;
2236 }
2237 w = _PyLong_New(size_w);
2238 if (w == NULL) {
2239 Py_DECREF(v);
2240 *prem = NULL;
2241 return NULL;
2242 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2245 shift v1 left by the same amount. Results go into w and v. */
2246 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2247 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2248 assert(carry == 0);
2249 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2250 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2251 v->ob_digit[size_v] = carry;
2252 size_v++;
2253 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2256 at most (and usually exactly) k = size_v - size_w digits. */
2257 k = size_v - size_w;
2258 assert(k >= 0);
2259 a = _PyLong_New(k);
2260 if (a == NULL) {
2261 Py_DECREF(w);
2262 Py_DECREF(v);
2263 *prem = NULL;
2264 return NULL;
2265 }
2266 v0 = v->ob_digit;
2267 w0 = w->ob_digit;
2268 wm1 = w0[size_w-1];
2269 wm2 = w0[size_w-2];
2270 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2271 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2272 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002275 Py_DECREF(a);
2276 Py_DECREF(w);
2277 Py_DECREF(v);
2278 *prem = NULL;
2279 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002280 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* estimate quotient digit q; may overestimate by 1 (rare) */
2283 vtop = vk[size_w];
2284 assert(vtop <= wm1);
2285 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2286 q = (digit)(vv / wm1);
2287 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2288 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2289 | vk[size_w-2])) {
2290 --q;
2291 r += wm1;
2292 if (r >= PyLong_BASE)
2293 break;
2294 }
2295 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2298 zhi = 0;
2299 for (i = 0; i < size_w; ++i) {
2300 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2301 -PyLong_BASE * q <= z < PyLong_BASE */
2302 z = (sdigit)vk[i] + zhi -
2303 (stwodigits)q * (stwodigits)w0[i];
2304 vk[i] = (digit)z & PyLong_MASK;
2305 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002306 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* add w back if q was too large (this branch taken rarely) */
2310 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2311 if ((sdigit)vtop + zhi < 0) {
2312 carry = 0;
2313 for (i = 0; i < size_w; ++i) {
2314 carry += vk[i] + w0[i];
2315 vk[i] = carry & PyLong_MASK;
2316 carry >>= PyLong_SHIFT;
2317 }
2318 --q;
2319 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* store quotient digit */
2322 assert(q < PyLong_BASE);
2323 *--ak = q;
2324 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* unshift remainder; we reuse w to store the result */
2327 carry = v_rshift(w0, v0, size_w, d);
2328 assert(carry==0);
2329 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 *prem = long_normalize(w);
2332 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002333}
2334
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002335/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2336 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2337 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2338 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2339 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2340 -1.0. */
2341
2342/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2343#if DBL_MANT_DIG == 53
2344#define EXP2_DBL_MANT_DIG 9007199254740992.0
2345#else
2346#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2347#endif
2348
2349double
2350_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2353 /* See below for why x_digits is always large enough. */
2354 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2355 double dx;
2356 /* Correction term for round-half-to-even rounding. For a digit x,
2357 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2358 multiple of 4, rounding ties to a multiple of 8. */
2359 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 a_size = ABS(Py_SIZE(a));
2362 if (a_size == 0) {
2363 /* Special case for 0: significand 0.0, exponent 0. */
2364 *e = 0;
2365 return 0.0;
2366 }
2367 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2368 /* The following is an overflow-free version of the check
2369 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2370 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2371 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2372 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002373 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2377 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 Number of digits needed for result: write // for floor division.
2380 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2389 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2392 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2393 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 in both cases.
2400 */
2401 if (a_bits <= DBL_MANT_DIG + 2) {
2402 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2403 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2404 x_size = 0;
2405 while (x_size < shift_digits)
2406 x_digits[x_size++] = 0;
2407 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2408 (int)shift_bits);
2409 x_size += a_size;
2410 x_digits[x_size++] = rem;
2411 }
2412 else {
2413 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2414 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2415 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2416 a_size - shift_digits, (int)shift_bits);
2417 x_size = a_size - shift_digits;
2418 /* For correct rounding below, we need the least significant
2419 bit of x to be 'sticky' for this shift: if any of the bits
2420 shifted out was nonzero, we set the least significant bit
2421 of x. */
2422 if (rem)
2423 x_digits[0] |= 1;
2424 else
2425 while (shift_digits > 0)
2426 if (a->ob_digit[--shift_digits]) {
2427 x_digits[0] |= 1;
2428 break;
2429 }
2430 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002431 assert(1 <= x_size &&
2432 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 /* Round, and convert to double. */
2435 x_digits[0] += half_even_correction[x_digits[0] & 7];
2436 dx = x_digits[--x_size];
2437 while (x_size > 0)
2438 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 /* Rescale; make correction if result is 1.0. */
2441 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2442 if (dx == 1.0) {
2443 if (a_bits == PY_SSIZE_T_MAX)
2444 goto overflow;
2445 dx = 0.5;
2446 a_bits += 1;
2447 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 *e = a_bits;
2450 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002451
2452 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* exponent > PY_SSIZE_T_MAX */
2454 PyErr_SetString(PyExc_OverflowError,
2455 "huge integer: number of bits overflows a Py_ssize_t");
2456 *e = 0;
2457 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002458}
2459
2460/* Get a C double from a long int object. Rounds to the nearest double,
2461 using the round-half-to-even rule in the case of a tie. */
2462
2463double
2464PyLong_AsDouble(PyObject *v)
2465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 Py_ssize_t exponent;
2467 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 if (v == NULL || !PyLong_Check(v)) {
2470 PyErr_BadInternalCall();
2471 return -1.0;
2472 }
2473 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2474 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2475 PyErr_SetString(PyExc_OverflowError,
2476 "long int too large to convert to float");
2477 return -1.0;
2478 }
2479 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002480}
2481
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002482/* Methods */
2483
2484static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002485long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002488}
2489
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002490static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002491long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (Py_SIZE(a) != Py_SIZE(b)) {
2496 sign = Py_SIZE(a) - Py_SIZE(b);
2497 }
2498 else {
2499 Py_ssize_t i = ABS(Py_SIZE(a));
2500 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2501 ;
2502 if (i < 0)
2503 sign = 0;
2504 else {
2505 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2506 if (Py_SIZE(a) < 0)
2507 sign = -sign;
2508 }
2509 }
2510 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002511}
2512
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002513#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002515
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002516static PyObject *
2517long_richcompare(PyObject *self, PyObject *other, int op)
2518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 int result;
2520 PyObject *v;
2521 CHECK_BINOP(self, other);
2522 if (self == other)
2523 result = 0;
2524 else
2525 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2526 /* Convert the return value to a Boolean */
2527 switch (op) {
2528 case Py_EQ:
2529 v = TEST_COND(result == 0);
2530 break;
2531 case Py_NE:
2532 v = TEST_COND(result != 0);
2533 break;
2534 case Py_LE:
2535 v = TEST_COND(result <= 0);
2536 break;
2537 case Py_GE:
2538 v = TEST_COND(result >= 0);
2539 break;
2540 case Py_LT:
2541 v = TEST_COND(result == -1);
2542 break;
2543 case Py_GT:
2544 v = TEST_COND(result == 1);
2545 break;
2546 default:
2547 PyErr_BadArgument();
2548 return NULL;
2549 }
2550 Py_INCREF(v);
2551 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002552}
2553
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002554static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002555long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002556{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002557 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 Py_ssize_t i;
2559 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 i = Py_SIZE(v);
2562 switch(i) {
2563 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2564 case 0: return 0;
2565 case 1: return v->ob_digit[0];
2566 }
2567 sign = 1;
2568 x = 0;
2569 if (i < 0) {
2570 sign = -1;
2571 i = -(i);
2572 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002574 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2575 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2576 _PyHASH_MODULUS.
2577
2578 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2579 amounts to a rotation of the bits of x. To see this, write
2580
2581 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2582
2583 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2584 PyLong_SHIFT bits of x (those that are shifted out of the
2585 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2586 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2587 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2588 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2589 congruent to y modulo _PyHASH_MODULUS. So
2590
2591 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2592
2593 The right-hand side is just the result of rotating the
2594 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2595 not all _PyHASH_BITS bits of x are 1s, the same is true
2596 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2597 the reduction of x*2**PyLong_SHIFT modulo
2598 _PyHASH_MODULUS. */
2599 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2600 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002602 if (x >= _PyHASH_MODULUS)
2603 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 }
2605 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002606 if (x == (Py_uhash_t)-1)
2607 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002608 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002609}
2610
2611
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002612/* Add the absolute values of two long integers. */
2613
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002614static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002615x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2618 PyLongObject *z;
2619 Py_ssize_t i;
2620 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 /* Ensure a is the larger of the two: */
2623 if (size_a < size_b) {
2624 { PyLongObject *temp = a; a = b; b = temp; }
2625 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002626 size_a = size_b;
2627 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 }
2629 z = _PyLong_New(size_a+1);
2630 if (z == NULL)
2631 return NULL;
2632 for (i = 0; i < size_b; ++i) {
2633 carry += a->ob_digit[i] + b->ob_digit[i];
2634 z->ob_digit[i] = carry & PyLong_MASK;
2635 carry >>= PyLong_SHIFT;
2636 }
2637 for (; i < size_a; ++i) {
2638 carry += a->ob_digit[i];
2639 z->ob_digit[i] = carry & PyLong_MASK;
2640 carry >>= PyLong_SHIFT;
2641 }
2642 z->ob_digit[i] = carry;
2643 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002644}
2645
2646/* Subtract the absolute values of two integers. */
2647
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002648static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002649x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2652 PyLongObject *z;
2653 Py_ssize_t i;
2654 int sign = 1;
2655 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 /* Ensure a is the larger of the two: */
2658 if (size_a < size_b) {
2659 sign = -1;
2660 { PyLongObject *temp = a; a = b; b = temp; }
2661 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002662 size_a = size_b;
2663 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 }
2665 else if (size_a == size_b) {
2666 /* Find highest digit where a and b differ: */
2667 i = size_a;
2668 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2669 ;
2670 if (i < 0)
2671 return (PyLongObject *)PyLong_FromLong(0);
2672 if (a->ob_digit[i] < b->ob_digit[i]) {
2673 sign = -1;
2674 { PyLongObject *temp = a; a = b; b = temp; }
2675 }
2676 size_a = size_b = i+1;
2677 }
2678 z = _PyLong_New(size_a);
2679 if (z == NULL)
2680 return NULL;
2681 for (i = 0; i < size_b; ++i) {
2682 /* The following assumes unsigned arithmetic
2683 works module 2**N for some N>PyLong_SHIFT. */
2684 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2685 z->ob_digit[i] = borrow & PyLong_MASK;
2686 borrow >>= PyLong_SHIFT;
2687 borrow &= 1; /* Keep only one sign bit */
2688 }
2689 for (; i < size_a; ++i) {
2690 borrow = a->ob_digit[i] - borrow;
2691 z->ob_digit[i] = borrow & PyLong_MASK;
2692 borrow >>= PyLong_SHIFT;
2693 borrow &= 1; /* Keep only one sign bit */
2694 }
2695 assert(borrow == 0);
2696 if (sign < 0)
2697 NEGATE(z);
2698 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002699}
2700
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002701static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002702long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2709 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2710 MEDIUM_VALUE(b));
2711 return result;
2712 }
2713 if (Py_SIZE(a) < 0) {
2714 if (Py_SIZE(b) < 0) {
2715 z = x_add(a, b);
2716 if (z != NULL && Py_SIZE(z) != 0)
2717 Py_SIZE(z) = -(Py_SIZE(z));
2718 }
2719 else
2720 z = x_sub(b, a);
2721 }
2722 else {
2723 if (Py_SIZE(b) < 0)
2724 z = x_sub(a, b);
2725 else
2726 z = x_add(a, b);
2727 }
2728 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002729}
2730
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002731static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002732long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2739 PyObject* r;
2740 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2741 return r;
2742 }
2743 if (Py_SIZE(a) < 0) {
2744 if (Py_SIZE(b) < 0)
2745 z = x_sub(a, b);
2746 else
2747 z = x_add(a, b);
2748 if (z != NULL && Py_SIZE(z) != 0)
2749 Py_SIZE(z) = -(Py_SIZE(z));
2750 }
2751 else {
2752 if (Py_SIZE(b) < 0)
2753 z = x_add(a, b);
2754 else
2755 z = x_sub(a, b);
2756 }
2757 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002758}
2759
Tim Peters5af4e6c2002-08-12 02:31:19 +00002760/* Grade school multiplication, ignoring the signs.
2761 * Returns the absolute value of the product, or NULL if error.
2762 */
2763static PyLongObject *
2764x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyLongObject *z;
2767 Py_ssize_t size_a = ABS(Py_SIZE(a));
2768 Py_ssize_t size_b = ABS(Py_SIZE(b));
2769 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 z = _PyLong_New(size_a + size_b);
2772 if (z == NULL)
2773 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2776 if (a == b) {
2777 /* Efficient squaring per HAC, Algorithm 14.16:
2778 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2779 * Gives slightly less than a 2x speedup when a == b,
2780 * via exploiting that each entry in the multiplication
2781 * pyramid appears twice (except for the size_a squares).
2782 */
2783 for (i = 0; i < size_a; ++i) {
2784 twodigits carry;
2785 twodigits f = a->ob_digit[i];
2786 digit *pz = z->ob_digit + (i << 1);
2787 digit *pa = a->ob_digit + i + 1;
2788 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002791 Py_DECREF(z);
2792 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002793 });
Tim Peters0973b992004-08-29 22:16:50 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 carry = *pz + f * f;
2796 *pz++ = (digit)(carry & PyLong_MASK);
2797 carry >>= PyLong_SHIFT;
2798 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 /* Now f is added in twice in each column of the
2801 * pyramid it appears. Same as adding f<<1 once.
2802 */
2803 f <<= 1;
2804 while (pa < paend) {
2805 carry += *pz + *pa++ * f;
2806 *pz++ = (digit)(carry & PyLong_MASK);
2807 carry >>= PyLong_SHIFT;
2808 assert(carry <= (PyLong_MASK << 1));
2809 }
2810 if (carry) {
2811 carry += *pz;
2812 *pz++ = (digit)(carry & PyLong_MASK);
2813 carry >>= PyLong_SHIFT;
2814 }
2815 if (carry)
2816 *pz += (digit)(carry & PyLong_MASK);
2817 assert((carry >> PyLong_SHIFT) == 0);
2818 }
2819 }
2820 else { /* a is not the same as b -- gradeschool long mult */
2821 for (i = 0; i < size_a; ++i) {
2822 twodigits carry = 0;
2823 twodigits f = a->ob_digit[i];
2824 digit *pz = z->ob_digit + i;
2825 digit *pb = b->ob_digit;
2826 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002829 Py_DECREF(z);
2830 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002831 });
Tim Peters0973b992004-08-29 22:16:50 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 while (pb < pbend) {
2834 carry += *pz + *pb++ * f;
2835 *pz++ = (digit)(carry & PyLong_MASK);
2836 carry >>= PyLong_SHIFT;
2837 assert(carry <= PyLong_MASK);
2838 }
2839 if (carry)
2840 *pz += (digit)(carry & PyLong_MASK);
2841 assert((carry >> PyLong_SHIFT) == 0);
2842 }
2843 }
2844 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002845}
2846
2847/* A helper for Karatsuba multiplication (k_mul).
2848 Takes a long "n" and an integer "size" representing the place to
2849 split, and sets low and high such that abs(n) == (high << size) + low,
2850 viewing the shift as being by digits. The sign bit is ignored, and
2851 the return values are >= 0.
2852 Returns 0 on success, -1 on failure.
2853*/
2854static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002855kmul_split(PyLongObject *n,
2856 Py_ssize_t size,
2857 PyLongObject **high,
2858 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 PyLongObject *hi, *lo;
2861 Py_ssize_t size_lo, size_hi;
2862 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 size_lo = MIN(size_n, size);
2865 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 if ((hi = _PyLong_New(size_hi)) == NULL)
2868 return -1;
2869 if ((lo = _PyLong_New(size_lo)) == NULL) {
2870 Py_DECREF(hi);
2871 return -1;
2872 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2875 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 *high = long_normalize(hi);
2878 *low = long_normalize(lo);
2879 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002880}
2881
Tim Peters60004642002-08-12 22:01:34 +00002882static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2883
Tim Peters5af4e6c2002-08-12 02:31:19 +00002884/* Karatsuba multiplication. Ignores the input signs, and returns the
2885 * absolute value of the product (or NULL if error).
2886 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2887 */
2888static PyLongObject *
2889k_mul(PyLongObject *a, PyLongObject *b)
2890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 Py_ssize_t asize = ABS(Py_SIZE(a));
2892 Py_ssize_t bsize = ABS(Py_SIZE(b));
2893 PyLongObject *ah = NULL;
2894 PyLongObject *al = NULL;
2895 PyLongObject *bh = NULL;
2896 PyLongObject *bl = NULL;
2897 PyLongObject *ret = NULL;
2898 PyLongObject *t1, *t2, *t3;
2899 Py_ssize_t shift; /* the number of digits we split off */
2900 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2903 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2904 * Then the original product is
2905 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2906 * By picking X to be a power of 2, "*X" is just shifting, and it's
2907 * been reduced to 3 multiplies on numbers half the size.
2908 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002910 /* We want to split based on the larger number; fiddle so that b
2911 * is largest.
2912 */
2913 if (asize > bsize) {
2914 t1 = a;
2915 a = b;
2916 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 i = asize;
2919 asize = bsize;
2920 bsize = i;
2921 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 /* Use gradeschool math when either number is too small. */
2924 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2925 if (asize <= i) {
2926 if (asize == 0)
2927 return (PyLongObject *)PyLong_FromLong(0);
2928 else
2929 return x_mul(a, b);
2930 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 /* If a is small compared to b, splitting on b gives a degenerate
2933 * case with ah==0, and Karatsuba may be (even much) less efficient
2934 * than "grade school" then. However, we can still win, by viewing
2935 * b as a string of "big digits", each of width a->ob_size. That
2936 * leads to a sequence of balanced calls to k_mul.
2937 */
2938 if (2 * asize <= bsize)
2939 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 /* Split a & b into hi & lo pieces. */
2942 shift = bsize >> 1;
2943 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2944 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 if (a == b) {
2947 bh = ah;
2948 bl = al;
2949 Py_INCREF(bh);
2950 Py_INCREF(bl);
2951 }
2952 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 /* The plan:
2955 * 1. Allocate result space (asize + bsize digits: that's always
2956 * enough).
2957 * 2. Compute ah*bh, and copy into result at 2*shift.
2958 * 3. Compute al*bl, and copy into result at 0. Note that this
2959 * can't overlap with #2.
2960 * 4. Subtract al*bl from the result, starting at shift. This may
2961 * underflow (borrow out of the high digit), but we don't care:
2962 * we're effectively doing unsigned arithmetic mod
2963 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2964 * borrows and carries out of the high digit can be ignored.
2965 * 5. Subtract ah*bh from the result, starting at shift.
2966 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2967 * at shift.
2968 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 /* 1. Allocate result space. */
2971 ret = _PyLong_New(asize + bsize);
2972 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002973#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 /* Fill with trash, to catch reference to uninitialized digits. */
2975 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002976#endif
Tim Peters44121a62002-08-12 06:17:58 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2979 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2980 assert(Py_SIZE(t1) >= 0);
2981 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2982 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2983 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 /* Zero-out the digits higher than the ah*bh copy. */
2986 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2987 if (i)
2988 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2989 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 /* 3. t2 <- al*bl, and copy into the low digits. */
2992 if ((t2 = k_mul(al, bl)) == NULL) {
2993 Py_DECREF(t1);
2994 goto fail;
2995 }
2996 assert(Py_SIZE(t2) >= 0);
2997 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2998 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 /* Zero out remaining digits. */
3001 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3002 if (i)
3003 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3006 * because it's fresher in cache.
3007 */
3008 i = Py_SIZE(ret) - shift; /* # digits after shift */
3009 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3010 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3013 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3016 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3017 Py_DECREF(ah);
3018 Py_DECREF(al);
3019 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 if (a == b) {
3022 t2 = t1;
3023 Py_INCREF(t2);
3024 }
3025 else if ((t2 = x_add(bh, bl)) == NULL) {
3026 Py_DECREF(t1);
3027 goto fail;
3028 }
3029 Py_DECREF(bh);
3030 Py_DECREF(bl);
3031 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 t3 = k_mul(t1, t2);
3034 Py_DECREF(t1);
3035 Py_DECREF(t2);
3036 if (t3 == NULL) goto fail;
3037 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 /* Add t3. It's not obvious why we can't run out of room here.
3040 * See the (*) comment after this function.
3041 */
3042 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3043 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003046
Mark Dickinson22b20182010-05-10 21:27:53 +00003047 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 Py_XDECREF(ret);
3049 Py_XDECREF(ah);
3050 Py_XDECREF(al);
3051 Py_XDECREF(bh);
3052 Py_XDECREF(bl);
3053 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003054}
3055
Tim Petersd6974a52002-08-13 20:37:51 +00003056/* (*) Why adding t3 can't "run out of room" above.
3057
Tim Petersab86c2b2002-08-15 20:06:00 +00003058Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3059to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003060
Tim Petersab86c2b2002-08-15 20:06:00 +000030611. For any integer i, i = c(i/2) + f(i/2). In particular,
3062 bsize = c(bsize/2) + f(bsize/2).
30632. shift = f(bsize/2)
30643. asize <= bsize
30654. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3066 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003067
Tim Petersab86c2b2002-08-15 20:06:00 +00003068We allocated asize + bsize result digits, and add t3 into them at an offset
3069of shift. This leaves asize+bsize-shift allocated digit positions for t3
3070to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3071asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003072
Tim Petersab86c2b2002-08-15 20:06:00 +00003073bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3074at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003075
Tim Petersab86c2b2002-08-15 20:06:00 +00003076If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3077digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3078most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003079
Tim Petersab86c2b2002-08-15 20:06:00 +00003080The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003081
Tim Petersab86c2b2002-08-15 20:06:00 +00003082 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003083
Tim Petersab86c2b2002-08-15 20:06:00 +00003084and we have asize + c(bsize/2) available digit positions. We need to show
3085this is always enough. An instance of c(bsize/2) cancels out in both, so
3086the question reduces to whether asize digits is enough to hold
3087(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3088then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3089asize 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 +00003090digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003091asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003092c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3093is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3094bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003095
Tim Peters48d52c02002-08-14 17:07:32 +00003096Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3097clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3098ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003099*/
3100
Tim Peters60004642002-08-12 22:01:34 +00003101/* b has at least twice the digits of a, and a is big enough that Karatsuba
3102 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3103 * of slices, each with a->ob_size digits, and multiply the slices by a,
3104 * one at a time. This gives k_mul balanced inputs to work with, and is
3105 * also cache-friendly (we compute one double-width slice of the result
3106 * at a time, then move on, never bactracking except for the helpful
3107 * single-width slice overlap between successive partial sums).
3108 */
3109static PyLongObject *
3110k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 const Py_ssize_t asize = ABS(Py_SIZE(a));
3113 Py_ssize_t bsize = ABS(Py_SIZE(b));
3114 Py_ssize_t nbdone; /* # of b digits already multiplied */
3115 PyLongObject *ret;
3116 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118 assert(asize > KARATSUBA_CUTOFF);
3119 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 /* Allocate result space, and zero it out. */
3122 ret = _PyLong_New(asize + bsize);
3123 if (ret == NULL)
3124 return NULL;
3125 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 /* Successive slices of b are copied into bslice. */
3128 bslice = _PyLong_New(asize);
3129 if (bslice == NULL)
3130 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 nbdone = 0;
3133 while (bsize > 0) {
3134 PyLongObject *product;
3135 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 /* Multiply the next slice of b by a. */
3138 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3139 nbtouse * sizeof(digit));
3140 Py_SIZE(bslice) = nbtouse;
3141 product = k_mul(a, bslice);
3142 if (product == NULL)
3143 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 /* Add into result. */
3146 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3147 product->ob_digit, Py_SIZE(product));
3148 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 bsize -= nbtouse;
3151 nbdone += nbtouse;
3152 }
Tim Peters60004642002-08-12 22:01:34 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 Py_DECREF(bslice);
3155 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003156
Mark Dickinson22b20182010-05-10 21:27:53 +00003157 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 Py_DECREF(ret);
3159 Py_XDECREF(bslice);
3160 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003161}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003162
3163static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003164long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 /* fast path for single-digit multiplication */
3171 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3172 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003173#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003175#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 /* if we don't have long long then we're almost certainly
3177 using 15-bit digits, so v will fit in a long. In the
3178 unlikely event that we're using 30-bit digits on a platform
3179 without long long, a large v will just cause us to fall
3180 through to the general multiplication code below. */
3181 if (v >= LONG_MIN && v <= LONG_MAX)
3182 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003183#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 z = k_mul(a, b);
3187 /* Negate if exactly one of the inputs is negative. */
3188 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3189 NEGATE(z);
3190 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003191}
3192
Guido van Rossume32e0141992-01-19 16:31:05 +00003193/* The / and % operators are now defined in terms of divmod().
3194 The expression a mod b has the value a - b*floor(a/b).
3195 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003196 |a| by |b|, with the sign of a. This is also expressed
3197 as a - b*trunc(a/b), if trunc truncates towards zero.
3198 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 a b a rem b a mod b
3200 13 10 3 3
3201 -13 10 -3 7
3202 13 -10 3 -7
3203 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003204 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003205 have different signs. We then subtract one from the 'div'
3206 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003207
Tim Peters47e52ee2004-08-30 02:44:38 +00003208/* Compute
3209 * *pdiv, *pmod = divmod(v, w)
3210 * NULL can be passed for pdiv or pmod, in which case that part of
3211 * the result is simply thrown away. The caller owns a reference to
3212 * each of these it requests (does not pass NULL for).
3213 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003214static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003215l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 if (long_divrem(v, w, &div, &mod) < 0)
3221 return -1;
3222 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3223 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3224 PyLongObject *temp;
3225 PyLongObject *one;
3226 temp = (PyLongObject *) long_add(mod, w);
3227 Py_DECREF(mod);
3228 mod = temp;
3229 if (mod == NULL) {
3230 Py_DECREF(div);
3231 return -1;
3232 }
3233 one = (PyLongObject *) PyLong_FromLong(1L);
3234 if (one == NULL ||
3235 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3236 Py_DECREF(mod);
3237 Py_DECREF(div);
3238 Py_XDECREF(one);
3239 return -1;
3240 }
3241 Py_DECREF(one);
3242 Py_DECREF(div);
3243 div = temp;
3244 }
3245 if (pdiv != NULL)
3246 *pdiv = div;
3247 else
3248 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (pmod != NULL)
3251 *pmod = mod;
3252 else
3253 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003256}
3257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003258static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003259long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003263 CHECK_BINOP(a, b);
3264 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3265 div = NULL;
3266 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003267}
3268
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003269/* PyLong/PyLong -> float, with correctly rounded result. */
3270
3271#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3272#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003274static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003275long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 PyLongObject *a, *b, *x;
3278 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3279 digit mask, low;
3280 int inexact, negate, a_is_small, b_is_small;
3281 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 CHECK_BINOP(v, w);
3284 a = (PyLongObject *)v;
3285 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 /*
3288 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3291 1. choose a suitable integer 'shift'
3292 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3293 3. adjust x for correct rounding
3294 4. convert x to a double dx with the same value
3295 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3300 returns either 0.0 or -0.0, depending on the sign of b. For a and
3301 b both nonzero, ignore signs of a and b, and add the sign back in
3302 at the end. Now write a_bits and b_bits for the bit lengths of a
3303 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3304 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3309 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3310 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3311 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 1. The integer 'shift' is chosen so that x has the right number of
3316 bits for a double, plus two or three extra bits that will be used
3317 in the rounding decisions. Writing a_bits and b_bits for the
3318 number of significant bits in a and b respectively, a
3319 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 This is fine in the usual case, but if a/b is smaller than the
3324 smallest normal float then it can lead to double rounding on an
3325 IEEE 754 platform, giving incorrectly rounded results. So we
3326 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 2. The quantity x is computed by first shifting a (left -shift bits
3331 if shift <= 0, right shift bits if shift > 0) and then dividing by
3332 b. For both the shift and the division, we keep track of whether
3333 the result is inexact, in a flag 'inexact'; this information is
3334 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 With the choice of shift above, together with our assumption that
3337 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3338 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3341 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 For float representability, we need x/2**extra_bits <
3346 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3347 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 To round, we just modify the bottom digit of x in-place; this can
3352 end up giving a digit with value > PyLONG_MASK, but that's not a
3353 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 With the original choices for shift above, extra_bits will always
3356 be 2 or 3. Then rounding under the round-half-to-even rule, we
3357 round up iff the most significant of the extra bits is 1, and
3358 either: (a) the computation of x in step 2 had an inexact result,
3359 or (b) at least one other of the extra bits is 1, or (c) the least
3360 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 4. Conversion to a double is straightforward; all floating-point
3363 operations involved in the conversion are exact, so there's no
3364 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3367 The result will always be exactly representable as a double, except
3368 in the case that it overflows. To avoid dependence on the exact
3369 behaviour of ldexp on overflow, we check for overflow before
3370 applying ldexp. The result of ldexp is adjusted for sign before
3371 returning.
3372 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 /* Reduce to case where a and b are both positive. */
3375 a_size = ABS(Py_SIZE(a));
3376 b_size = ABS(Py_SIZE(b));
3377 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3378 if (b_size == 0) {
3379 PyErr_SetString(PyExc_ZeroDivisionError,
3380 "division by zero");
3381 goto error;
3382 }
3383 if (a_size == 0)
3384 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* Fast path for a and b small (exactly representable in a double).
3387 Relies on floating-point division being correctly rounded; results
3388 may be subject to double rounding on x86 machines that operate with
3389 the x87 FPU set to 64-bit precision. */
3390 a_is_small = a_size <= MANT_DIG_DIGITS ||
3391 (a_size == MANT_DIG_DIGITS+1 &&
3392 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3393 b_is_small = b_size <= MANT_DIG_DIGITS ||
3394 (b_size == MANT_DIG_DIGITS+1 &&
3395 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3396 if (a_is_small && b_is_small) {
3397 double da, db;
3398 da = a->ob_digit[--a_size];
3399 while (a_size > 0)
3400 da = da * PyLong_BASE + a->ob_digit[--a_size];
3401 db = b->ob_digit[--b_size];
3402 while (b_size > 0)
3403 db = db * PyLong_BASE + b->ob_digit[--b_size];
3404 result = da / db;
3405 goto success;
3406 }
Tim Peterse2a60002001-09-04 06:17:36 +00003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 /* Catch obvious cases of underflow and overflow */
3409 diff = a_size - b_size;
3410 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3411 /* Extreme overflow */
3412 goto overflow;
3413 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3414 /* Extreme underflow */
3415 goto underflow_or_zero;
3416 /* Next line is now safe from overflowing a Py_ssize_t */
3417 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3418 bits_in_digit(b->ob_digit[b_size - 1]);
3419 /* Now diff = a_bits - b_bits. */
3420 if (diff > DBL_MAX_EXP)
3421 goto overflow;
3422 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3423 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 /* Choose value for shift; see comments for step 1 above. */
3426 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 /* x = abs(a * 2**-shift) */
3431 if (shift <= 0) {
3432 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3433 digit rem;
3434 /* x = a << -shift */
3435 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3436 /* In practice, it's probably impossible to end up
3437 here. Both a and b would have to be enormous,
3438 using close to SIZE_T_MAX bytes of memory each. */
3439 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003440 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 goto error;
3442 }
3443 x = _PyLong_New(a_size + shift_digits + 1);
3444 if (x == NULL)
3445 goto error;
3446 for (i = 0; i < shift_digits; i++)
3447 x->ob_digit[i] = 0;
3448 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3449 a_size, -shift % PyLong_SHIFT);
3450 x->ob_digit[a_size + shift_digits] = rem;
3451 }
3452 else {
3453 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3454 digit rem;
3455 /* x = a >> shift */
3456 assert(a_size >= shift_digits);
3457 x = _PyLong_New(a_size - shift_digits);
3458 if (x == NULL)
3459 goto error;
3460 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3461 a_size - shift_digits, shift % PyLong_SHIFT);
3462 /* set inexact if any of the bits shifted out is nonzero */
3463 if (rem)
3464 inexact = 1;
3465 while (!inexact && shift_digits > 0)
3466 if (a->ob_digit[--shift_digits])
3467 inexact = 1;
3468 }
3469 long_normalize(x);
3470 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3473 reference to x, so it's safe to modify it in-place. */
3474 if (b_size == 1) {
3475 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3476 b->ob_digit[0]);
3477 long_normalize(x);
3478 if (rem)
3479 inexact = 1;
3480 }
3481 else {
3482 PyLongObject *div, *rem;
3483 div = x_divrem(x, b, &rem);
3484 Py_DECREF(x);
3485 x = div;
3486 if (x == NULL)
3487 goto error;
3488 if (Py_SIZE(rem))
3489 inexact = 1;
3490 Py_DECREF(rem);
3491 }
3492 x_size = ABS(Py_SIZE(x));
3493 assert(x_size > 0); /* result of division is never zero */
3494 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 /* The number of extra bits that have to be rounded away. */
3497 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3498 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 /* Round by directly modifying the low digit of x. */
3501 mask = (digit)1 << (extra_bits - 1);
3502 low = x->ob_digit[0] | inexact;
3503 if (low & mask && low & (3*mask-1))
3504 low += mask;
3505 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 /* Convert x to a double dx; the conversion is exact. */
3508 dx = x->ob_digit[--x_size];
3509 while (x_size > 0)
3510 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3511 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 /* Check whether ldexp result will overflow a double. */
3514 if (shift + x_bits >= DBL_MAX_EXP &&
3515 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3516 goto overflow;
3517 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003518
3519 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003521
3522 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003524
3525 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 PyErr_SetString(PyExc_OverflowError,
3527 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003528 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003530}
3531
3532static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003533long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 CHECK_BINOP(a, b);
3538
3539 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3540 mod = NULL;
3541 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003542}
3543
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003544static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003545long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 PyLongObject *div, *mod;
3548 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3553 return NULL;
3554 }
3555 z = PyTuple_New(2);
3556 if (z != NULL) {
3557 PyTuple_SetItem(z, 0, (PyObject *) div);
3558 PyTuple_SetItem(z, 1, (PyObject *) mod);
3559 }
3560 else {
3561 Py_DECREF(div);
3562 Py_DECREF(mod);
3563 }
3564 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003565}
3566
Tim Peters47e52ee2004-08-30 02:44:38 +00003567/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003568static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003569long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3572 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 PyLongObject *z = NULL; /* accumulated result */
3575 Py_ssize_t i, j, k; /* counters */
3576 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 /* 5-ary values. If the exponent is large enough, table is
3579 * precomputed so that table[i] == a**i % c for i in range(32).
3580 */
3581 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3582 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 /* a, b, c = v, w, x */
3585 CHECK_BINOP(v, w);
3586 a = (PyLongObject*)v; Py_INCREF(a);
3587 b = (PyLongObject*)w; Py_INCREF(b);
3588 if (PyLong_Check(x)) {
3589 c = (PyLongObject *)x;
3590 Py_INCREF(x);
3591 }
3592 else if (x == Py_None)
3593 c = NULL;
3594 else {
3595 Py_DECREF(a);
3596 Py_DECREF(b);
3597 Py_INCREF(Py_NotImplemented);
3598 return Py_NotImplemented;
3599 }
Tim Peters4c483c42001-09-05 06:24:58 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3602 if (c) {
3603 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003604 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 goto Error;
3606 }
3607 else {
3608 /* else return a float. This works because we know
3609 that this calls float_pow() which converts its
3610 arguments to double. */
3611 Py_DECREF(a);
3612 Py_DECREF(b);
3613 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3614 }
3615 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 if (c) {
3618 /* if modulus == 0:
3619 raise ValueError() */
3620 if (Py_SIZE(c) == 0) {
3621 PyErr_SetString(PyExc_ValueError,
3622 "pow() 3rd argument cannot be 0");
3623 goto Error;
3624 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* if modulus < 0:
3627 negativeOutput = True
3628 modulus = -modulus */
3629 if (Py_SIZE(c) < 0) {
3630 negativeOutput = 1;
3631 temp = (PyLongObject *)_PyLong_Copy(c);
3632 if (temp == NULL)
3633 goto Error;
3634 Py_DECREF(c);
3635 c = temp;
3636 temp = NULL;
3637 NEGATE(c);
3638 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 /* if modulus == 1:
3641 return 0 */
3642 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3643 z = (PyLongObject *)PyLong_FromLong(0L);
3644 goto Done;
3645 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 /* if base < 0:
3648 base = base % modulus
3649 Having the base positive just makes things easier. */
3650 if (Py_SIZE(a) < 0) {
3651 if (l_divmod(a, c, NULL, &temp) < 0)
3652 goto Error;
3653 Py_DECREF(a);
3654 a = temp;
3655 temp = NULL;
3656 }
3657 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 /* At this point a, b, and c are guaranteed non-negative UNLESS
3660 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 z = (PyLongObject *)PyLong_FromLong(1L);
3663 if (z == NULL)
3664 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 /* Perform a modular reduction, X = X % c, but leave X alone if c
3667 * is NULL.
3668 */
3669#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003670 do { \
3671 if (c != NULL) { \
3672 if (l_divmod(X, c, NULL, &temp) < 0) \
3673 goto Error; \
3674 Py_XDECREF(X); \
3675 X = temp; \
3676 temp = NULL; \
3677 } \
3678 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 /* Multiply two values, then reduce the result:
3681 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003682#define MULT(X, Y, result) \
3683 do { \
3684 temp = (PyLongObject *)long_mul(X, Y); \
3685 if (temp == NULL) \
3686 goto Error; \
3687 Py_XDECREF(result); \
3688 result = temp; \
3689 temp = NULL; \
3690 REDUCE(result); \
3691 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3694 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3695 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3696 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3697 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003700 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003702 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 }
3704 }
3705 }
3706 else {
3707 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3708 Py_INCREF(z); /* still holds 1L */
3709 table[0] = z;
3710 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003711 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3714 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3717 const int index = (bi >> j) & 0x1f;
3718 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003719 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003721 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 }
3723 }
3724 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 if (negativeOutput && (Py_SIZE(z) != 0)) {
3727 temp = (PyLongObject *)long_sub(z, c);
3728 if (temp == NULL)
3729 goto Error;
3730 Py_DECREF(z);
3731 z = temp;
3732 temp = NULL;
3733 }
3734 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003735
Mark Dickinson22b20182010-05-10 21:27:53 +00003736 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 if (z != NULL) {
3738 Py_DECREF(z);
3739 z = NULL;
3740 }
3741 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003742 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3744 for (i = 0; i < 32; ++i)
3745 Py_XDECREF(table[i]);
3746 }
3747 Py_DECREF(a);
3748 Py_DECREF(b);
3749 Py_XDECREF(c);
3750 Py_XDECREF(temp);
3751 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003752}
3753
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003754static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003755long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 /* Implement ~x as -(x+1) */
3758 PyLongObject *x;
3759 PyLongObject *w;
3760 if (ABS(Py_SIZE(v)) <=1)
3761 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3762 w = (PyLongObject *)PyLong_FromLong(1L);
3763 if (w == NULL)
3764 return NULL;
3765 x = (PyLongObject *) long_add(v, w);
3766 Py_DECREF(w);
3767 if (x == NULL)
3768 return NULL;
3769 Py_SIZE(x) = -(Py_SIZE(x));
3770 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003771}
3772
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003773static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003774long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 PyLongObject *z;
3777 if (ABS(Py_SIZE(v)) <= 1)
3778 return PyLong_FromLong(-MEDIUM_VALUE(v));
3779 z = (PyLongObject *)_PyLong_Copy(v);
3780 if (z != NULL)
3781 Py_SIZE(z) = -(Py_SIZE(v));
3782 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003783}
3784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003785static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003786long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 if (Py_SIZE(v) < 0)
3789 return long_neg(v);
3790 else
3791 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003792}
3793
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003794static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003795long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003798}
3799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003800static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003801long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 PyLongObject *z = NULL;
3804 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3805 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 if (Py_SIZE(a) < 0) {
3810 /* Right shifting negative numbers is harder */
3811 PyLongObject *a1, *a2;
3812 a1 = (PyLongObject *) long_invert(a);
3813 if (a1 == NULL)
3814 goto rshift_error;
3815 a2 = (PyLongObject *) long_rshift(a1, b);
3816 Py_DECREF(a1);
3817 if (a2 == NULL)
3818 goto rshift_error;
3819 z = (PyLongObject *) long_invert(a2);
3820 Py_DECREF(a2);
3821 }
3822 else {
3823 shiftby = PyLong_AsSsize_t((PyObject *)b);
3824 if (shiftby == -1L && PyErr_Occurred())
3825 goto rshift_error;
3826 if (shiftby < 0) {
3827 PyErr_SetString(PyExc_ValueError,
3828 "negative shift count");
3829 goto rshift_error;
3830 }
3831 wordshift = shiftby / PyLong_SHIFT;
3832 newsize = ABS(Py_SIZE(a)) - wordshift;
3833 if (newsize <= 0)
3834 return PyLong_FromLong(0);
3835 loshift = shiftby % PyLong_SHIFT;
3836 hishift = PyLong_SHIFT - loshift;
3837 lomask = ((digit)1 << hishift) - 1;
3838 himask = PyLong_MASK ^ lomask;
3839 z = _PyLong_New(newsize);
3840 if (z == NULL)
3841 goto rshift_error;
3842 if (Py_SIZE(a) < 0)
3843 Py_SIZE(z) = -(Py_SIZE(z));
3844 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3845 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3846 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003847 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 }
3849 z = long_normalize(z);
3850 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003851 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003853
Guido van Rossumc6913e71991-11-19 20:26:46 +00003854}
3855
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003856static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003857long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003859 /* This version due to Tim Peters */
3860 PyLongObject *a = (PyLongObject*)v;
3861 PyLongObject *b = (PyLongObject*)w;
3862 PyLongObject *z = NULL;
3863 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3864 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 shiftby = PyLong_AsSsize_t((PyObject *)b);
3869 if (shiftby == -1L && PyErr_Occurred())
3870 goto lshift_error;
3871 if (shiftby < 0) {
3872 PyErr_SetString(PyExc_ValueError, "negative shift count");
3873 goto lshift_error;
3874 }
3875 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3876 wordshift = shiftby / PyLong_SHIFT;
3877 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 oldsize = ABS(Py_SIZE(a));
3880 newsize = oldsize + wordshift;
3881 if (remshift)
3882 ++newsize;
3883 z = _PyLong_New(newsize);
3884 if (z == NULL)
3885 goto lshift_error;
3886 if (Py_SIZE(a) < 0)
3887 NEGATE(z);
3888 for (i = 0; i < wordshift; i++)
3889 z->ob_digit[i] = 0;
3890 accum = 0;
3891 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3892 accum |= (twodigits)a->ob_digit[j] << remshift;
3893 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3894 accum >>= PyLong_SHIFT;
3895 }
3896 if (remshift)
3897 z->ob_digit[newsize-1] = (digit)accum;
3898 else
3899 assert(!accum);
3900 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003901 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003903}
3904
Mark Dickinson27a87a22009-10-25 20:43:34 +00003905/* Compute two's complement of digit vector a[0:m], writing result to
3906 z[0:m]. The digit vector a need not be normalized, but should not
3907 be entirely zero. a and z may point to the same digit vector. */
3908
3909static void
3910v_complement(digit *z, digit *a, Py_ssize_t m)
3911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 Py_ssize_t i;
3913 digit carry = 1;
3914 for (i = 0; i < m; ++i) {
3915 carry += a[i] ^ PyLong_MASK;
3916 z[i] = carry & PyLong_MASK;
3917 carry >>= PyLong_SHIFT;
3918 }
3919 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003920}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003921
3922/* Bitwise and/xor/or operations */
3923
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003924static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003925long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003927 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 int nega, negb, negz;
3930 Py_ssize_t size_a, size_b, size_z, i;
3931 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 /* Bitwise operations for negative numbers operate as though
3934 on a two's complement representation. So convert arguments
3935 from sign-magnitude to two's complement, and convert the
3936 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 /* If a is negative, replace it by its two's complement. */
3939 size_a = ABS(Py_SIZE(a));
3940 nega = Py_SIZE(a) < 0;
3941 if (nega) {
3942 z = _PyLong_New(size_a);
3943 if (z == NULL)
3944 return NULL;
3945 v_complement(z->ob_digit, a->ob_digit, size_a);
3946 a = z;
3947 }
3948 else
3949 /* Keep reference count consistent. */
3950 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 /* Same for b. */
3953 size_b = ABS(Py_SIZE(b));
3954 negb = Py_SIZE(b) < 0;
3955 if (negb) {
3956 z = _PyLong_New(size_b);
3957 if (z == NULL) {
3958 Py_DECREF(a);
3959 return NULL;
3960 }
3961 v_complement(z->ob_digit, b->ob_digit, size_b);
3962 b = z;
3963 }
3964 else
3965 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* Swap a and b if necessary to ensure size_a >= size_b. */
3968 if (size_a < size_b) {
3969 z = a; a = b; b = z;
3970 size_z = size_a; size_a = size_b; size_b = size_z;
3971 negz = nega; nega = negb; negb = negz;
3972 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* JRH: The original logic here was to allocate the result value (z)
3975 as the longer of the two operands. However, there are some cases
3976 where the result is guaranteed to be shorter than that: AND of two
3977 positives, OR of two negatives: use the shorter number. AND with
3978 mixed signs: use the positive number. OR with mixed signs: use the
3979 negative number.
3980 */
3981 switch (op) {
3982 case '^':
3983 negz = nega ^ negb;
3984 size_z = size_a;
3985 break;
3986 case '&':
3987 negz = nega & negb;
3988 size_z = negb ? size_a : size_b;
3989 break;
3990 case '|':
3991 negz = nega | negb;
3992 size_z = negb ? size_b : size_a;
3993 break;
3994 default:
3995 PyErr_BadArgument();
3996 return NULL;
3997 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003999 /* We allow an extra digit if z is negative, to make sure that
4000 the final two's complement of z doesn't overflow. */
4001 z = _PyLong_New(size_z + negz);
4002 if (z == NULL) {
4003 Py_DECREF(a);
4004 Py_DECREF(b);
4005 return NULL;
4006 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 /* Compute digits for overlap of a and b. */
4009 switch(op) {
4010 case '&':
4011 for (i = 0; i < size_b; ++i)
4012 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4013 break;
4014 case '|':
4015 for (i = 0; i < size_b; ++i)
4016 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4017 break;
4018 case '^':
4019 for (i = 0; i < size_b; ++i)
4020 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4021 break;
4022 default:
4023 PyErr_BadArgument();
4024 return NULL;
4025 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 /* Copy any remaining digits of a, inverting if necessary. */
4028 if (op == '^' && negb)
4029 for (; i < size_z; ++i)
4030 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4031 else if (i < size_z)
4032 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4033 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 /* Complement result if negative. */
4036 if (negz) {
4037 Py_SIZE(z) = -(Py_SIZE(z));
4038 z->ob_digit[size_z] = PyLong_MASK;
4039 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4040 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 Py_DECREF(a);
4043 Py_DECREF(b);
4044 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004045}
4046
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004047static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004048long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 PyObject *c;
4051 CHECK_BINOP(a, b);
4052 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4053 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004054}
4055
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004056static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004057long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004059 PyObject *c;
4060 CHECK_BINOP(a, b);
4061 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4062 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004063}
4064
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004065static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004066long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 PyObject *c;
4069 CHECK_BINOP(a, b);
4070 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4071 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004072}
4073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004074static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004075long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004077 if (PyLong_CheckExact(v))
4078 Py_INCREF(v);
4079 else
4080 v = _PyLong_Copy((PyLongObject *)v);
4081 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004082}
4083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004084static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004085long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 double result;
4088 result = PyLong_AsDouble(v);
4089 if (result == -1.0 && PyErr_Occurred())
4090 return NULL;
4091 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004092}
4093
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004094static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004095long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004096
Tim Peters6d6c1a32001-08-02 04:15:00 +00004097static PyObject *
4098long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4099{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004100 PyObject *obase = NULL, *x = NULL;
4101 long base;
4102 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 if (type != &PyLong_Type)
4106 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004107 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4108 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 return NULL;
4110 if (x == NULL)
4111 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004112 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004114
4115 base = PyLong_AsLongAndOverflow(obase, &overflow);
4116 if (base == -1 && PyErr_Occurred())
4117 return NULL;
4118 if (overflow || (base != 0 && base < 2) || base > 36) {
4119 PyErr_SetString(PyExc_ValueError,
4120 "int() arg 2 must be >= 2 and <= 36");
4121 return NULL;
4122 }
4123
4124 if (PyUnicode_Check(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4126 PyUnicode_GET_SIZE(x),
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004127 (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4129 /* Since PyLong_FromString doesn't have a length parameter,
4130 * check here for possible NULs in the string. */
4131 char *string;
4132 Py_ssize_t size = Py_SIZE(x);
4133 if (PyByteArray_Check(x))
4134 string = PyByteArray_AS_STRING(x);
4135 else
4136 string = PyBytes_AS_STRING(x);
4137 if (strlen(string) != (size_t)size) {
4138 /* We only see this if there's a null byte in x,
4139 x is a bytes or buffer, *and* a base is given. */
4140 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004141 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004142 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 return NULL;
4144 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004145 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 }
4147 else {
4148 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004149 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 return NULL;
4151 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004152}
4153
Guido van Rossumbef14172001-08-29 15:47:46 +00004154/* Wimpy, slow approach to tp_new calls for subtypes of long:
4155 first create a regular long from whatever arguments we got,
4156 then allocate a subtype instance and initialize it from
4157 the regular long. The regular long is then thrown away.
4158*/
4159static PyObject *
4160long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004162 PyLongObject *tmp, *newobj;
4163 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 assert(PyType_IsSubtype(type, &PyLong_Type));
4166 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4167 if (tmp == NULL)
4168 return NULL;
4169 assert(PyLong_CheckExact(tmp));
4170 n = Py_SIZE(tmp);
4171 if (n < 0)
4172 n = -n;
4173 newobj = (PyLongObject *)type->tp_alloc(type, n);
4174 if (newobj == NULL) {
4175 Py_DECREF(tmp);
4176 return NULL;
4177 }
4178 assert(PyLong_Check(newobj));
4179 Py_SIZE(newobj) = Py_SIZE(tmp);
4180 for (i = 0; i < n; i++)
4181 newobj->ob_digit[i] = tmp->ob_digit[i];
4182 Py_DECREF(tmp);
4183 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004184}
4185
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004186static PyObject *
4187long_getnewargs(PyLongObject *v)
4188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004190}
4191
Guido van Rossumb43daf72007-08-01 18:08:08 +00004192static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004193long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004195}
4196
4197static PyObject *
4198long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004200}
4201
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004202static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004203long__format__(PyObject *self, PyObject *args)
4204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4208 return NULL;
4209 return _PyLong_FormatAdvanced(self,
4210 PyUnicode_AS_UNICODE(format_spec),
4211 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004212}
4213
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004214/* Return a pair (q, r) such that a = b * q + r, and
4215 abs(r) <= abs(b)/2, with equality possible only if q is even.
4216 In other words, q == a / b, rounded to the nearest integer using
4217 round-half-to-even. */
4218
4219PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004220_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004221{
4222 PyLongObject *quo = NULL, *rem = NULL;
4223 PyObject *one = NULL, *twice_rem, *result, *temp;
4224 int cmp, quo_is_odd, quo_is_neg;
4225
4226 /* Equivalent Python code:
4227
4228 def divmod_near(a, b):
4229 q, r = divmod(a, b)
4230 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4231 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4232 # positive, 2 * r < b if b negative.
4233 greater_than_half = 2*r > b if b > 0 else 2*r < b
4234 exactly_half = 2*r == b
4235 if greater_than_half or exactly_half and q % 2 == 1:
4236 q += 1
4237 r -= b
4238 return q, r
4239
4240 */
4241 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4242 PyErr_SetString(PyExc_TypeError,
4243 "non-integer arguments in division");
4244 return NULL;
4245 }
4246
4247 /* Do a and b have different signs? If so, quotient is negative. */
4248 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4249
4250 one = PyLong_FromLong(1L);
4251 if (one == NULL)
4252 return NULL;
4253
4254 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4255 goto error;
4256
4257 /* compare twice the remainder with the divisor, to see
4258 if we need to adjust the quotient and remainder */
4259 twice_rem = long_lshift((PyObject *)rem, one);
4260 if (twice_rem == NULL)
4261 goto error;
4262 if (quo_is_neg) {
4263 temp = long_neg((PyLongObject*)twice_rem);
4264 Py_DECREF(twice_rem);
4265 twice_rem = temp;
4266 if (twice_rem == NULL)
4267 goto error;
4268 }
4269 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4270 Py_DECREF(twice_rem);
4271
4272 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4273 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4274 /* fix up quotient */
4275 if (quo_is_neg)
4276 temp = long_sub(quo, (PyLongObject *)one);
4277 else
4278 temp = long_add(quo, (PyLongObject *)one);
4279 Py_DECREF(quo);
4280 quo = (PyLongObject *)temp;
4281 if (quo == NULL)
4282 goto error;
4283 /* and remainder */
4284 if (quo_is_neg)
4285 temp = long_add(rem, (PyLongObject *)b);
4286 else
4287 temp = long_sub(rem, (PyLongObject *)b);
4288 Py_DECREF(rem);
4289 rem = (PyLongObject *)temp;
4290 if (rem == NULL)
4291 goto error;
4292 }
4293
4294 result = PyTuple_New(2);
4295 if (result == NULL)
4296 goto error;
4297
4298 /* PyTuple_SET_ITEM steals references */
4299 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4300 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4301 Py_DECREF(one);
4302 return result;
4303
4304 error:
4305 Py_XDECREF(quo);
4306 Py_XDECREF(rem);
4307 Py_XDECREF(one);
4308 return NULL;
4309}
4310
Eric Smith8c663262007-08-25 02:26:07 +00004311static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004312long_round(PyObject *self, PyObject *args)
4313{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004314 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004315
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004316 /* To round an integer m to the nearest 10**n (n positive), we make use of
4317 * the divmod_near operation, defined by:
4318 *
4319 * divmod_near(a, b) = (q, r)
4320 *
4321 * where q is the nearest integer to the quotient a / b (the
4322 * nearest even integer in the case of a tie) and r == a - q * b.
4323 * Hence q * b = a - r is the nearest multiple of b to a,
4324 * preferring even multiples in the case of a tie.
4325 *
4326 * So the nearest multiple of 10**n to m is:
4327 *
4328 * m - divmod_near(m, 10**n)[1].
4329 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004330 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4331 return NULL;
4332 if (o_ndigits == NULL)
4333 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004334
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004335 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 if (ndigits == NULL)
4337 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004338
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004339 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 if (Py_SIZE(ndigits) >= 0) {
4341 Py_DECREF(ndigits);
4342 return long_long(self);
4343 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004344
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004345 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4346 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004348 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004350 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004351
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004352 result = PyLong_FromLong(10L);
4353 if (result == NULL) {
4354 Py_DECREF(ndigits);
4355 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004357
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004358 temp = long_pow(result, ndigits, Py_None);
4359 Py_DECREF(ndigits);
4360 Py_DECREF(result);
4361 result = temp;
4362 if (result == NULL)
4363 return NULL;
4364
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004365 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004366 Py_DECREF(result);
4367 result = temp;
4368 if (result == NULL)
4369 return NULL;
4370
4371 temp = long_sub((PyLongObject *)self,
4372 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4373 Py_DECREF(result);
4374 result = temp;
4375
4376 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004377}
4378
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004379static PyObject *
4380long_sizeof(PyLongObject *v)
4381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4385 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004386}
4387
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004388static PyObject *
4389long_bit_length(PyLongObject *v)
4390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 PyLongObject *result, *x, *y;
4392 Py_ssize_t ndigits, msd_bits = 0;
4393 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 assert(v != NULL);
4396 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 ndigits = ABS(Py_SIZE(v));
4399 if (ndigits == 0)
4400 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 msd = v->ob_digit[ndigits-1];
4403 while (msd >= 32) {
4404 msd_bits += 6;
4405 msd >>= 6;
4406 }
4407 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4410 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 /* expression above may overflow; use Python integers instead */
4413 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4414 if (result == NULL)
4415 return NULL;
4416 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4417 if (x == NULL)
4418 goto error;
4419 y = (PyLongObject *)long_mul(result, x);
4420 Py_DECREF(x);
4421 if (y == NULL)
4422 goto error;
4423 Py_DECREF(result);
4424 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4427 if (x == NULL)
4428 goto error;
4429 y = (PyLongObject *)long_add(result, x);
4430 Py_DECREF(x);
4431 if (y == NULL)
4432 goto error;
4433 Py_DECREF(result);
4434 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004437
Mark Dickinson22b20182010-05-10 21:27:53 +00004438 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 Py_DECREF(result);
4440 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004441}
4442
4443PyDoc_STRVAR(long_bit_length_doc,
4444"int.bit_length() -> int\n\
4445\n\
4446Number of bits necessary to represent self in binary.\n\
4447>>> bin(37)\n\
4448'0b100101'\n\
4449>>> (37).bit_length()\n\
44506");
4451
Christian Heimes53876d92008-04-19 00:31:39 +00004452#if 0
4453static PyObject *
4454long_is_finite(PyObject *v)
4455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004457}
4458#endif
4459
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004460
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004461static PyObject *
4462long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 PyObject *byteorder_str;
4465 PyObject *is_signed_obj = NULL;
4466 Py_ssize_t length;
4467 int little_endian;
4468 int is_signed;
4469 PyObject *bytes;
4470 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4473 &length, &byteorder_str,
4474 &is_signed_obj))
4475 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 if (args != NULL && Py_SIZE(args) > 2) {
4478 PyErr_SetString(PyExc_TypeError,
4479 "'signed' is a keyword-only argument");
4480 return NULL;
4481 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4484 little_endian = 1;
4485 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4486 little_endian = 0;
4487 else {
4488 PyErr_SetString(PyExc_ValueError,
4489 "byteorder must be either 'little' or 'big'");
4490 return NULL;
4491 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 if (is_signed_obj != NULL) {
4494 int cmp = PyObject_IsTrue(is_signed_obj);
4495 if (cmp < 0)
4496 return NULL;
4497 is_signed = cmp ? 1 : 0;
4498 }
4499 else {
4500 /* If the signed argument was omitted, use False as the
4501 default. */
4502 is_signed = 0;
4503 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 if (length < 0) {
4506 PyErr_SetString(PyExc_ValueError,
4507 "length argument must be non-negative");
4508 return NULL;
4509 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 bytes = PyBytes_FromStringAndSize(NULL, length);
4512 if (bytes == NULL)
4513 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4516 length, little_endian, is_signed) < 0) {
4517 Py_DECREF(bytes);
4518 return NULL;
4519 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004522}
4523
Mark Dickinson078c2532010-01-30 18:06:17 +00004524PyDoc_STRVAR(long_to_bytes_doc,
4525"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004526\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004527Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004528\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004530raised if the integer is not representable with the given number of\n\
4531bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004532\n\
4533The byteorder argument determines the byte order used to represent the\n\
4534integer. If byteorder is 'big', the most significant byte is at the\n\
4535beginning of the byte array. If byteorder is 'little', the most\n\
4536significant byte is at the end of the byte array. To request the native\n\
4537byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4538\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004539The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004541is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004542
4543static PyObject *
4544long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004546 PyObject *byteorder_str;
4547 PyObject *is_signed_obj = NULL;
4548 int little_endian;
4549 int is_signed;
4550 PyObject *obj;
4551 PyObject *bytes;
4552 PyObject *long_obj;
4553 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4556 &obj, &byteorder_str,
4557 &is_signed_obj))
4558 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004560 if (args != NULL && Py_SIZE(args) > 2) {
4561 PyErr_SetString(PyExc_TypeError,
4562 "'signed' is a keyword-only argument");
4563 return NULL;
4564 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4567 little_endian = 1;
4568 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4569 little_endian = 0;
4570 else {
4571 PyErr_SetString(PyExc_ValueError,
4572 "byteorder must be either 'little' or 'big'");
4573 return NULL;
4574 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 if (is_signed_obj != NULL) {
4577 int cmp = PyObject_IsTrue(is_signed_obj);
4578 if (cmp < 0)
4579 return NULL;
4580 is_signed = cmp ? 1 : 0;
4581 }
4582 else {
4583 /* If the signed argument was omitted, use False as the
4584 default. */
4585 is_signed = 0;
4586 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 bytes = PyObject_Bytes(obj);
4589 if (bytes == NULL)
4590 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 long_obj = _PyLong_FromByteArray(
4593 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4594 little_endian, is_signed);
4595 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 /* If from_bytes() was used on subclass, allocate new subclass
4598 * instance, initialize it with decoded long value and return it.
4599 */
4600 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4601 PyLongObject *newobj;
4602 int i;
4603 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 newobj = (PyLongObject *)type->tp_alloc(type, n);
4606 if (newobj == NULL) {
4607 Py_DECREF(long_obj);
4608 return NULL;
4609 }
4610 assert(PyLong_Check(newobj));
4611 Py_SIZE(newobj) = Py_SIZE(long_obj);
4612 for (i = 0; i < n; i++) {
4613 newobj->ob_digit[i] =
4614 ((PyLongObject *)long_obj)->ob_digit[i];
4615 }
4616 Py_DECREF(long_obj);
4617 return (PyObject *)newobj;
4618 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004621}
4622
Mark Dickinson078c2532010-01-30 18:06:17 +00004623PyDoc_STRVAR(long_from_bytes_doc,
4624"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4625\n\
4626Return the integer represented by the given array of bytes.\n\
4627\n\
4628The bytes argument must either support the buffer protocol or be an\n\
4629iterable object producing bytes. Bytes and bytearray are examples of\n\
4630built-in objects that support the buffer protocol.\n\
4631\n\
4632The byteorder argument determines the byte order used to represent the\n\
4633integer. If byteorder is 'big', the most significant byte is at the\n\
4634beginning of the byte array. If byteorder is 'little', the most\n\
4635significant byte is at the end of the byte array. To request the native\n\
4636byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4637\n\
4638The signed keyword-only argument indicates whether two's complement is\n\
4639used to represent the integer.");
4640
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004641static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4643 "Returns self, the complex conjugate of any int."},
4644 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4645 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004646#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4648 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004649#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 {"to_bytes", (PyCFunction)long_to_bytes,
4651 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4652 {"from_bytes", (PyCFunction)long_from_bytes,
4653 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4654 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4655 "Truncating an Integral returns itself."},
4656 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4657 "Flooring an Integral returns itself."},
4658 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4659 "Ceiling of an Integral returns itself."},
4660 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4661 "Rounding an Integral returns itself.\n"
4662 "Rounding with an ndigits argument also returns an integer."},
4663 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4664 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4665 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4666 "Returns size in memory, in bytes"},
4667 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004668};
4669
Guido van Rossumb43daf72007-08-01 18:08:08 +00004670static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004671 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004672 (getter)long_long, (setter)NULL,
4673 "the real part of a complex number",
4674 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004675 {"imag",
4676 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004677 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004678 NULL},
4679 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004680 (getter)long_long, (setter)NULL,
4681 "the numerator of a rational number in lowest terms",
4682 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004683 {"denominator",
4684 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004685 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004686 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004687 {NULL} /* Sentinel */
4688};
4689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004690PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004691"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004692\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004693Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004694point argument will be truncated towards zero (this does not include a\n\
4695string representation of a floating point number!) When converting a\n\
4696string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004697converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004698
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004699static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004700 (binaryfunc)long_add, /*nb_add*/
4701 (binaryfunc)long_sub, /*nb_subtract*/
4702 (binaryfunc)long_mul, /*nb_multiply*/
4703 long_mod, /*nb_remainder*/
4704 long_divmod, /*nb_divmod*/
4705 long_pow, /*nb_power*/
4706 (unaryfunc)long_neg, /*nb_negative*/
4707 (unaryfunc)long_long, /*tp_positive*/
4708 (unaryfunc)long_abs, /*tp_absolute*/
4709 (inquiry)long_bool, /*tp_bool*/
4710 (unaryfunc)long_invert, /*nb_invert*/
4711 long_lshift, /*nb_lshift*/
4712 (binaryfunc)long_rshift, /*nb_rshift*/
4713 long_and, /*nb_and*/
4714 long_xor, /*nb_xor*/
4715 long_or, /*nb_or*/
4716 long_long, /*nb_int*/
4717 0, /*nb_reserved*/
4718 long_float, /*nb_float*/
4719 0, /* nb_inplace_add */
4720 0, /* nb_inplace_subtract */
4721 0, /* nb_inplace_multiply */
4722 0, /* nb_inplace_remainder */
4723 0, /* nb_inplace_power */
4724 0, /* nb_inplace_lshift */
4725 0, /* nb_inplace_rshift */
4726 0, /* nb_inplace_and */
4727 0, /* nb_inplace_xor */
4728 0, /* nb_inplace_or */
4729 long_div, /* nb_floor_divide */
4730 long_true_divide, /* nb_true_divide */
4731 0, /* nb_inplace_floor_divide */
4732 0, /* nb_inplace_true_divide */
4733 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004734};
4735
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004736PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4738 "int", /* tp_name */
4739 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4740 sizeof(digit), /* tp_itemsize */
4741 long_dealloc, /* tp_dealloc */
4742 0, /* tp_print */
4743 0, /* tp_getattr */
4744 0, /* tp_setattr */
4745 0, /* tp_reserved */
4746 long_to_decimal_string, /* tp_repr */
4747 &long_as_number, /* tp_as_number */
4748 0, /* tp_as_sequence */
4749 0, /* tp_as_mapping */
4750 (hashfunc)long_hash, /* tp_hash */
4751 0, /* tp_call */
4752 long_to_decimal_string, /* tp_str */
4753 PyObject_GenericGetAttr, /* tp_getattro */
4754 0, /* tp_setattro */
4755 0, /* tp_as_buffer */
4756 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4757 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4758 long_doc, /* tp_doc */
4759 0, /* tp_traverse */
4760 0, /* tp_clear */
4761 long_richcompare, /* tp_richcompare */
4762 0, /* tp_weaklistoffset */
4763 0, /* tp_iter */
4764 0, /* tp_iternext */
4765 long_methods, /* tp_methods */
4766 0, /* tp_members */
4767 long_getset, /* tp_getset */
4768 0, /* tp_base */
4769 0, /* tp_dict */
4770 0, /* tp_descr_get */
4771 0, /* tp_descr_set */
4772 0, /* tp_dictoffset */
4773 0, /* tp_init */
4774 0, /* tp_alloc */
4775 long_new, /* tp_new */
4776 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004777};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004778
Mark Dickinsonbd792642009-03-18 20:06:12 +00004779static PyTypeObject Int_InfoType;
4780
4781PyDoc_STRVAR(int_info__doc__,
4782"sys.int_info\n\
4783\n\
4784A struct sequence that holds information about Python's\n\
4785internal representation of integers. The attributes are read only.");
4786
4787static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004789 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004790 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004791};
4792
4793static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 "sys.int_info", /* name */
4795 int_info__doc__, /* doc */
4796 int_info_fields, /* fields */
4797 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004798};
4799
4800PyObject *
4801PyLong_GetInfo(void)
4802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 PyObject* int_info;
4804 int field = 0;
4805 int_info = PyStructSequence_New(&Int_InfoType);
4806 if (int_info == NULL)
4807 return NULL;
4808 PyStructSequence_SET_ITEM(int_info, field++,
4809 PyLong_FromLong(PyLong_SHIFT));
4810 PyStructSequence_SET_ITEM(int_info, field++,
4811 PyLong_FromLong(sizeof(digit)));
4812 if (PyErr_Occurred()) {
4813 Py_CLEAR(int_info);
4814 return NULL;
4815 }
4816 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004817}
4818
Guido van Rossumddefaf32007-01-14 03:31:43 +00004819int
4820_PyLong_Init(void)
4821{
4822#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 int ival, size;
4824 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4827 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4828 if (Py_TYPE(v) == &PyLong_Type) {
4829 /* The element is already initialized, most likely
4830 * the Python interpreter was initialized before.
4831 */
4832 Py_ssize_t refcnt;
4833 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4836 _Py_NewReference(op);
4837 /* _Py_NewReference sets the ref count to 1 but
4838 * the ref count might be larger. Set the refcnt
4839 * to the original refcnt + 1 */
4840 Py_REFCNT(op) = refcnt + 1;
4841 assert(Py_SIZE(op) == size);
4842 assert(v->ob_digit[0] == abs(ival));
4843 }
4844 else {
4845 PyObject_INIT(v, &PyLong_Type);
4846 }
4847 Py_SIZE(v) = size;
4848 v->ob_digit[0] = abs(ival);
4849 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004850#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 /* initialize int_info */
4852 if (Int_InfoType.tp_name == 0)
4853 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004856}
4857
4858void
4859PyLong_Fini(void)
4860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 /* Integers are currently statically allocated. Py_DECREF is not
4862 needed, but Python must forget about the reference or multiple
4863 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004864#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 int i;
4866 PyLongObject *v = small_ints;
4867 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4868 _Py_DEC_REFTOTAL;
4869 _Py_ForgetReference((PyObject*)v);
4870 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004871#endif
4872}