blob: c9c9817f12300fdeaf08fa376c0bf02a72d8326c [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Mark Dickinsonbd792642009-03-18 20:06:12 +00007#include "structseq.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00008
Mark Dickinsonc6300392009-04-20 21:38:00 +00009#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +000010#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000011#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000012
Guido van Rossumddefaf32007-01-14 03:31:43 +000013#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000014#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000015#endif
16#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000019
Mark Dickinsone4416742009-02-15 15:14:57 +000020/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
22 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
34int quick_int_allocs, quick_neg_int_allocs;
35#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000042#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
50#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
52 return get_small_int((sdigit)ival); \
53 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000056maybe_small_long(PyLongObject *v)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (v && ABS(Py_SIZE(v)) <= 1) {
59 sdigit ival = MEDIUM_VALUE(v);
60 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Guido van Rossumddefaf32007-01-14 03:31:43 +000072/* If a freshly-allocated long is already shared, it must
73 be a small integer, so negating it must go to PyLong_FromLong */
74#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
76 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
77 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
78 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000079/* For long multiplication, use the O(N**2) school algorithm unless
80 * both operands contain more than KARATSUBA_CUTOFF digits (this
81 * being an internal Python long digit, in base BASE).
82 */
Tim Peters0973b992004-08-29 22:16:50 +000083#define KARATSUBA_CUTOFF 70
84#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000085
Tim Peters47e52ee2004-08-30 02:44:38 +000086/* For exponentiation, use the binary left-to-right algorithm
87 * unless the exponent contains more than FIVEARY_CUTOFF digits.
88 * In that case, do 5 bits at a time. The potential drawback is that
89 * a table of 2**5 intermediate results is computed.
90 */
91#define FIVEARY_CUTOFF 8
92
Tim Peters5af4e6c2002-08-12 02:31:19 +000093#undef MIN
94#undef MAX
95#define MAX(x, y) ((x) < (y) ? (y) : (x))
96#define MIN(x, y) ((x) > (y) ? (y) : (x))
97
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000098#define SIGCHECK(PyTryBlock) \
99 do { \
100 if (PyErr_CheckSignals()) PyTryBlock \
101 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000102
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000103/* Normalize (remove leading zeros from) a long int object.
104 Doesn't attempt to free the storage--in most cases, due to the nature
105 of the algorithms used, this could save at most be one word anyway. */
106
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000107static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000108long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 Py_ssize_t j = ABS(Py_SIZE(v));
111 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 while (i > 0 && v->ob_digit[i-1] == 0)
114 --i;
115 if (i != j)
116 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
117 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000118}
119
120/* Allocate a new long int object with size digits.
121 Return NULL and set exception if we run out of memory. */
122
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000123#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000125
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000127_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyLongObject *result;
130 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
131 sizeof(digit)*size. Previous incarnations of this code used
132 sizeof(PyVarObject) instead of the offsetof, but this risks being
133 incorrect in the presence of padding between the PyVarObject header
134 and the digits. */
135 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
136 PyErr_SetString(PyExc_OverflowError,
137 "too many digits in integer");
138 return NULL;
139 }
140 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
141 size*sizeof(digit));
142 if (!result) {
143 PyErr_NoMemory();
144 return NULL;
145 }
146 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000147}
148
Tim Peters64b5ce32001-09-10 20:52:51 +0000149PyObject *
150_PyLong_Copy(PyLongObject *src)
151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 PyLongObject *result;
153 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 assert(src != NULL);
156 i = Py_SIZE(src);
157 if (i < 0)
158 i = -(i);
159 if (i < 2) {
160 sdigit ival = src->ob_digit[0];
161 if (Py_SIZE(src) < 0)
162 ival = -ival;
163 CHECK_SMALL_INT(ival);
164 }
165 result = _PyLong_New(i);
166 if (result != NULL) {
167 Py_SIZE(result) = Py_SIZE(src);
168 while (--i >= 0)
169 result->ob_digit[i] = src->ob_digit[i];
170 }
171 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000172}
173
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000174/* Create a new long int object from a C long int */
175
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000177PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 PyLongObject *v;
180 unsigned long abs_ival;
181 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
182 int ndigits = 0;
183 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (ival < 0) {
188 /* negate: can't write this as abs_ival = -ival since that
189 invokes undefined behaviour when ival is LONG_MIN */
190 abs_ival = 0U-(unsigned long)ival;
191 sign = -1;
192 }
193 else {
194 abs_ival = (unsigned long)ival;
195 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 /* Fast path for single-digit ints */
198 if (!(abs_ival >> PyLong_SHIFT)) {
199 v = _PyLong_New(1);
200 if (v) {
201 Py_SIZE(v) = sign;
202 v->ob_digit[0] = Py_SAFE_DOWNCAST(
203 abs_ival, unsigned long, digit);
204 }
205 return (PyObject*)v;
206 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000207
Mark Dickinson249b8982009-04-27 19:41:00 +0000208#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 /* 2 digits */
210 if (!(abs_ival >> 2*PyLong_SHIFT)) {
211 v = _PyLong_New(2);
212 if (v) {
213 Py_SIZE(v) = 2*sign;
214 v->ob_digit[0] = Py_SAFE_DOWNCAST(
215 abs_ival & PyLong_MASK, unsigned long, digit);
216 v->ob_digit[1] = Py_SAFE_DOWNCAST(
217 abs_ival >> PyLong_SHIFT, unsigned long, digit);
218 }
219 return (PyObject*)v;
220 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000221#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 /* Larger numbers: loop to determine number of digits */
224 t = abs_ival;
225 while (t) {
226 ++ndigits;
227 t >>= PyLong_SHIFT;
228 }
229 v = _PyLong_New(ndigits);
230 if (v != NULL) {
231 digit *p = v->ob_digit;
232 Py_SIZE(v) = ndigits*sign;
233 t = abs_ival;
234 while (t) {
235 *p++ = Py_SAFE_DOWNCAST(
236 t & PyLong_MASK, unsigned long, digit);
237 t >>= PyLong_SHIFT;
238 }
239 }
240 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241}
242
Guido van Rossum53756b11997-01-03 17:14:46 +0000243/* Create a new long int object from a C unsigned long int */
244
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000246PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyLongObject *v;
249 unsigned long t;
250 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (ival < PyLong_BASE)
253 return PyLong_FromLong(ival);
254 /* Count the number of Python digits. */
255 t = (unsigned long)ival;
256 while (t) {
257 ++ndigits;
258 t >>= PyLong_SHIFT;
259 }
260 v = _PyLong_New(ndigits);
261 if (v != NULL) {
262 digit *p = v->ob_digit;
263 Py_SIZE(v) = ndigits;
264 while (ival) {
265 *p++ = (digit)(ival & PyLong_MASK);
266 ival >>= PyLong_SHIFT;
267 }
268 }
269 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000270}
271
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000272/* Create a new long int object from a C double */
273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 PyLongObject *v;
278 double frac;
279 int i, ndig, expo, neg;
280 neg = 0;
281 if (Py_IS_INFINITY(dval)) {
282 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000283 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return NULL;
285 }
286 if (Py_IS_NAN(dval)) {
287 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000288 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 return NULL;
290 }
291 if (dval < 0.0) {
292 neg = 1;
293 dval = -dval;
294 }
295 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
296 if (expo <= 0)
297 return PyLong_FromLong(0L);
298 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
299 v = _PyLong_New(ndig);
300 if (v == NULL)
301 return NULL;
302 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
303 for (i = ndig; --i >= 0; ) {
304 digit bits = (digit)frac;
305 v->ob_digit[i] = bits;
306 frac = frac - (double)bits;
307 frac = ldexp(frac, PyLong_SHIFT);
308 }
309 if (neg)
310 Py_SIZE(v) = -(Py_SIZE(v));
311 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000312}
313
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
315 * anything about what happens when a signed integer operation overflows,
316 * and some compilers think they're doing you a favor by being "clever"
317 * then. The bit pattern for the largest postive signed long is
318 * (unsigned long)LONG_MAX, and for the smallest negative signed long
319 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
320 * However, some other compilers warn about applying unary minus to an
321 * unsigned operand. Hence the weird "0-".
322 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
324#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000326/* Get a C long int from a long int object.
327 Returns -1 and sets an error condition if overflow occurs. */
328
329long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000330PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* This version by Tim Peters */
333 register PyLongObject *v;
334 unsigned long x, prev;
335 long res;
336 Py_ssize_t i;
337 int sign;
338 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 *overflow = 0;
341 if (vv == NULL) {
342 PyErr_BadInternalCall();
343 return -1;
344 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (!PyLong_Check(vv)) {
347 PyNumberMethods *nb;
348 nb = vv->ob_type->tp_as_number;
349 if (nb == NULL || nb->nb_int == NULL) {
350 PyErr_SetString(PyExc_TypeError,
351 "an integer is required");
352 return -1;
353 }
354 vv = (*nb->nb_int) (vv);
355 if (vv == NULL)
356 return -1;
357 do_decref = 1;
358 if (!PyLong_Check(vv)) {
359 Py_DECREF(vv);
360 PyErr_SetString(PyExc_TypeError,
361 "nb_int should return int object");
362 return -1;
363 }
364 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 res = -1;
367 v = (PyLongObject *)vv;
368 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 switch (i) {
371 case -1:
372 res = -(sdigit)v->ob_digit[0];
373 break;
374 case 0:
375 res = 0;
376 break;
377 case 1:
378 res = v->ob_digit[0];
379 break;
380 default:
381 sign = 1;
382 x = 0;
383 if (i < 0) {
384 sign = -1;
385 i = -(i);
386 }
387 while (--i >= 0) {
388 prev = x;
389 x = (x << PyLong_SHIFT) | v->ob_digit[i];
390 if ((x >> PyLong_SHIFT) != prev) {
391 *overflow = sign;
392 goto exit;
393 }
394 }
395 /* Haven't lost any bits, but casting to long requires extra
396 * care (see comment above).
397 */
398 if (x <= (unsigned long)LONG_MAX) {
399 res = (long)x * sign;
400 }
401 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
402 res = LONG_MIN;
403 }
404 else {
405 *overflow = sign;
406 /* res is already set to -1 */
407 }
408 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000409 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (do_decref) {
411 Py_DECREF(vv);
412 }
413 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000414}
415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000417PyLong_AsLong(PyObject *obj)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 int overflow;
420 long result = PyLong_AsLongAndOverflow(obj, &overflow);
421 if (overflow) {
422 /* XXX: could be cute and give a different
423 message for overflow == -1 */
424 PyErr_SetString(PyExc_OverflowError,
425 "Python int too large to convert to C long");
426 }
427 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000428}
429
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000430/* Get a Py_ssize_t from a long int object.
431 Returns -1 and sets an error condition if overflow occurs. */
432
433Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000434PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 register PyLongObject *v;
436 size_t x, prev;
437 Py_ssize_t i;
438 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (vv == NULL) {
441 PyErr_BadInternalCall();
442 return -1;
443 }
444 if (!PyLong_Check(vv)) {
445 PyErr_SetString(PyExc_TypeError, "an integer is required");
446 return -1;
447 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 v = (PyLongObject *)vv;
450 i = Py_SIZE(v);
451 switch (i) {
452 case -1: return -(sdigit)v->ob_digit[0];
453 case 0: return 0;
454 case 1: return v->ob_digit[0];
455 }
456 sign = 1;
457 x = 0;
458 if (i < 0) {
459 sign = -1;
460 i = -(i);
461 }
462 while (--i >= 0) {
463 prev = x;
464 x = (x << PyLong_SHIFT) | v->ob_digit[i];
465 if ((x >> PyLong_SHIFT) != prev)
466 goto overflow;
467 }
468 /* Haven't lost any bits, but casting to a signed type requires
469 * extra care (see comment above).
470 */
471 if (x <= (size_t)PY_SSIZE_T_MAX) {
472 return (Py_ssize_t)x * sign;
473 }
474 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
475 return PY_SSIZE_T_MIN;
476 }
477 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000478
Mark Dickinson22b20182010-05-10 21:27:53 +0000479 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyErr_SetString(PyExc_OverflowError,
481 "Python int too large to convert to C ssize_t");
482 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000483}
484
Guido van Rossumd8c80482002-08-13 00:24:58 +0000485/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000486 Returns -1 and sets an error condition if overflow occurs. */
487
488unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000489PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 register PyLongObject *v;
492 unsigned long x, prev;
493 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (vv == NULL) {
496 PyErr_BadInternalCall();
497 return (unsigned long)-1;
498 }
499 if (!PyLong_Check(vv)) {
500 PyErr_SetString(PyExc_TypeError, "an integer is required");
501 return (unsigned long)-1;
502 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 v = (PyLongObject *)vv;
505 i = Py_SIZE(v);
506 x = 0;
507 if (i < 0) {
508 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000509 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return (unsigned long) -1;
511 }
512 switch (i) {
513 case 0: return 0;
514 case 1: return v->ob_digit[0];
515 }
516 while (--i >= 0) {
517 prev = x;
518 x = (x << PyLong_SHIFT) | v->ob_digit[i];
519 if ((x >> PyLong_SHIFT) != prev) {
520 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000521 "python int too large to convert "
522 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return (unsigned long) -1;
524 }
525 }
526 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000527}
528
529/* Get a C unsigned long int from a long int object.
530 Returns -1 and sets an error condition if overflow occurs. */
531
532size_t
533PyLong_AsSize_t(PyObject *vv)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 register PyLongObject *v;
536 size_t x, prev;
537 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (vv == NULL) {
540 PyErr_BadInternalCall();
541 return (size_t) -1;
542 }
543 if (!PyLong_Check(vv)) {
544 PyErr_SetString(PyExc_TypeError, "an integer is required");
545 return (size_t)-1;
546 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 v = (PyLongObject *)vv;
549 i = Py_SIZE(v);
550 x = 0;
551 if (i < 0) {
552 PyErr_SetString(PyExc_OverflowError,
553 "can't convert negative value to size_t");
554 return (size_t) -1;
555 }
556 switch (i) {
557 case 0: return 0;
558 case 1: return v->ob_digit[0];
559 }
560 while (--i >= 0) {
561 prev = x;
562 x = (x << PyLong_SHIFT) | v->ob_digit[i];
563 if ((x >> PyLong_SHIFT) != prev) {
564 PyErr_SetString(PyExc_OverflowError,
565 "Python int too large to convert to C size_t");
566 return (unsigned long) -1;
567 }
568 }
569 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000570}
571
Thomas Hellera4ea6032003-04-17 18:55:45 +0000572/* Get a C unsigned long int from a long int object, ignoring the high bits.
573 Returns -1 and sets an error condition if an error occurs. */
574
Guido van Rossumddefaf32007-01-14 03:31:43 +0000575static unsigned long
576_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 register PyLongObject *v;
579 unsigned long x;
580 Py_ssize_t i;
581 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (vv == NULL || !PyLong_Check(vv)) {
584 PyErr_BadInternalCall();
585 return (unsigned long) -1;
586 }
587 v = (PyLongObject *)vv;
588 i = Py_SIZE(v);
589 switch (i) {
590 case 0: return 0;
591 case 1: return v->ob_digit[0];
592 }
593 sign = 1;
594 x = 0;
595 if (i < 0) {
596 sign = -1;
597 i = -i;
598 }
599 while (--i >= 0) {
600 x = (x << PyLong_SHIFT) | v->ob_digit[i];
601 }
602 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000603}
604
Guido van Rossumddefaf32007-01-14 03:31:43 +0000605unsigned long
606PyLong_AsUnsignedLongMask(register PyObject *op)
607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyNumberMethods *nb;
609 PyLongObject *lo;
610 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (op && PyLong_Check(op))
613 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
616 nb->nb_int == NULL) {
617 PyErr_SetString(PyExc_TypeError, "an integer is required");
618 return (unsigned long)-1;
619 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 lo = (PyLongObject*) (*nb->nb_int) (op);
622 if (lo == NULL)
623 return (unsigned long)-1;
624 if (PyLong_Check(lo)) {
625 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
626 Py_DECREF(lo);
627 if (PyErr_Occurred())
628 return (unsigned long)-1;
629 return val;
630 }
631 else
632 {
633 Py_DECREF(lo);
634 PyErr_SetString(PyExc_TypeError,
635 "nb_int should return int object");
636 return (unsigned long)-1;
637 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000638}
639
Tim Peters5b8132f2003-01-31 15:52:05 +0000640int
641_PyLong_Sign(PyObject *vv)
642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 assert(v != NULL);
646 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000649}
650
Tim Petersbaefd9e2003-01-28 20:37:45 +0000651size_t
652_PyLong_NumBits(PyObject *vv)
653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyLongObject *v = (PyLongObject *)vv;
655 size_t result = 0;
656 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 assert(v != NULL);
659 assert(PyLong_Check(v));
660 ndigits = ABS(Py_SIZE(v));
661 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
662 if (ndigits > 0) {
663 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 result = (ndigits - 1) * PyLong_SHIFT;
666 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
667 goto Overflow;
668 do {
669 ++result;
670 if (result == 0)
671 goto Overflow;
672 msd >>= 1;
673 } while (msd);
674 }
675 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000676
Mark Dickinson22b20182010-05-10 21:27:53 +0000677 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
679 "to express in a platform size_t");
680 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000681}
682
Tim Peters2a9b3672001-06-11 21:23:58 +0000683PyObject *
684_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000686{
Mark Dickinson22b20182010-05-10 21:27:53 +0000687 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 int incr; /* direction to move pstartbyte */
689 const unsigned char* pendbyte; /* MSB of bytes */
690 size_t numsignificantbytes; /* number of bytes that matter */
691 Py_ssize_t ndigits; /* number of Python long digits */
692 PyLongObject* v; /* result */
693 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (n == 0)
696 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (little_endian) {
699 pstartbyte = bytes;
700 pendbyte = bytes + n - 1;
701 incr = 1;
702 }
703 else {
704 pstartbyte = bytes + n - 1;
705 pendbyte = bytes;
706 incr = -1;
707 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (is_signed)
710 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Compute numsignificantbytes. This consists of finding the most
713 significant byte. Leading 0 bytes are insignficant if the number
714 is positive, and leading 0xff bytes if negative. */
715 {
716 size_t i;
717 const unsigned char* p = pendbyte;
718 const int pincr = -incr; /* search MSB to LSB */
719 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 for (i = 0; i < n; ++i, p += pincr) {
722 if (*p != insignficant)
723 break;
724 }
725 numsignificantbytes = n - i;
726 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
727 actually has 2 significant bytes. OTOH, 0xff0001 ==
728 -0x00ffff, so we wouldn't *need* to bump it there; but we
729 do for 0xffff = -0x0001. To be safe without bothering to
730 check every case, bump it regardless. */
731 if (is_signed && numsignificantbytes < n)
732 ++numsignificantbytes;
733 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 /* How many Python long digits do we need? We have
736 8*numsignificantbytes bits, and each Python long digit has
737 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
738 /* catch overflow before it happens */
739 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
740 PyErr_SetString(PyExc_OverflowError,
741 "byte array too long to convert to int");
742 return NULL;
743 }
744 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
745 v = _PyLong_New(ndigits);
746 if (v == NULL)
747 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 /* Copy the bits over. The tricky parts are computing 2's-comp on
750 the fly for signed numbers, and dealing with the mismatch between
751 8-bit bytes and (probably) 15-bit Python digits.*/
752 {
753 size_t i;
754 twodigits carry = 1; /* for 2's-comp calculation */
755 twodigits accum = 0; /* sliding register */
756 unsigned int accumbits = 0; /* number of bits in accum */
757 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
760 twodigits thisbyte = *p;
761 /* Compute correction for 2's comp, if needed. */
762 if (is_signed) {
763 thisbyte = (0xff ^ thisbyte) + carry;
764 carry = thisbyte >> 8;
765 thisbyte &= 0xff;
766 }
767 /* Because we're going LSB to MSB, thisbyte is
768 more significant than what's already in accum,
769 so needs to be prepended to accum. */
770 accum |= (twodigits)thisbyte << accumbits;
771 accumbits += 8;
772 if (accumbits >= PyLong_SHIFT) {
773 /* There's enough to fill a Python digit. */
774 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000775 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 ++idigit;
777 accum >>= PyLong_SHIFT;
778 accumbits -= PyLong_SHIFT;
779 assert(accumbits < PyLong_SHIFT);
780 }
781 }
782 assert(accumbits < PyLong_SHIFT);
783 if (accumbits) {
784 assert(idigit < ndigits);
785 v->ob_digit[idigit] = (digit)accum;
786 ++idigit;
787 }
788 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_SIZE(v) = is_signed ? -idigit : idigit;
791 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000792}
793
794int
795_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 unsigned char* bytes, size_t n,
797 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000800 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000802 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
804 digit carry; /* for computing 2's-comp */
805 size_t j; /* # bytes filled */
806 unsigned char* p; /* pointer to next byte in bytes */
807 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (Py_SIZE(v) < 0) {
812 ndigits = -(Py_SIZE(v));
813 if (!is_signed) {
814 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000815 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 return -1;
817 }
818 do_twos_comp = 1;
819 }
820 else {
821 ndigits = Py_SIZE(v);
822 do_twos_comp = 0;
823 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 if (little_endian) {
826 p = bytes;
827 pincr = 1;
828 }
829 else {
830 p = bytes + n - 1;
831 pincr = -1;
832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* Copy over all the Python digits.
835 It's crucial that every Python digit except for the MSD contribute
836 exactly PyLong_SHIFT bits to the total, so first assert that the long is
837 normalized. */
838 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
839 j = 0;
840 accum = 0;
841 accumbits = 0;
842 carry = do_twos_comp ? 1 : 0;
843 for (i = 0; i < ndigits; ++i) {
844 digit thisdigit = v->ob_digit[i];
845 if (do_twos_comp) {
846 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
847 carry = thisdigit >> PyLong_SHIFT;
848 thisdigit &= PyLong_MASK;
849 }
850 /* Because we're going LSB to MSB, thisdigit is more
851 significant than what's already in accum, so needs to be
852 prepended to accum. */
853 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 /* The most-significant digit may be (probably is) at least
856 partly empty. */
857 if (i == ndigits - 1) {
858 /* Count # of sign bits -- they needn't be stored,
859 * although for signed conversion we need later to
860 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000861 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 while (s != 0) {
863 s >>= 1;
864 accumbits++;
865 }
866 }
867 else
868 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 /* Store as many bytes as possible. */
871 while (accumbits >= 8) {
872 if (j >= n)
873 goto Overflow;
874 ++j;
875 *p = (unsigned char)(accum & 0xff);
876 p += pincr;
877 accumbits -= 8;
878 accum >>= 8;
879 }
880 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Store the straggler (if any). */
883 assert(accumbits < 8);
884 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
885 if (accumbits > 0) {
886 if (j >= n)
887 goto Overflow;
888 ++j;
889 if (do_twos_comp) {
890 /* Fill leading bits of the byte with sign bits
891 (appropriately pretending that the long had an
892 infinite supply of sign bits). */
893 accum |= (~(twodigits)0) << accumbits;
894 }
895 *p = (unsigned char)(accum & 0xff);
896 p += pincr;
897 }
898 else if (j == n && n > 0 && is_signed) {
899 /* The main loop filled the byte array exactly, so the code
900 just above didn't get to ensure there's a sign bit, and the
901 loop below wouldn't add one either. Make sure a sign bit
902 exists. */
903 unsigned char msb = *(p - pincr);
904 int sign_bit_set = msb >= 0x80;
905 assert(accumbits == 0);
906 if (sign_bit_set == do_twos_comp)
907 return 0;
908 else
909 goto Overflow;
910 }
Tim Peters05607ad2001-06-13 21:01:27 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Fill remaining bytes with copies of the sign bit. */
913 {
914 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
915 for ( ; j < n; ++j, p += pincr)
916 *p = signbyte;
917 }
Tim Peters05607ad2001-06-13 21:01:27 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000920
Mark Dickinson22b20182010-05-10 21:27:53 +0000921 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
923 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000924
Tim Peters2a9b3672001-06-11 21:23:58 +0000925}
926
Guido van Rossum78694d91998-09-18 14:14:13 +0000927/* Create a new long (or int) object from a C pointer */
928
929PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000930PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000931{
Tim Peters70128a12001-06-16 08:48:40 +0000932#ifndef HAVE_LONG_LONG
933# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
934#endif
935#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000936# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000937#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* special-case null pointer */
939 if (!p)
940 return PyLong_FromLong(0);
941 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000942
Guido van Rossum78694d91998-09-18 14:14:13 +0000943}
944
945/* Get a C pointer from a long object (or an int object in some cases) */
946
947void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000948PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* This function will allow int or long objects. If vv is neither,
951 then the PyLong_AsLong*() functions will raise the exception:
952 PyExc_SystemError, "bad argument to internal function"
953 */
Tim Peters70128a12001-06-16 08:48:40 +0000954#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
958 x = PyLong_AsLong(vv);
959 else
960 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000961#else
Tim Peters70128a12001-06-16 08:48:40 +0000962
963#ifndef HAVE_LONG_LONG
964# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
965#endif
966#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000968#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
972 x = PyLong_AsLongLong(vv);
973 else
974 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000975
976#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (x == -1 && PyErr_Occurred())
979 return NULL;
980 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000981}
982
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000983#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000984
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000985/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000986 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000987 */
988
Tim Peterscf37dfc2001-06-14 18:42:50 +0000989#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000990#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000991
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000992/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000993
994PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyLongObject *v;
998 unsigned PY_LONG_LONG abs_ival;
999 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1000 int ndigits = 0;
1001 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 CHECK_SMALL_INT(ival);
1004 if (ival < 0) {
1005 /* avoid signed overflow on negation; see comments
1006 in PyLong_FromLong above. */
1007 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1008 negative = 1;
1009 }
1010 else {
1011 abs_ival = (unsigned PY_LONG_LONG)ival;
1012 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 /* Count the number of Python digits.
1015 We used to pick 5 ("big enough for anything"), but that's a
1016 waste of time and space given that 5*15 = 75 bits are rarely
1017 needed. */
1018 t = abs_ival;
1019 while (t) {
1020 ++ndigits;
1021 t >>= PyLong_SHIFT;
1022 }
1023 v = _PyLong_New(ndigits);
1024 if (v != NULL) {
1025 digit *p = v->ob_digit;
1026 Py_SIZE(v) = negative ? -ndigits : ndigits;
1027 t = abs_ival;
1028 while (t) {
1029 *p++ = (digit)(t & PyLong_MASK);
1030 t >>= PyLong_SHIFT;
1031 }
1032 }
1033 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034}
1035
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001036/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001037
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001038PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001039PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyLongObject *v;
1042 unsigned PY_LONG_LONG t;
1043 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 if (ival < PyLong_BASE)
1046 return PyLong_FromLong((long)ival);
1047 /* Count the number of Python digits. */
1048 t = (unsigned PY_LONG_LONG)ival;
1049 while (t) {
1050 ++ndigits;
1051 t >>= PyLong_SHIFT;
1052 }
1053 v = _PyLong_New(ndigits);
1054 if (v != NULL) {
1055 digit *p = v->ob_digit;
1056 Py_SIZE(v) = ndigits;
1057 while (ival) {
1058 *p++ = (digit)(ival & PyLong_MASK);
1059 ival >>= PyLong_SHIFT;
1060 }
1061 }
1062 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001063}
1064
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065/* Create a new long int object from a C Py_ssize_t. */
1066
1067PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001068PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyLongObject *v;
1071 size_t abs_ival;
1072 size_t t; /* unsigned so >> doesn't propagate sign bit */
1073 int ndigits = 0;
1074 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 CHECK_SMALL_INT(ival);
1077 if (ival < 0) {
1078 /* avoid signed overflow when ival = SIZE_T_MIN */
1079 abs_ival = (size_t)(-1-ival)+1;
1080 negative = 1;
1081 }
1082 else {
1083 abs_ival = (size_t)ival;
1084 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 /* Count the number of Python digits. */
1087 t = abs_ival;
1088 while (t) {
1089 ++ndigits;
1090 t >>= PyLong_SHIFT;
1091 }
1092 v = _PyLong_New(ndigits);
1093 if (v != NULL) {
1094 digit *p = v->ob_digit;
1095 Py_SIZE(v) = negative ? -ndigits : ndigits;
1096 t = abs_ival;
1097 while (t) {
1098 *p++ = (digit)(t & PyLong_MASK);
1099 t >>= PyLong_SHIFT;
1100 }
1101 }
1102 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103}
1104
1105/* Create a new long int object from a C size_t. */
1106
1107PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001108PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 PyLongObject *v;
1111 size_t t;
1112 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (ival < PyLong_BASE)
1115 return PyLong_FromLong((long)ival);
1116 /* Count the number of Python digits. */
1117 t = ival;
1118 while (t) {
1119 ++ndigits;
1120 t >>= PyLong_SHIFT;
1121 }
1122 v = _PyLong_New(ndigits);
1123 if (v != NULL) {
1124 digit *p = v->ob_digit;
1125 Py_SIZE(v) = ndigits;
1126 while (ival) {
1127 *p++ = (digit)(ival & PyLong_MASK);
1128 ival >>= PyLong_SHIFT;
1129 }
1130 }
1131 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001132}
1133
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001134/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001135 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001136
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001137PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001138PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyLongObject *v;
1141 PY_LONG_LONG bytes;
1142 int one = 1;
1143 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (vv == NULL) {
1146 PyErr_BadInternalCall();
1147 return -1;
1148 }
1149 if (!PyLong_Check(vv)) {
1150 PyNumberMethods *nb;
1151 PyObject *io;
1152 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1153 nb->nb_int == NULL) {
1154 PyErr_SetString(PyExc_TypeError, "an integer is required");
1155 return -1;
1156 }
1157 io = (*nb->nb_int) (vv);
1158 if (io == NULL)
1159 return -1;
1160 if (PyLong_Check(io)) {
1161 bytes = PyLong_AsLongLong(io);
1162 Py_DECREF(io);
1163 return bytes;
1164 }
1165 Py_DECREF(io);
1166 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1167 return -1;
1168 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 v = (PyLongObject*)vv;
1171 switch(Py_SIZE(v)) {
1172 case -1: return -(sdigit)v->ob_digit[0];
1173 case 0: return 0;
1174 case 1: return v->ob_digit[0];
1175 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001176 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1177 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1180 if (res < 0)
1181 return (PY_LONG_LONG)-1;
1182 else
1183 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001184}
1185
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001186/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001187 Return -1 and set an error if overflow occurs. */
1188
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001189unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001190PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyLongObject *v;
1193 unsigned PY_LONG_LONG bytes;
1194 int one = 1;
1195 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (vv == NULL || !PyLong_Check(vv)) {
1198 PyErr_BadInternalCall();
1199 return (unsigned PY_LONG_LONG)-1;
1200 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 v = (PyLongObject*)vv;
1203 switch(Py_SIZE(v)) {
1204 case 0: return 0;
1205 case 1: return v->ob_digit[0];
1206 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001207
Mark Dickinson22b20182010-05-10 21:27:53 +00001208 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1209 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1212 if (res < 0)
1213 return (unsigned PY_LONG_LONG)res;
1214 else
1215 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001216}
Tim Petersd1a7da62001-06-13 00:35:57 +00001217
Thomas Hellera4ea6032003-04-17 18:55:45 +00001218/* Get a C unsigned long int from a long int object, ignoring the high bits.
1219 Returns -1 and sets an error condition if an error occurs. */
1220
Guido van Rossumddefaf32007-01-14 03:31:43 +00001221static unsigned PY_LONG_LONG
1222_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 register PyLongObject *v;
1225 unsigned PY_LONG_LONG x;
1226 Py_ssize_t i;
1227 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (vv == NULL || !PyLong_Check(vv)) {
1230 PyErr_BadInternalCall();
1231 return (unsigned long) -1;
1232 }
1233 v = (PyLongObject *)vv;
1234 switch(Py_SIZE(v)) {
1235 case 0: return 0;
1236 case 1: return v->ob_digit[0];
1237 }
1238 i = Py_SIZE(v);
1239 sign = 1;
1240 x = 0;
1241 if (i < 0) {
1242 sign = -1;
1243 i = -i;
1244 }
1245 while (--i >= 0) {
1246 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1247 }
1248 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001249}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001250
1251unsigned PY_LONG_LONG
1252PyLong_AsUnsignedLongLongMask(register PyObject *op)
1253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyNumberMethods *nb;
1255 PyLongObject *lo;
1256 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (op && PyLong_Check(op))
1259 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1262 nb->nb_int == NULL) {
1263 PyErr_SetString(PyExc_TypeError, "an integer is required");
1264 return (unsigned PY_LONG_LONG)-1;
1265 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 lo = (PyLongObject*) (*nb->nb_int) (op);
1268 if (lo == NULL)
1269 return (unsigned PY_LONG_LONG)-1;
1270 if (PyLong_Check(lo)) {
1271 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1272 Py_DECREF(lo);
1273 if (PyErr_Occurred())
1274 return (unsigned PY_LONG_LONG)-1;
1275 return val;
1276 }
1277 else
1278 {
1279 Py_DECREF(lo);
1280 PyErr_SetString(PyExc_TypeError,
1281 "nb_int should return int object");
1282 return (unsigned PY_LONG_LONG)-1;
1283 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001284}
Tim Petersd1a7da62001-06-13 00:35:57 +00001285#undef IS_LITTLE_ENDIAN
1286
Mark Dickinson93f562c2010-01-30 10:30:15 +00001287/* Get a C long long int from a Python long or Python int object.
1288 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1289 on the sign of the result. Otherwise *overflow is 0.
1290
1291 For other errors (e.g., type error), returns -1 and sets an error
1292 condition.
1293*/
1294
1295PY_LONG_LONG
1296PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 /* This version by Tim Peters */
1299 register PyLongObject *v;
1300 unsigned PY_LONG_LONG x, prev;
1301 PY_LONG_LONG res;
1302 Py_ssize_t i;
1303 int sign;
1304 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 *overflow = 0;
1307 if (vv == NULL) {
1308 PyErr_BadInternalCall();
1309 return -1;
1310 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (!PyLong_Check(vv)) {
1313 PyNumberMethods *nb;
1314 nb = vv->ob_type->tp_as_number;
1315 if (nb == NULL || nb->nb_int == NULL) {
1316 PyErr_SetString(PyExc_TypeError,
1317 "an integer is required");
1318 return -1;
1319 }
1320 vv = (*nb->nb_int) (vv);
1321 if (vv == NULL)
1322 return -1;
1323 do_decref = 1;
1324 if (!PyLong_Check(vv)) {
1325 Py_DECREF(vv);
1326 PyErr_SetString(PyExc_TypeError,
1327 "nb_int should return int object");
1328 return -1;
1329 }
1330 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 res = -1;
1333 v = (PyLongObject *)vv;
1334 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 switch (i) {
1337 case -1:
1338 res = -(sdigit)v->ob_digit[0];
1339 break;
1340 case 0:
1341 res = 0;
1342 break;
1343 case 1:
1344 res = v->ob_digit[0];
1345 break;
1346 default:
1347 sign = 1;
1348 x = 0;
1349 if (i < 0) {
1350 sign = -1;
1351 i = -(i);
1352 }
1353 while (--i >= 0) {
1354 prev = x;
1355 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1356 if ((x >> PyLong_SHIFT) != prev) {
1357 *overflow = sign;
1358 goto exit;
1359 }
1360 }
1361 /* Haven't lost any bits, but casting to long requires extra
1362 * care (see comment above).
1363 */
1364 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1365 res = (PY_LONG_LONG)x * sign;
1366 }
1367 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1368 res = PY_LLONG_MIN;
1369 }
1370 else {
1371 *overflow = sign;
1372 /* res is already set to -1 */
1373 }
1374 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001375 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (do_decref) {
1377 Py_DECREF(vv);
1378 }
1379 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001380}
1381
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001382#endif /* HAVE_LONG_LONG */
1383
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001384#define CHECK_BINOP(v,w) \
1385 do { \
1386 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1387 Py_INCREF(Py_NotImplemented); \
1388 return Py_NotImplemented; \
1389 } \
1390 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001391
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001392/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1393 2**k if d is nonzero, else 0. */
1394
1395static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1397 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001398};
1399
1400static int
1401bits_in_digit(digit d)
1402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 int d_bits = 0;
1404 while (d >= 32) {
1405 d_bits += 6;
1406 d >>= 6;
1407 }
1408 d_bits += (int)BitLengthTable[d];
1409 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001410}
1411
Tim Peters877a2122002-08-12 05:09:36 +00001412/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1413 * is modified in place, by adding y to it. Carries are propagated as far as
1414 * x[m-1], and the remaining carry (0 or 1) is returned.
1415 */
1416static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001417v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 Py_ssize_t i;
1420 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 assert(m >= n);
1423 for (i = 0; i < n; ++i) {
1424 carry += x[i] + y[i];
1425 x[i] = carry & PyLong_MASK;
1426 carry >>= PyLong_SHIFT;
1427 assert((carry & 1) == carry);
1428 }
1429 for (; carry && i < m; ++i) {
1430 carry += x[i];
1431 x[i] = carry & PyLong_MASK;
1432 carry >>= PyLong_SHIFT;
1433 assert((carry & 1) == carry);
1434 }
1435 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001436}
1437
1438/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1439 * is modified in place, by subtracting y from it. Borrows are propagated as
1440 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1441 */
1442static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 Py_ssize_t i;
1446 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 assert(m >= n);
1449 for (i = 0; i < n; ++i) {
1450 borrow = x[i] - y[i] - borrow;
1451 x[i] = borrow & PyLong_MASK;
1452 borrow >>= PyLong_SHIFT;
1453 borrow &= 1; /* keep only 1 sign bit */
1454 }
1455 for (; borrow && i < m; ++i) {
1456 borrow = x[i] - borrow;
1457 x[i] = borrow & PyLong_MASK;
1458 borrow >>= PyLong_SHIFT;
1459 borrow &= 1;
1460 }
1461 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001462}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001463
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001464/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1465 * result in z[0:m], and return the d bits shifted out of the top.
1466 */
1467static digit
1468v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 Py_ssize_t i;
1471 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 assert(0 <= d && d < PyLong_SHIFT);
1474 for (i=0; i < m; i++) {
1475 twodigits acc = (twodigits)a[i] << d | carry;
1476 z[i] = (digit)acc & PyLong_MASK;
1477 carry = (digit)(acc >> PyLong_SHIFT);
1478 }
1479 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001480}
1481
1482/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1483 * result in z[0:m], and return the d bits shifted out of the bottom.
1484 */
1485static digit
1486v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 Py_ssize_t i;
1489 digit carry = 0;
1490 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 assert(0 <= d && d < PyLong_SHIFT);
1493 for (i=m; i-- > 0;) {
1494 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1495 carry = (digit)acc & mask;
1496 z[i] = (digit)(acc >> d);
1497 }
1498 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499}
1500
Tim Peters212e6142001-07-14 12:23:19 +00001501/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1502 in pout, and returning the remainder. pin and pout point at the LSD.
1503 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001504 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001505 immutable. */
1506
1507static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001508inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 assert(n > 0 && n <= PyLong_MASK);
1513 pin += size;
1514 pout += size;
1515 while (--size >= 0) {
1516 digit hi;
1517 rem = (rem << PyLong_SHIFT) | *--pin;
1518 *--pout = hi = (digit)(rem / n);
1519 rem -= (twodigits)hi * n;
1520 }
1521 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001522}
1523
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001524/* Divide a long integer by a digit, returning both the quotient
1525 (as function result) and the remainder (through *prem).
1526 The sign of a is ignored; n should not be zero. */
1527
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001528static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001529divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 const Py_ssize_t size = ABS(Py_SIZE(a));
1532 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 assert(n > 0 && n <= PyLong_MASK);
1535 z = _PyLong_New(size);
1536 if (z == NULL)
1537 return NULL;
1538 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1539 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001540}
1541
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001542/* Convert a long integer to a base 10 string. Returns a new non-shared
1543 string. (Return value is non-shared so that callers can modify the
1544 returned value if necessary.) */
1545
1546static PyObject *
1547long_to_decimal_string(PyObject *aa)
1548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 PyLongObject *scratch, *a;
1550 PyObject *str;
1551 Py_ssize_t size, strlen, size_a, i, j;
1552 digit *pout, *pin, rem, tenpow;
1553 Py_UNICODE *p;
1554 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 a = (PyLongObject *)aa;
1557 if (a == NULL || !PyLong_Check(a)) {
1558 PyErr_BadInternalCall();
1559 return NULL;
1560 }
1561 size_a = ABS(Py_SIZE(a));
1562 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 /* quick and dirty upper bound for the number of digits
1565 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 But log2(a) < size_a * PyLong_SHIFT, and
1570 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1571 > 3 * _PyLong_DECIMAL_SHIFT
1572 */
1573 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1574 PyErr_SetString(PyExc_OverflowError,
1575 "long is too large to format");
1576 return NULL;
1577 }
1578 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1579 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1580 scratch = _PyLong_New(size);
1581 if (scratch == NULL)
1582 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 /* convert array of base _PyLong_BASE digits in pin to an array of
1585 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1586 Volume 2 (3rd edn), section 4.4, Method 1b). */
1587 pin = a->ob_digit;
1588 pout = scratch->ob_digit;
1589 size = 0;
1590 for (i = size_a; --i >= 0; ) {
1591 digit hi = pin[i];
1592 for (j = 0; j < size; j++) {
1593 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1594 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1595 pout[j] = (digit)(z - (twodigits)hi *
1596 _PyLong_DECIMAL_BASE);
1597 }
1598 while (hi) {
1599 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1600 hi /= _PyLong_DECIMAL_BASE;
1601 }
1602 /* check for keyboard interrupt */
1603 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001604 Py_DECREF(scratch);
1605 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001606 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 }
1608 /* pout should have at least one digit, so that the case when a = 0
1609 works correctly */
1610 if (size == 0)
1611 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 /* calculate exact length of output string, and allocate */
1614 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1615 tenpow = 10;
1616 rem = pout[size-1];
1617 while (rem >= tenpow) {
1618 tenpow *= 10;
1619 strlen++;
1620 }
1621 str = PyUnicode_FromUnicode(NULL, strlen);
1622 if (str == NULL) {
1623 Py_DECREF(scratch);
1624 return NULL;
1625 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* fill the string right-to-left */
1628 p = PyUnicode_AS_UNICODE(str) + strlen;
1629 *p = '\0';
1630 /* pout[0] through pout[size-2] contribute exactly
1631 _PyLong_DECIMAL_SHIFT digits each */
1632 for (i=0; i < size - 1; i++) {
1633 rem = pout[i];
1634 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1635 *--p = '0' + rem % 10;
1636 rem /= 10;
1637 }
1638 }
1639 /* pout[size-1]: always produce at least one decimal digit */
1640 rem = pout[i];
1641 do {
1642 *--p = '0' + rem % 10;
1643 rem /= 10;
1644 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* and sign */
1647 if (negative)
1648 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* check we've counted correctly */
1651 assert(p == PyUnicode_AS_UNICODE(str));
1652 Py_DECREF(scratch);
1653 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001654}
1655
Mark Dickinsoncd068122009-09-18 14:53:08 +00001656/* Convert a long int object to a string, using a given conversion base,
1657 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001658 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001659
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001660PyObject *
1661_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 register PyLongObject *a = (PyLongObject *)aa;
1664 PyObject *str;
1665 Py_ssize_t i, sz;
1666 Py_ssize_t size_a;
1667 Py_UNICODE *p, sign = '\0';
1668 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 assert(base == 2 || base == 8 || base == 10 || base == 16);
1671 if (base == 10)
1672 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (a == NULL || !PyLong_Check(a)) {
1675 PyErr_BadInternalCall();
1676 return NULL;
1677 }
1678 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 /* Compute a rough upper bound for the length of the string */
1681 switch (base) {
1682 case 16:
1683 bits = 4;
1684 break;
1685 case 8:
1686 bits = 3;
1687 break;
1688 case 2:
1689 bits = 1;
1690 break;
1691 default:
1692 assert(0); /* shouldn't ever get here */
1693 bits = 0; /* to silence gcc warning */
1694 }
1695 /* compute length of output string: allow 2 characters for prefix and
1696 1 for possible '-' sign. */
1697 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1698 PyErr_SetString(PyExc_OverflowError,
1699 "int is too large to format");
1700 return NULL;
1701 }
1702 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1703 is safe from overflow */
1704 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1705 assert(sz >= 0);
1706 str = PyUnicode_FromUnicode(NULL, sz);
1707 if (str == NULL)
1708 return NULL;
1709 p = PyUnicode_AS_UNICODE(str) + sz;
1710 *p = '\0';
1711 if (Py_SIZE(a) < 0)
1712 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (Py_SIZE(a) == 0) {
1715 *--p = '0';
1716 }
1717 else {
1718 /* JRH: special case for power-of-2 bases */
1719 twodigits accum = 0;
1720 int accumbits = 0; /* # of bits in accum */
1721 for (i = 0; i < size_a; ++i) {
1722 accum |= (twodigits)a->ob_digit[i] << accumbits;
1723 accumbits += PyLong_SHIFT;
1724 assert(accumbits >= bits);
1725 do {
1726 Py_UNICODE cdigit;
1727 cdigit = (Py_UNICODE)(accum & (base - 1));
1728 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1729 assert(p > PyUnicode_AS_UNICODE(str));
1730 *--p = cdigit;
1731 accumbits -= bits;
1732 accum >>= bits;
1733 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1734 }
1735 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (base == 16)
1738 *--p = 'x';
1739 else if (base == 8)
1740 *--p = 'o';
1741 else /* (base == 2) */
1742 *--p = 'b';
1743 *--p = '0';
1744 if (sign)
1745 *--p = sign;
1746 if (p != PyUnicode_AS_UNICODE(str)) {
1747 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1748 assert(p > q);
1749 do {
1750 } while ((*q++ = *p++) != '\0');
1751 q--;
1752 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1753 PyUnicode_AS_UNICODE(str)))) {
1754 Py_DECREF(str);
1755 return NULL;
1756 }
1757 }
1758 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001759}
1760
Thomas Wouters477c8d52006-05-27 19:21:47 +00001761/* Table of digit values for 8-bit string -> integer conversion.
1762 * '0' maps to 0, ..., '9' maps to 9.
1763 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1764 * All other indices map to 37.
1765 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001766 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001767 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001768unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1772 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1773 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1774 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1775 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1776 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
1784 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001785};
1786
1787/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001788 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1789 * non-digit (which may be *str!). A normalized long is returned.
1790 * The point to this routine is that it takes time linear in the number of
1791 * string characters.
1792 */
1793static PyLongObject *
1794long_from_binary_base(char **str, int base)
1795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 char *p = *str;
1797 char *start = p;
1798 int bits_per_char;
1799 Py_ssize_t n;
1800 PyLongObject *z;
1801 twodigits accum;
1802 int bits_in_accum;
1803 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1806 n = base;
1807 for (bits_per_char = -1; n; ++bits_per_char)
1808 n >>= 1;
1809 /* n <- total # of bits needed, while setting p to end-of-string */
1810 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1811 ++p;
1812 *str = p;
1813 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1814 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1815 if (n / bits_per_char < p - start) {
1816 PyErr_SetString(PyExc_ValueError,
1817 "int string too large to convert");
1818 return NULL;
1819 }
1820 n = n / PyLong_SHIFT;
1821 z = _PyLong_New(n);
1822 if (z == NULL)
1823 return NULL;
1824 /* Read string from right, and fill in long from left; i.e.,
1825 * from least to most significant in both.
1826 */
1827 accum = 0;
1828 bits_in_accum = 0;
1829 pdigit = z->ob_digit;
1830 while (--p >= start) {
1831 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1832 assert(k >= 0 && k < base);
1833 accum |= (twodigits)k << bits_in_accum;
1834 bits_in_accum += bits_per_char;
1835 if (bits_in_accum >= PyLong_SHIFT) {
1836 *pdigit++ = (digit)(accum & PyLong_MASK);
1837 assert(pdigit - z->ob_digit <= n);
1838 accum >>= PyLong_SHIFT;
1839 bits_in_accum -= PyLong_SHIFT;
1840 assert(bits_in_accum < PyLong_SHIFT);
1841 }
1842 }
1843 if (bits_in_accum) {
1844 assert(bits_in_accum <= PyLong_SHIFT);
1845 *pdigit++ = (digit)accum;
1846 assert(pdigit - z->ob_digit <= n);
1847 }
1848 while (pdigit - z->ob_digit < n)
1849 *pdigit++ = 0;
1850 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001851}
1852
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001853PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001854PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 int sign = 1, error_if_nonzero = 0;
1857 char *start, *orig_str = str;
1858 PyLongObject *z = NULL;
1859 PyObject *strobj;
1860 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if ((base != 0 && base < 2) || base > 36) {
1863 PyErr_SetString(PyExc_ValueError,
1864 "int() arg 2 must be >= 2 and <= 36");
1865 return NULL;
1866 }
1867 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1868 str++;
1869 if (*str == '+')
1870 ++str;
1871 else if (*str == '-') {
1872 ++str;
1873 sign = -1;
1874 }
1875 if (base == 0) {
1876 if (str[0] != '0')
1877 base = 10;
1878 else if (str[1] == 'x' || str[1] == 'X')
1879 base = 16;
1880 else if (str[1] == 'o' || str[1] == 'O')
1881 base = 8;
1882 else if (str[1] == 'b' || str[1] == 'B')
1883 base = 2;
1884 else {
1885 /* "old" (C-style) octal literal, now invalid.
1886 it might still be zero though */
1887 error_if_nonzero = 1;
1888 base = 10;
1889 }
1890 }
1891 if (str[0] == '0' &&
1892 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1893 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1894 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1895 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 start = str;
1898 if ((base & (base - 1)) == 0)
1899 z = long_from_binary_base(&str, base);
1900 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901/***
1902Binary bases can be converted in time linear in the number of digits, because
1903Python's representation base is binary. Other bases (including decimal!) use
1904the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001905
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906First some math: the largest integer that can be expressed in N base-B digits
1907is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1908case number of Python digits needed to hold it is the smallest integer n s.t.
1909
1910 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1911 BASE**n >= B**N [taking logs to base BASE]
1912 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1913
1914The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1915this quickly. A Python long with that much space is reserved near the start,
1916and the result is computed into it.
1917
1918The input string is actually treated as being in base base**i (i.e., i digits
1919are processed at a time), where two more static arrays hold:
1920
1921 convwidth_base[base] = the largest integer i such that base**i <= BASE
1922 convmultmax_base[base] = base ** convwidth_base[base]
1923
1924The first of these is the largest i such that i consecutive input digits
1925must fit in a single Python digit. The second is effectively the input
1926base we're really using.
1927
1928Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1929convmultmax_base[base], the result is "simply"
1930
1931 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1932
1933where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001934
1935Error analysis: as above, the number of Python digits `n` needed is worst-
1936case
1937
1938 n >= N * log(B)/log(BASE)
1939
1940where `N` is the number of input digits in base `B`. This is computed via
1941
1942 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1943
1944below. Two numeric concerns are how much space this can waste, and whether
1945the computed result can be too small. To be concrete, assume BASE = 2**15,
1946which is the default (and it's unlikely anyone changes that).
1947
1948Waste isn't a problem: provided the first input digit isn't 0, the difference
1949between the worst-case input with N digits and the smallest input with N
1950digits is about a factor of B, but B is small compared to BASE so at most
1951one allocated Python digit can remain unused on that count. If
1952N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1953and adding 1 returns a result 1 larger than necessary. However, that can't
1954happen: whenever B is a power of 2, long_from_binary_base() is called
1955instead, and it's impossible for B**i to be an integer power of 2**15 when
1956B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1957an exact integer when B is not a power of 2, since B**i has a prime factor
1958other than 2 in that case, but (2**15)**j's only prime factor is 2).
1959
1960The computed result can be too small if the true value of N*log(B)/log(BASE)
1961is a little bit larger than an exact integer, but due to roundoff errors (in
1962computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1963yields a numeric result a little less than that integer. Unfortunately, "how
1964close can a transcendental function get to an integer over some range?"
1965questions are generally theoretically intractable. Computer analysis via
1966continued fractions is practical: expand log(B)/log(BASE) via continued
1967fractions, giving a sequence i/j of "the best" rational approximations. Then
1968j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1969we can get very close to being in trouble, but very rarely. For example,
197076573 is a denominator in one of the continued-fraction approximations to
1971log(10)/log(2**15), and indeed:
1972
1973 >>> log(10)/log(2**15)*76573
1974 16958.000000654003
1975
1976is very close to an integer. If we were working with IEEE single-precision,
1977rounding errors could kill us. Finding worst cases in IEEE double-precision
1978requires better-than-double-precision log() functions, and Tim didn't bother.
1979Instead the code checks to see whether the allocated space is enough as each
1980new Python digit is added, and copies the whole thing to a larger long if not.
1981This should happen extremely rarely, and in fact I don't have a test case
1982that triggers it(!). Instead the code was tested by artificially allocating
1983just 1 digit at the start, so that the copying code was exercised for every
1984digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 register twodigits c; /* current input character */
1987 Py_ssize_t size_z;
1988 int i;
1989 int convwidth;
1990 twodigits convmultmax, convmult;
1991 digit *pz, *pzstop;
1992 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 static double log_base_BASE[37] = {0.0e0,};
1995 static int convwidth_base[37] = {0,};
1996 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (log_base_BASE[base] == 0.0) {
1999 twodigits convmax = base;
2000 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002001
Mark Dickinson22b20182010-05-10 21:27:53 +00002002 log_base_BASE[base] = (log((double)base) /
2003 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 for (;;) {
2005 twodigits next = convmax * base;
2006 if (next > PyLong_BASE)
2007 break;
2008 convmax = next;
2009 ++i;
2010 }
2011 convmultmax_base[base] = convmax;
2012 assert(i > 0);
2013 convwidth_base[base] = i;
2014 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 /* Find length of the string of numeric characters. */
2017 scan = str;
2018 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2019 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Create a long object that can contain the largest possible
2022 * integer with this base and length. Note that there's no
2023 * need to initialize z->ob_digit -- no slot is read up before
2024 * being stored into.
2025 */
2026 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2027 /* Uncomment next line to test exceedingly rare copy code */
2028 /* size_z = 1; */
2029 assert(size_z > 0);
2030 z = _PyLong_New(size_z);
2031 if (z == NULL)
2032 return NULL;
2033 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 /* `convwidth` consecutive input digits are treated as a single
2036 * digit in base `convmultmax`.
2037 */
2038 convwidth = convwidth_base[base];
2039 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* Work ;-) */
2042 while (str < scan) {
2043 /* grab up to convwidth digits from the input string */
2044 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2045 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2046 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002047 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 assert(c < PyLong_BASE);
2049 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 convmult = convmultmax;
2052 /* Calculate the shift only if we couldn't get
2053 * convwidth digits.
2054 */
2055 if (i != convwidth) {
2056 convmult = base;
2057 for ( ; i > 1; --i)
2058 convmult *= base;
2059 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* Multiply z by convmult, and add c. */
2062 pz = z->ob_digit;
2063 pzstop = pz + Py_SIZE(z);
2064 for (; pz < pzstop; ++pz) {
2065 c += (twodigits)*pz * convmult;
2066 *pz = (digit)(c & PyLong_MASK);
2067 c >>= PyLong_SHIFT;
2068 }
2069 /* carry off the current end? */
2070 if (c) {
2071 assert(c < PyLong_BASE);
2072 if (Py_SIZE(z) < size_z) {
2073 *pz = (digit)c;
2074 ++Py_SIZE(z);
2075 }
2076 else {
2077 PyLongObject *tmp;
2078 /* Extremely rare. Get more space. */
2079 assert(Py_SIZE(z) == size_z);
2080 tmp = _PyLong_New(size_z + 1);
2081 if (tmp == NULL) {
2082 Py_DECREF(z);
2083 return NULL;
2084 }
2085 memcpy(tmp->ob_digit,
2086 z->ob_digit,
2087 sizeof(digit) * size_z);
2088 Py_DECREF(z);
2089 z = tmp;
2090 z->ob_digit[size_z] = (digit)c;
2091 ++size_z;
2092 }
2093 }
2094 }
2095 }
2096 if (z == NULL)
2097 return NULL;
2098 if (error_if_nonzero) {
2099 /* reset the base to 0, else the exception message
2100 doesn't make too much sense */
2101 base = 0;
2102 if (Py_SIZE(z) != 0)
2103 goto onError;
2104 /* there might still be other problems, therefore base
2105 remains zero here for the same reason */
2106 }
2107 if (str == start)
2108 goto onError;
2109 if (sign < 0)
2110 Py_SIZE(z) = -(Py_SIZE(z));
2111 while (*str && isspace(Py_CHARMASK(*str)))
2112 str++;
2113 if (*str != '\0')
2114 goto onError;
2115 if (pend)
2116 *pend = str;
2117 long_normalize(z);
2118 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002119
Mark Dickinson22b20182010-05-10 21:27:53 +00002120 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 Py_XDECREF(z);
2122 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2123 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2124 if (strobj == NULL)
2125 return NULL;
2126 PyErr_Format(PyExc_ValueError,
2127 "invalid literal for int() with base %d: %R",
2128 base, strobj);
2129 Py_DECREF(strobj);
2130 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002131}
2132
2133PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002134PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyObject *result;
2137 char *buffer = (char *)PyMem_MALLOC(length+1);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (buffer == NULL)
2140 return NULL;
Walter Dörwald07e14762002-11-06 16:15:14 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
2143 PyMem_FREE(buffer);
2144 return NULL;
2145 }
2146 result = PyLong_FromString(buffer, NULL, base);
2147 PyMem_FREE(buffer);
2148 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002149}
2150
Tim Peters9f688bf2000-07-07 15:53:28 +00002151/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002152static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002154static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002155
2156/* Long division with remainder, top-level routine */
2157
Guido van Rossume32e0141992-01-19 16:31:05 +00002158static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002159long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2163 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (size_b == 0) {
2166 PyErr_SetString(PyExc_ZeroDivisionError,
2167 "integer division or modulo by zero");
2168 return -1;
2169 }
2170 if (size_a < size_b ||
2171 (size_a == size_b &&
2172 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2173 /* |a| < |b|. */
2174 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2175 if (*pdiv == NULL)
2176 return -1;
2177 Py_INCREF(a);
2178 *prem = (PyLongObject *) a;
2179 return 0;
2180 }
2181 if (size_b == 1) {
2182 digit rem = 0;
2183 z = divrem1(a, b->ob_digit[0], &rem);
2184 if (z == NULL)
2185 return -1;
2186 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2187 if (*prem == NULL) {
2188 Py_DECREF(z);
2189 return -1;
2190 }
2191 }
2192 else {
2193 z = x_divrem(a, b, prem);
2194 if (z == NULL)
2195 return -1;
2196 }
2197 /* Set the signs.
2198 The quotient z has the sign of a*b;
2199 the remainder r has the sign of a,
2200 so a = b*z + r. */
2201 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2202 NEGATE(z);
2203 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2204 NEGATE(*prem);
2205 *pdiv = maybe_small_long(z);
2206 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002207}
2208
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002209/* Unsigned long division with remainder -- the algorithm. The arguments v1
2210 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002211
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002212static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002213x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyLongObject *v, *w, *a;
2216 Py_ssize_t i, k, size_v, size_w;
2217 int d;
2218 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2219 twodigits vv;
2220 sdigit zhi;
2221 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2224 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2225 handle the special case when the initial estimate q for a quotient
2226 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2227 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 /* allocate space; w will also be used to hold the final remainder */
2230 size_v = ABS(Py_SIZE(v1));
2231 size_w = ABS(Py_SIZE(w1));
2232 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2233 v = _PyLong_New(size_v+1);
2234 if (v == NULL) {
2235 *prem = NULL;
2236 return NULL;
2237 }
2238 w = _PyLong_New(size_w);
2239 if (w == NULL) {
2240 Py_DECREF(v);
2241 *prem = NULL;
2242 return NULL;
2243 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2246 shift v1 left by the same amount. Results go into w and v. */
2247 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2248 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2249 assert(carry == 0);
2250 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2251 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2252 v->ob_digit[size_v] = carry;
2253 size_v++;
2254 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2257 at most (and usually exactly) k = size_v - size_w digits. */
2258 k = size_v - size_w;
2259 assert(k >= 0);
2260 a = _PyLong_New(k);
2261 if (a == NULL) {
2262 Py_DECREF(w);
2263 Py_DECREF(v);
2264 *prem = NULL;
2265 return NULL;
2266 }
2267 v0 = v->ob_digit;
2268 w0 = w->ob_digit;
2269 wm1 = w0[size_w-1];
2270 wm2 = w0[size_w-2];
2271 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2272 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2273 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002276 Py_DECREF(a);
2277 Py_DECREF(w);
2278 Py_DECREF(v);
2279 *prem = NULL;
2280 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002281 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* estimate quotient digit q; may overestimate by 1 (rare) */
2284 vtop = vk[size_w];
2285 assert(vtop <= wm1);
2286 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2287 q = (digit)(vv / wm1);
2288 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2289 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2290 | vk[size_w-2])) {
2291 --q;
2292 r += wm1;
2293 if (r >= PyLong_BASE)
2294 break;
2295 }
2296 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2299 zhi = 0;
2300 for (i = 0; i < size_w; ++i) {
2301 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2302 -PyLong_BASE * q <= z < PyLong_BASE */
2303 z = (sdigit)vk[i] + zhi -
2304 (stwodigits)q * (stwodigits)w0[i];
2305 vk[i] = (digit)z & PyLong_MASK;
2306 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002307 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* add w back if q was too large (this branch taken rarely) */
2311 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2312 if ((sdigit)vtop + zhi < 0) {
2313 carry = 0;
2314 for (i = 0; i < size_w; ++i) {
2315 carry += vk[i] + w0[i];
2316 vk[i] = carry & PyLong_MASK;
2317 carry >>= PyLong_SHIFT;
2318 }
2319 --q;
2320 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* store quotient digit */
2323 assert(q < PyLong_BASE);
2324 *--ak = q;
2325 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 /* unshift remainder; we reuse w to store the result */
2328 carry = v_rshift(w0, v0, size_w, d);
2329 assert(carry==0);
2330 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 *prem = long_normalize(w);
2333 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002334}
2335
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002336/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2337 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2338 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2339 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2340 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2341 -1.0. */
2342
2343/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2344#if DBL_MANT_DIG == 53
2345#define EXP2_DBL_MANT_DIG 9007199254740992.0
2346#else
2347#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2348#endif
2349
2350double
2351_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2354 /* See below for why x_digits is always large enough. */
2355 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2356 double dx;
2357 /* Correction term for round-half-to-even rounding. For a digit x,
2358 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2359 multiple of 4, rounding ties to a multiple of 8. */
2360 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 a_size = ABS(Py_SIZE(a));
2363 if (a_size == 0) {
2364 /* Special case for 0: significand 0.0, exponent 0. */
2365 *e = 0;
2366 return 0.0;
2367 }
2368 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2369 /* The following is an overflow-free version of the check
2370 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2371 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2372 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2373 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002374 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2378 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Number of digits needed for result: write // for floor division.
2381 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2390 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2393 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2394 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 in both cases.
2401 */
2402 if (a_bits <= DBL_MANT_DIG + 2) {
2403 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2404 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2405 x_size = 0;
2406 while (x_size < shift_digits)
2407 x_digits[x_size++] = 0;
2408 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2409 (int)shift_bits);
2410 x_size += a_size;
2411 x_digits[x_size++] = rem;
2412 }
2413 else {
2414 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2415 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2416 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2417 a_size - shift_digits, (int)shift_bits);
2418 x_size = a_size - shift_digits;
2419 /* For correct rounding below, we need the least significant
2420 bit of x to be 'sticky' for this shift: if any of the bits
2421 shifted out was nonzero, we set the least significant bit
2422 of x. */
2423 if (rem)
2424 x_digits[0] |= 1;
2425 else
2426 while (shift_digits > 0)
2427 if (a->ob_digit[--shift_digits]) {
2428 x_digits[0] |= 1;
2429 break;
2430 }
2431 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002432 assert(1 <= x_size &&
2433 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* Round, and convert to double. */
2436 x_digits[0] += half_even_correction[x_digits[0] & 7];
2437 dx = x_digits[--x_size];
2438 while (x_size > 0)
2439 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 /* Rescale; make correction if result is 1.0. */
2442 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2443 if (dx == 1.0) {
2444 if (a_bits == PY_SSIZE_T_MAX)
2445 goto overflow;
2446 dx = 0.5;
2447 a_bits += 1;
2448 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 *e = a_bits;
2451 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002452
2453 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* exponent > PY_SSIZE_T_MAX */
2455 PyErr_SetString(PyExc_OverflowError,
2456 "huge integer: number of bits overflows a Py_ssize_t");
2457 *e = 0;
2458 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002459}
2460
2461/* Get a C double from a long int object. Rounds to the nearest double,
2462 using the round-half-to-even rule in the case of a tie. */
2463
2464double
2465PyLong_AsDouble(PyObject *v)
2466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 Py_ssize_t exponent;
2468 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (v == NULL || !PyLong_Check(v)) {
2471 PyErr_BadInternalCall();
2472 return -1.0;
2473 }
2474 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2475 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2476 PyErr_SetString(PyExc_OverflowError,
2477 "long int too large to convert to float");
2478 return -1.0;
2479 }
2480 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002481}
2482
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002483/* Methods */
2484
2485static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002486long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002489}
2490
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002491static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002492long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (Py_SIZE(a) != Py_SIZE(b)) {
2497 sign = Py_SIZE(a) - Py_SIZE(b);
2498 }
2499 else {
2500 Py_ssize_t i = ABS(Py_SIZE(a));
2501 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2502 ;
2503 if (i < 0)
2504 sign = 0;
2505 else {
2506 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2507 if (Py_SIZE(a) < 0)
2508 sign = -sign;
2509 }
2510 }
2511 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002512}
2513
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002514#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002516
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002517static PyObject *
2518long_richcompare(PyObject *self, PyObject *other, int op)
2519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 int result;
2521 PyObject *v;
2522 CHECK_BINOP(self, other);
2523 if (self == other)
2524 result = 0;
2525 else
2526 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2527 /* Convert the return value to a Boolean */
2528 switch (op) {
2529 case Py_EQ:
2530 v = TEST_COND(result == 0);
2531 break;
2532 case Py_NE:
2533 v = TEST_COND(result != 0);
2534 break;
2535 case Py_LE:
2536 v = TEST_COND(result <= 0);
2537 break;
2538 case Py_GE:
2539 v = TEST_COND(result >= 0);
2540 break;
2541 case Py_LT:
2542 v = TEST_COND(result == -1);
2543 break;
2544 case Py_GT:
2545 v = TEST_COND(result == 1);
2546 break;
2547 default:
2548 PyErr_BadArgument();
2549 return NULL;
2550 }
2551 Py_INCREF(v);
2552 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002553}
2554
Guido van Rossum9bfef441993-03-29 10:43:31 +00002555static long
Tim Peters9f688bf2000-07-07 15:53:28 +00002556long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 unsigned long x;
2559 Py_ssize_t i;
2560 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 i = Py_SIZE(v);
2563 switch(i) {
2564 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2565 case 0: return 0;
2566 case 1: return v->ob_digit[0];
2567 }
2568 sign = 1;
2569 x = 0;
2570 if (i < 0) {
2571 sign = -1;
2572 i = -(i);
2573 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002575 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2576 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2577 _PyHASH_MODULUS.
2578
2579 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2580 amounts to a rotation of the bits of x. To see this, write
2581
2582 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2583
2584 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2585 PyLong_SHIFT bits of x (those that are shifted out of the
2586 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2587 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2588 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2589 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2590 congruent to y modulo _PyHASH_MODULUS. So
2591
2592 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2593
2594 The right-hand side is just the result of rotating the
2595 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2596 not all _PyHASH_BITS bits of x are 1s, the same is true
2597 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2598 the reduction of x*2**PyLong_SHIFT modulo
2599 _PyHASH_MODULUS. */
2600 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2601 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002603 if (x >= _PyHASH_MODULUS)
2604 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 }
2606 x = x * sign;
2607 if (x == (unsigned long)-1)
2608 x = (unsigned long)-2;
2609 return (long)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002610}
2611
2612
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002613/* Add the absolute values of two long integers. */
2614
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002615static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002616x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2619 PyLongObject *z;
2620 Py_ssize_t i;
2621 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* Ensure a is the larger of the two: */
2624 if (size_a < size_b) {
2625 { PyLongObject *temp = a; a = b; b = temp; }
2626 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002627 size_a = size_b;
2628 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 }
2630 z = _PyLong_New(size_a+1);
2631 if (z == NULL)
2632 return NULL;
2633 for (i = 0; i < size_b; ++i) {
2634 carry += a->ob_digit[i] + b->ob_digit[i];
2635 z->ob_digit[i] = carry & PyLong_MASK;
2636 carry >>= PyLong_SHIFT;
2637 }
2638 for (; i < size_a; ++i) {
2639 carry += a->ob_digit[i];
2640 z->ob_digit[i] = carry & PyLong_MASK;
2641 carry >>= PyLong_SHIFT;
2642 }
2643 z->ob_digit[i] = carry;
2644 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002645}
2646
2647/* Subtract the absolute values of two integers. */
2648
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002649static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002650x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2653 PyLongObject *z;
2654 Py_ssize_t i;
2655 int sign = 1;
2656 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 /* Ensure a is the larger of the two: */
2659 if (size_a < size_b) {
2660 sign = -1;
2661 { PyLongObject *temp = a; a = b; b = temp; }
2662 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002663 size_a = size_b;
2664 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 }
2666 else if (size_a == size_b) {
2667 /* Find highest digit where a and b differ: */
2668 i = size_a;
2669 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2670 ;
2671 if (i < 0)
2672 return (PyLongObject *)PyLong_FromLong(0);
2673 if (a->ob_digit[i] < b->ob_digit[i]) {
2674 sign = -1;
2675 { PyLongObject *temp = a; a = b; b = temp; }
2676 }
2677 size_a = size_b = i+1;
2678 }
2679 z = _PyLong_New(size_a);
2680 if (z == NULL)
2681 return NULL;
2682 for (i = 0; i < size_b; ++i) {
2683 /* The following assumes unsigned arithmetic
2684 works module 2**N for some N>PyLong_SHIFT. */
2685 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2686 z->ob_digit[i] = borrow & PyLong_MASK;
2687 borrow >>= PyLong_SHIFT;
2688 borrow &= 1; /* Keep only one sign bit */
2689 }
2690 for (; i < size_a; ++i) {
2691 borrow = a->ob_digit[i] - borrow;
2692 z->ob_digit[i] = borrow & PyLong_MASK;
2693 borrow >>= PyLong_SHIFT;
2694 borrow &= 1; /* Keep only one sign bit */
2695 }
2696 assert(borrow == 0);
2697 if (sign < 0)
2698 NEGATE(z);
2699 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002700}
2701
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002702static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002703long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2710 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2711 MEDIUM_VALUE(b));
2712 return result;
2713 }
2714 if (Py_SIZE(a) < 0) {
2715 if (Py_SIZE(b) < 0) {
2716 z = x_add(a, b);
2717 if (z != NULL && Py_SIZE(z) != 0)
2718 Py_SIZE(z) = -(Py_SIZE(z));
2719 }
2720 else
2721 z = x_sub(b, a);
2722 }
2723 else {
2724 if (Py_SIZE(b) < 0)
2725 z = x_sub(a, b);
2726 else
2727 z = x_add(a, b);
2728 }
2729 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002730}
2731
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002732static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002733long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2740 PyObject* r;
2741 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2742 return r;
2743 }
2744 if (Py_SIZE(a) < 0) {
2745 if (Py_SIZE(b) < 0)
2746 z = x_sub(a, b);
2747 else
2748 z = x_add(a, b);
2749 if (z != NULL && Py_SIZE(z) != 0)
2750 Py_SIZE(z) = -(Py_SIZE(z));
2751 }
2752 else {
2753 if (Py_SIZE(b) < 0)
2754 z = x_add(a, b);
2755 else
2756 z = x_sub(a, b);
2757 }
2758 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002759}
2760
Tim Peters5af4e6c2002-08-12 02:31:19 +00002761/* Grade school multiplication, ignoring the signs.
2762 * Returns the absolute value of the product, or NULL if error.
2763 */
2764static PyLongObject *
2765x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 PyLongObject *z;
2768 Py_ssize_t size_a = ABS(Py_SIZE(a));
2769 Py_ssize_t size_b = ABS(Py_SIZE(b));
2770 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 z = _PyLong_New(size_a + size_b);
2773 if (z == NULL)
2774 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2777 if (a == b) {
2778 /* Efficient squaring per HAC, Algorithm 14.16:
2779 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2780 * Gives slightly less than a 2x speedup when a == b,
2781 * via exploiting that each entry in the multiplication
2782 * pyramid appears twice (except for the size_a squares).
2783 */
2784 for (i = 0; i < size_a; ++i) {
2785 twodigits carry;
2786 twodigits f = a->ob_digit[i];
2787 digit *pz = z->ob_digit + (i << 1);
2788 digit *pa = a->ob_digit + i + 1;
2789 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002792 Py_DECREF(z);
2793 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002794 });
Tim Peters0973b992004-08-29 22:16:50 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 carry = *pz + f * f;
2797 *pz++ = (digit)(carry & PyLong_MASK);
2798 carry >>= PyLong_SHIFT;
2799 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 /* Now f is added in twice in each column of the
2802 * pyramid it appears. Same as adding f<<1 once.
2803 */
2804 f <<= 1;
2805 while (pa < paend) {
2806 carry += *pz + *pa++ * f;
2807 *pz++ = (digit)(carry & PyLong_MASK);
2808 carry >>= PyLong_SHIFT;
2809 assert(carry <= (PyLong_MASK << 1));
2810 }
2811 if (carry) {
2812 carry += *pz;
2813 *pz++ = (digit)(carry & PyLong_MASK);
2814 carry >>= PyLong_SHIFT;
2815 }
2816 if (carry)
2817 *pz += (digit)(carry & PyLong_MASK);
2818 assert((carry >> PyLong_SHIFT) == 0);
2819 }
2820 }
2821 else { /* a is not the same as b -- gradeschool long mult */
2822 for (i = 0; i < size_a; ++i) {
2823 twodigits carry = 0;
2824 twodigits f = a->ob_digit[i];
2825 digit *pz = z->ob_digit + i;
2826 digit *pb = b->ob_digit;
2827 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002830 Py_DECREF(z);
2831 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002832 });
Tim Peters0973b992004-08-29 22:16:50 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 while (pb < pbend) {
2835 carry += *pz + *pb++ * f;
2836 *pz++ = (digit)(carry & PyLong_MASK);
2837 carry >>= PyLong_SHIFT;
2838 assert(carry <= PyLong_MASK);
2839 }
2840 if (carry)
2841 *pz += (digit)(carry & PyLong_MASK);
2842 assert((carry >> PyLong_SHIFT) == 0);
2843 }
2844 }
2845 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002846}
2847
2848/* A helper for Karatsuba multiplication (k_mul).
2849 Takes a long "n" and an integer "size" representing the place to
2850 split, and sets low and high such that abs(n) == (high << size) + low,
2851 viewing the shift as being by digits. The sign bit is ignored, and
2852 the return values are >= 0.
2853 Returns 0 on success, -1 on failure.
2854*/
2855static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002856kmul_split(PyLongObject *n,
2857 Py_ssize_t size,
2858 PyLongObject **high,
2859 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 PyLongObject *hi, *lo;
2862 Py_ssize_t size_lo, size_hi;
2863 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 size_lo = MIN(size_n, size);
2866 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 if ((hi = _PyLong_New(size_hi)) == NULL)
2869 return -1;
2870 if ((lo = _PyLong_New(size_lo)) == NULL) {
2871 Py_DECREF(hi);
2872 return -1;
2873 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2876 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 *high = long_normalize(hi);
2879 *low = long_normalize(lo);
2880 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002881}
2882
Tim Peters60004642002-08-12 22:01:34 +00002883static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2884
Tim Peters5af4e6c2002-08-12 02:31:19 +00002885/* Karatsuba multiplication. Ignores the input signs, and returns the
2886 * absolute value of the product (or NULL if error).
2887 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2888 */
2889static PyLongObject *
2890k_mul(PyLongObject *a, PyLongObject *b)
2891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 Py_ssize_t asize = ABS(Py_SIZE(a));
2893 Py_ssize_t bsize = ABS(Py_SIZE(b));
2894 PyLongObject *ah = NULL;
2895 PyLongObject *al = NULL;
2896 PyLongObject *bh = NULL;
2897 PyLongObject *bl = NULL;
2898 PyLongObject *ret = NULL;
2899 PyLongObject *t1, *t2, *t3;
2900 Py_ssize_t shift; /* the number of digits we split off */
2901 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002903 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2904 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2905 * Then the original product is
2906 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2907 * By picking X to be a power of 2, "*X" is just shifting, and it's
2908 * been reduced to 3 multiplies on numbers half the size.
2909 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 /* We want to split based on the larger number; fiddle so that b
2912 * is largest.
2913 */
2914 if (asize > bsize) {
2915 t1 = a;
2916 a = b;
2917 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 i = asize;
2920 asize = bsize;
2921 bsize = i;
2922 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 /* Use gradeschool math when either number is too small. */
2925 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2926 if (asize <= i) {
2927 if (asize == 0)
2928 return (PyLongObject *)PyLong_FromLong(0);
2929 else
2930 return x_mul(a, b);
2931 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 /* If a is small compared to b, splitting on b gives a degenerate
2934 * case with ah==0, and Karatsuba may be (even much) less efficient
2935 * than "grade school" then. However, we can still win, by viewing
2936 * b as a string of "big digits", each of width a->ob_size. That
2937 * leads to a sequence of balanced calls to k_mul.
2938 */
2939 if (2 * asize <= bsize)
2940 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 /* Split a & b into hi & lo pieces. */
2943 shift = bsize >> 1;
2944 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2945 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 if (a == b) {
2948 bh = ah;
2949 bl = al;
2950 Py_INCREF(bh);
2951 Py_INCREF(bl);
2952 }
2953 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 /* The plan:
2956 * 1. Allocate result space (asize + bsize digits: that's always
2957 * enough).
2958 * 2. Compute ah*bh, and copy into result at 2*shift.
2959 * 3. Compute al*bl, and copy into result at 0. Note that this
2960 * can't overlap with #2.
2961 * 4. Subtract al*bl from the result, starting at shift. This may
2962 * underflow (borrow out of the high digit), but we don't care:
2963 * we're effectively doing unsigned arithmetic mod
2964 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2965 * borrows and carries out of the high digit can be ignored.
2966 * 5. Subtract ah*bh from the result, starting at shift.
2967 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2968 * at shift.
2969 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 /* 1. Allocate result space. */
2972 ret = _PyLong_New(asize + bsize);
2973 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002974#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 /* Fill with trash, to catch reference to uninitialized digits. */
2976 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002977#endif
Tim Peters44121a62002-08-12 06:17:58 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2980 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2981 assert(Py_SIZE(t1) >= 0);
2982 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2983 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2984 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 /* Zero-out the digits higher than the ah*bh copy. */
2987 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
2988 if (i)
2989 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
2990 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 /* 3. t2 <- al*bl, and copy into the low digits. */
2993 if ((t2 = k_mul(al, bl)) == NULL) {
2994 Py_DECREF(t1);
2995 goto fail;
2996 }
2997 assert(Py_SIZE(t2) >= 0);
2998 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
2999 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 /* Zero out remaining digits. */
3002 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3003 if (i)
3004 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3007 * because it's fresher in cache.
3008 */
3009 i = Py_SIZE(ret) - shift; /* # digits after shift */
3010 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3011 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3014 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3017 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3018 Py_DECREF(ah);
3019 Py_DECREF(al);
3020 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 if (a == b) {
3023 t2 = t1;
3024 Py_INCREF(t2);
3025 }
3026 else if ((t2 = x_add(bh, bl)) == NULL) {
3027 Py_DECREF(t1);
3028 goto fail;
3029 }
3030 Py_DECREF(bh);
3031 Py_DECREF(bl);
3032 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 t3 = k_mul(t1, t2);
3035 Py_DECREF(t1);
3036 Py_DECREF(t2);
3037 if (t3 == NULL) goto fail;
3038 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 /* Add t3. It's not obvious why we can't run out of room here.
3041 * See the (*) comment after this function.
3042 */
3043 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3044 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003047
Mark Dickinson22b20182010-05-10 21:27:53 +00003048 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003049 Py_XDECREF(ret);
3050 Py_XDECREF(ah);
3051 Py_XDECREF(al);
3052 Py_XDECREF(bh);
3053 Py_XDECREF(bl);
3054 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003055}
3056
Tim Petersd6974a52002-08-13 20:37:51 +00003057/* (*) Why adding t3 can't "run out of room" above.
3058
Tim Petersab86c2b2002-08-15 20:06:00 +00003059Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3060to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003061
Tim Petersab86c2b2002-08-15 20:06:00 +000030621. For any integer i, i = c(i/2) + f(i/2). In particular,
3063 bsize = c(bsize/2) + f(bsize/2).
30642. shift = f(bsize/2)
30653. asize <= bsize
30664. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3067 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003068
Tim Petersab86c2b2002-08-15 20:06:00 +00003069We allocated asize + bsize result digits, and add t3 into them at an offset
3070of shift. This leaves asize+bsize-shift allocated digit positions for t3
3071to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3072asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003073
Tim Petersab86c2b2002-08-15 20:06:00 +00003074bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3075at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003076
Tim Petersab86c2b2002-08-15 20:06:00 +00003077If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3078digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3079most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003080
Tim Petersab86c2b2002-08-15 20:06:00 +00003081The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003082
Tim Petersab86c2b2002-08-15 20:06:00 +00003083 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003084
Tim Petersab86c2b2002-08-15 20:06:00 +00003085and we have asize + c(bsize/2) available digit positions. We need to show
3086this is always enough. An instance of c(bsize/2) cancels out in both, so
3087the question reduces to whether asize digits is enough to hold
3088(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3089then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3090asize 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 +00003091digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003092asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003093c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3094is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3095bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003096
Tim Peters48d52c02002-08-14 17:07:32 +00003097Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3098clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3099ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003100*/
3101
Tim Peters60004642002-08-12 22:01:34 +00003102/* b has at least twice the digits of a, and a is big enough that Karatsuba
3103 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3104 * of slices, each with a->ob_size digits, and multiply the slices by a,
3105 * one at a time. This gives k_mul balanced inputs to work with, and is
3106 * also cache-friendly (we compute one double-width slice of the result
3107 * at a time, then move on, never bactracking except for the helpful
3108 * single-width slice overlap between successive partial sums).
3109 */
3110static PyLongObject *
3111k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 const Py_ssize_t asize = ABS(Py_SIZE(a));
3114 Py_ssize_t bsize = ABS(Py_SIZE(b));
3115 Py_ssize_t nbdone; /* # of b digits already multiplied */
3116 PyLongObject *ret;
3117 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 assert(asize > KARATSUBA_CUTOFF);
3120 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 /* Allocate result space, and zero it out. */
3123 ret = _PyLong_New(asize + bsize);
3124 if (ret == NULL)
3125 return NULL;
3126 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* Successive slices of b are copied into bslice. */
3129 bslice = _PyLong_New(asize);
3130 if (bslice == NULL)
3131 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 nbdone = 0;
3134 while (bsize > 0) {
3135 PyLongObject *product;
3136 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* Multiply the next slice of b by a. */
3139 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3140 nbtouse * sizeof(digit));
3141 Py_SIZE(bslice) = nbtouse;
3142 product = k_mul(a, bslice);
3143 if (product == NULL)
3144 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* Add into result. */
3147 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3148 product->ob_digit, Py_SIZE(product));
3149 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 bsize -= nbtouse;
3152 nbdone += nbtouse;
3153 }
Tim Peters60004642002-08-12 22:01:34 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 Py_DECREF(bslice);
3156 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003157
Mark Dickinson22b20182010-05-10 21:27:53 +00003158 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 Py_DECREF(ret);
3160 Py_XDECREF(bslice);
3161 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003162}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003163
3164static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003165long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 /* fast path for single-digit multiplication */
3172 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3173 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003174#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003176#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 /* if we don't have long long then we're almost certainly
3178 using 15-bit digits, so v will fit in a long. In the
3179 unlikely event that we're using 30-bit digits on a platform
3180 without long long, a large v will just cause us to fall
3181 through to the general multiplication code below. */
3182 if (v >= LONG_MIN && v <= LONG_MAX)
3183 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003184#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 z = k_mul(a, b);
3188 /* Negate if exactly one of the inputs is negative. */
3189 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3190 NEGATE(z);
3191 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003192}
3193
Guido van Rossume32e0141992-01-19 16:31:05 +00003194/* The / and % operators are now defined in terms of divmod().
3195 The expression a mod b has the value a - b*floor(a/b).
3196 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003197 |a| by |b|, with the sign of a. This is also expressed
3198 as a - b*trunc(a/b), if trunc truncates towards zero.
3199 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 a b a rem b a mod b
3201 13 10 3 3
3202 -13 10 -3 7
3203 13 -10 3 -7
3204 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003205 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003206 have different signs. We then subtract one from the 'div'
3207 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003208
Tim Peters47e52ee2004-08-30 02:44:38 +00003209/* Compute
3210 * *pdiv, *pmod = divmod(v, w)
3211 * NULL can be passed for pdiv or pmod, in which case that part of
3212 * the result is simply thrown away. The caller owns a reference to
3213 * each of these it requests (does not pass NULL for).
3214 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003215static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003216l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 if (long_divrem(v, w, &div, &mod) < 0)
3222 return -1;
3223 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3224 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3225 PyLongObject *temp;
3226 PyLongObject *one;
3227 temp = (PyLongObject *) long_add(mod, w);
3228 Py_DECREF(mod);
3229 mod = temp;
3230 if (mod == NULL) {
3231 Py_DECREF(div);
3232 return -1;
3233 }
3234 one = (PyLongObject *) PyLong_FromLong(1L);
3235 if (one == NULL ||
3236 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3237 Py_DECREF(mod);
3238 Py_DECREF(div);
3239 Py_XDECREF(one);
3240 return -1;
3241 }
3242 Py_DECREF(one);
3243 Py_DECREF(div);
3244 div = temp;
3245 }
3246 if (pdiv != NULL)
3247 *pdiv = div;
3248 else
3249 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 if (pmod != NULL)
3252 *pmod = mod;
3253 else
3254 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003257}
3258
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003259static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003260long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 CHECK_BINOP(a, b);
3265 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3266 div = NULL;
3267 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003268}
3269
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003270/* PyLong/PyLong -> float, with correctly rounded result. */
3271
3272#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3273#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003275static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003276long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 PyLongObject *a, *b, *x;
3279 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3280 digit mask, low;
3281 int inexact, negate, a_is_small, b_is_small;
3282 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 CHECK_BINOP(v, w);
3285 a = (PyLongObject *)v;
3286 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 /*
3289 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3292 1. choose a suitable integer 'shift'
3293 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3294 3. adjust x for correct rounding
3295 4. convert x to a double dx with the same value
3296 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3301 returns either 0.0 or -0.0, depending on the sign of b. For a and
3302 b both nonzero, ignore signs of a and b, and add the sign back in
3303 at the end. Now write a_bits and b_bits for the bit lengths of a
3304 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3305 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3310 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3311 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3312 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 1. The integer 'shift' is chosen so that x has the right number of
3317 bits for a double, plus two or three extra bits that will be used
3318 in the rounding decisions. Writing a_bits and b_bits for the
3319 number of significant bits in a and b respectively, a
3320 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 This is fine in the usual case, but if a/b is smaller than the
3325 smallest normal float then it can lead to double rounding on an
3326 IEEE 754 platform, giving incorrectly rounded results. So we
3327 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 2. The quantity x is computed by first shifting a (left -shift bits
3332 if shift <= 0, right shift bits if shift > 0) and then dividing by
3333 b. For both the shift and the division, we keep track of whether
3334 the result is inexact, in a flag 'inexact'; this information is
3335 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 With the choice of shift above, together with our assumption that
3338 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3339 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3342 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 For float representability, we need x/2**extra_bits <
3347 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3348 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 To round, we just modify the bottom digit of x in-place; this can
3353 end up giving a digit with value > PyLONG_MASK, but that's not a
3354 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 With the original choices for shift above, extra_bits will always
3357 be 2 or 3. Then rounding under the round-half-to-even rule, we
3358 round up iff the most significant of the extra bits is 1, and
3359 either: (a) the computation of x in step 2 had an inexact result,
3360 or (b) at least one other of the extra bits is 1, or (c) the least
3361 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 4. Conversion to a double is straightforward; all floating-point
3364 operations involved in the conversion are exact, so there's no
3365 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3368 The result will always be exactly representable as a double, except
3369 in the case that it overflows. To avoid dependence on the exact
3370 behaviour of ldexp on overflow, we check for overflow before
3371 applying ldexp. The result of ldexp is adjusted for sign before
3372 returning.
3373 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 /* Reduce to case where a and b are both positive. */
3376 a_size = ABS(Py_SIZE(a));
3377 b_size = ABS(Py_SIZE(b));
3378 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3379 if (b_size == 0) {
3380 PyErr_SetString(PyExc_ZeroDivisionError,
3381 "division by zero");
3382 goto error;
3383 }
3384 if (a_size == 0)
3385 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 /* Fast path for a and b small (exactly representable in a double).
3388 Relies on floating-point division being correctly rounded; results
3389 may be subject to double rounding on x86 machines that operate with
3390 the x87 FPU set to 64-bit precision. */
3391 a_is_small = a_size <= MANT_DIG_DIGITS ||
3392 (a_size == MANT_DIG_DIGITS+1 &&
3393 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3394 b_is_small = b_size <= MANT_DIG_DIGITS ||
3395 (b_size == MANT_DIG_DIGITS+1 &&
3396 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3397 if (a_is_small && b_is_small) {
3398 double da, db;
3399 da = a->ob_digit[--a_size];
3400 while (a_size > 0)
3401 da = da * PyLong_BASE + a->ob_digit[--a_size];
3402 db = b->ob_digit[--b_size];
3403 while (b_size > 0)
3404 db = db * PyLong_BASE + b->ob_digit[--b_size];
3405 result = da / db;
3406 goto success;
3407 }
Tim Peterse2a60002001-09-04 06:17:36 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 /* Catch obvious cases of underflow and overflow */
3410 diff = a_size - b_size;
3411 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3412 /* Extreme overflow */
3413 goto overflow;
3414 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3415 /* Extreme underflow */
3416 goto underflow_or_zero;
3417 /* Next line is now safe from overflowing a Py_ssize_t */
3418 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3419 bits_in_digit(b->ob_digit[b_size - 1]);
3420 /* Now diff = a_bits - b_bits. */
3421 if (diff > DBL_MAX_EXP)
3422 goto overflow;
3423 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3424 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 /* Choose value for shift; see comments for step 1 above. */
3427 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 /* x = abs(a * 2**-shift) */
3432 if (shift <= 0) {
3433 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3434 digit rem;
3435 /* x = a << -shift */
3436 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3437 /* In practice, it's probably impossible to end up
3438 here. Both a and b would have to be enormous,
3439 using close to SIZE_T_MAX bytes of memory each. */
3440 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003441 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 goto error;
3443 }
3444 x = _PyLong_New(a_size + shift_digits + 1);
3445 if (x == NULL)
3446 goto error;
3447 for (i = 0; i < shift_digits; i++)
3448 x->ob_digit[i] = 0;
3449 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3450 a_size, -shift % PyLong_SHIFT);
3451 x->ob_digit[a_size + shift_digits] = rem;
3452 }
3453 else {
3454 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3455 digit rem;
3456 /* x = a >> shift */
3457 assert(a_size >= shift_digits);
3458 x = _PyLong_New(a_size - shift_digits);
3459 if (x == NULL)
3460 goto error;
3461 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3462 a_size - shift_digits, shift % PyLong_SHIFT);
3463 /* set inexact if any of the bits shifted out is nonzero */
3464 if (rem)
3465 inexact = 1;
3466 while (!inexact && shift_digits > 0)
3467 if (a->ob_digit[--shift_digits])
3468 inexact = 1;
3469 }
3470 long_normalize(x);
3471 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3474 reference to x, so it's safe to modify it in-place. */
3475 if (b_size == 1) {
3476 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3477 b->ob_digit[0]);
3478 long_normalize(x);
3479 if (rem)
3480 inexact = 1;
3481 }
3482 else {
3483 PyLongObject *div, *rem;
3484 div = x_divrem(x, b, &rem);
3485 Py_DECREF(x);
3486 x = div;
3487 if (x == NULL)
3488 goto error;
3489 if (Py_SIZE(rem))
3490 inexact = 1;
3491 Py_DECREF(rem);
3492 }
3493 x_size = ABS(Py_SIZE(x));
3494 assert(x_size > 0); /* result of division is never zero */
3495 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 /* The number of extra bits that have to be rounded away. */
3498 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3499 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 /* Round by directly modifying the low digit of x. */
3502 mask = (digit)1 << (extra_bits - 1);
3503 low = x->ob_digit[0] | inexact;
3504 if (low & mask && low & (3*mask-1))
3505 low += mask;
3506 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 /* Convert x to a double dx; the conversion is exact. */
3509 dx = x->ob_digit[--x_size];
3510 while (x_size > 0)
3511 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3512 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 /* Check whether ldexp result will overflow a double. */
3515 if (shift + x_bits >= DBL_MAX_EXP &&
3516 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3517 goto overflow;
3518 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003519
3520 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003522
3523 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003525
3526 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 PyErr_SetString(PyExc_OverflowError,
3528 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003531}
3532
3533static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003534long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 CHECK_BINOP(a, b);
3539
3540 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3541 mod = NULL;
3542 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003543}
3544
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003545static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003546long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 PyLongObject *div, *mod;
3549 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3554 return NULL;
3555 }
3556 z = PyTuple_New(2);
3557 if (z != NULL) {
3558 PyTuple_SetItem(z, 0, (PyObject *) div);
3559 PyTuple_SetItem(z, 1, (PyObject *) mod);
3560 }
3561 else {
3562 Py_DECREF(div);
3563 Py_DECREF(mod);
3564 }
3565 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003566}
3567
Tim Peters47e52ee2004-08-30 02:44:38 +00003568/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003569static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003570long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3573 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 PyLongObject *z = NULL; /* accumulated result */
3576 Py_ssize_t i, j, k; /* counters */
3577 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 /* 5-ary values. If the exponent is large enough, table is
3580 * precomputed so that table[i] == a**i % c for i in range(32).
3581 */
3582 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3583 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 /* a, b, c = v, w, x */
3586 CHECK_BINOP(v, w);
3587 a = (PyLongObject*)v; Py_INCREF(a);
3588 b = (PyLongObject*)w; Py_INCREF(b);
3589 if (PyLong_Check(x)) {
3590 c = (PyLongObject *)x;
3591 Py_INCREF(x);
3592 }
3593 else if (x == Py_None)
3594 c = NULL;
3595 else {
3596 Py_DECREF(a);
3597 Py_DECREF(b);
3598 Py_INCREF(Py_NotImplemented);
3599 return Py_NotImplemented;
3600 }
Tim Peters4c483c42001-09-05 06:24:58 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3603 if (c) {
3604 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003605 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 goto Error;
3607 }
3608 else {
3609 /* else return a float. This works because we know
3610 that this calls float_pow() which converts its
3611 arguments to double. */
3612 Py_DECREF(a);
3613 Py_DECREF(b);
3614 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3615 }
3616 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 if (c) {
3619 /* if modulus == 0:
3620 raise ValueError() */
3621 if (Py_SIZE(c) == 0) {
3622 PyErr_SetString(PyExc_ValueError,
3623 "pow() 3rd argument cannot be 0");
3624 goto Error;
3625 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 /* if modulus < 0:
3628 negativeOutput = True
3629 modulus = -modulus */
3630 if (Py_SIZE(c) < 0) {
3631 negativeOutput = 1;
3632 temp = (PyLongObject *)_PyLong_Copy(c);
3633 if (temp == NULL)
3634 goto Error;
3635 Py_DECREF(c);
3636 c = temp;
3637 temp = NULL;
3638 NEGATE(c);
3639 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 /* if modulus == 1:
3642 return 0 */
3643 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3644 z = (PyLongObject *)PyLong_FromLong(0L);
3645 goto Done;
3646 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* if base < 0:
3649 base = base % modulus
3650 Having the base positive just makes things easier. */
3651 if (Py_SIZE(a) < 0) {
3652 if (l_divmod(a, c, NULL, &temp) < 0)
3653 goto Error;
3654 Py_DECREF(a);
3655 a = temp;
3656 temp = NULL;
3657 }
3658 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 /* At this point a, b, and c are guaranteed non-negative UNLESS
3661 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 z = (PyLongObject *)PyLong_FromLong(1L);
3664 if (z == NULL)
3665 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 /* Perform a modular reduction, X = X % c, but leave X alone if c
3668 * is NULL.
3669 */
3670#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003671 do { \
3672 if (c != NULL) { \
3673 if (l_divmod(X, c, NULL, &temp) < 0) \
3674 goto Error; \
3675 Py_XDECREF(X); \
3676 X = temp; \
3677 temp = NULL; \
3678 } \
3679 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 /* Multiply two values, then reduce the result:
3682 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003683#define MULT(X, Y, result) \
3684 do { \
3685 temp = (PyLongObject *)long_mul(X, Y); \
3686 if (temp == NULL) \
3687 goto Error; \
3688 Py_XDECREF(result); \
3689 result = temp; \
3690 temp = NULL; \
3691 REDUCE(result); \
3692 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3695 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3696 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3697 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3698 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003701 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003703 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 }
3705 }
3706 }
3707 else {
3708 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3709 Py_INCREF(z); /* still holds 1L */
3710 table[0] = z;
3711 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003712 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3715 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3718 const int index = (bi >> j) & 0x1f;
3719 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003720 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003722 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 }
3724 }
3725 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 if (negativeOutput && (Py_SIZE(z) != 0)) {
3728 temp = (PyLongObject *)long_sub(z, c);
3729 if (temp == NULL)
3730 goto Error;
3731 Py_DECREF(z);
3732 z = temp;
3733 temp = NULL;
3734 }
3735 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003736
Mark Dickinson22b20182010-05-10 21:27:53 +00003737 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 if (z != NULL) {
3739 Py_DECREF(z);
3740 z = NULL;
3741 }
3742 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003743 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3745 for (i = 0; i < 32; ++i)
3746 Py_XDECREF(table[i]);
3747 }
3748 Py_DECREF(a);
3749 Py_DECREF(b);
3750 Py_XDECREF(c);
3751 Py_XDECREF(temp);
3752 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003753}
3754
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003755static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003756long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 /* Implement ~x as -(x+1) */
3759 PyLongObject *x;
3760 PyLongObject *w;
3761 if (ABS(Py_SIZE(v)) <=1)
3762 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3763 w = (PyLongObject *)PyLong_FromLong(1L);
3764 if (w == NULL)
3765 return NULL;
3766 x = (PyLongObject *) long_add(v, w);
3767 Py_DECREF(w);
3768 if (x == NULL)
3769 return NULL;
3770 Py_SIZE(x) = -(Py_SIZE(x));
3771 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003772}
3773
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003774static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003775long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 PyLongObject *z;
3778 if (ABS(Py_SIZE(v)) <= 1)
3779 return PyLong_FromLong(-MEDIUM_VALUE(v));
3780 z = (PyLongObject *)_PyLong_Copy(v);
3781 if (z != NULL)
3782 Py_SIZE(z) = -(Py_SIZE(v));
3783 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003784}
3785
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003786static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003787long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 if (Py_SIZE(v) < 0)
3790 return long_neg(v);
3791 else
3792 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003793}
3794
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003795static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003796long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003799}
3800
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003801static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003802long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 PyLongObject *z = NULL;
3805 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3806 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 if (Py_SIZE(a) < 0) {
3811 /* Right shifting negative numbers is harder */
3812 PyLongObject *a1, *a2;
3813 a1 = (PyLongObject *) long_invert(a);
3814 if (a1 == NULL)
3815 goto rshift_error;
3816 a2 = (PyLongObject *) long_rshift(a1, b);
3817 Py_DECREF(a1);
3818 if (a2 == NULL)
3819 goto rshift_error;
3820 z = (PyLongObject *) long_invert(a2);
3821 Py_DECREF(a2);
3822 }
3823 else {
3824 shiftby = PyLong_AsSsize_t((PyObject *)b);
3825 if (shiftby == -1L && PyErr_Occurred())
3826 goto rshift_error;
3827 if (shiftby < 0) {
3828 PyErr_SetString(PyExc_ValueError,
3829 "negative shift count");
3830 goto rshift_error;
3831 }
3832 wordshift = shiftby / PyLong_SHIFT;
3833 newsize = ABS(Py_SIZE(a)) - wordshift;
3834 if (newsize <= 0)
3835 return PyLong_FromLong(0);
3836 loshift = shiftby % PyLong_SHIFT;
3837 hishift = PyLong_SHIFT - loshift;
3838 lomask = ((digit)1 << hishift) - 1;
3839 himask = PyLong_MASK ^ lomask;
3840 z = _PyLong_New(newsize);
3841 if (z == NULL)
3842 goto rshift_error;
3843 if (Py_SIZE(a) < 0)
3844 Py_SIZE(z) = -(Py_SIZE(z));
3845 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3846 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3847 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003848 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003849 }
3850 z = long_normalize(z);
3851 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003852 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003853 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003854
Guido van Rossumc6913e71991-11-19 20:26:46 +00003855}
3856
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003857static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003858long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 /* This version due to Tim Peters */
3861 PyLongObject *a = (PyLongObject*)v;
3862 PyLongObject *b = (PyLongObject*)w;
3863 PyLongObject *z = NULL;
3864 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3865 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 shiftby = PyLong_AsSsize_t((PyObject *)b);
3870 if (shiftby == -1L && PyErr_Occurred())
3871 goto lshift_error;
3872 if (shiftby < 0) {
3873 PyErr_SetString(PyExc_ValueError, "negative shift count");
3874 goto lshift_error;
3875 }
3876 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3877 wordshift = shiftby / PyLong_SHIFT;
3878 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 oldsize = ABS(Py_SIZE(a));
3881 newsize = oldsize + wordshift;
3882 if (remshift)
3883 ++newsize;
3884 z = _PyLong_New(newsize);
3885 if (z == NULL)
3886 goto lshift_error;
3887 if (Py_SIZE(a) < 0)
3888 NEGATE(z);
3889 for (i = 0; i < wordshift; i++)
3890 z->ob_digit[i] = 0;
3891 accum = 0;
3892 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3893 accum |= (twodigits)a->ob_digit[j] << remshift;
3894 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3895 accum >>= PyLong_SHIFT;
3896 }
3897 if (remshift)
3898 z->ob_digit[newsize-1] = (digit)accum;
3899 else
3900 assert(!accum);
3901 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003902 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003904}
3905
Mark Dickinson27a87a22009-10-25 20:43:34 +00003906/* Compute two's complement of digit vector a[0:m], writing result to
3907 z[0:m]. The digit vector a need not be normalized, but should not
3908 be entirely zero. a and z may point to the same digit vector. */
3909
3910static void
3911v_complement(digit *z, digit *a, Py_ssize_t m)
3912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 Py_ssize_t i;
3914 digit carry = 1;
3915 for (i = 0; i < m; ++i) {
3916 carry += a[i] ^ PyLong_MASK;
3917 z[i] = carry & PyLong_MASK;
3918 carry >>= PyLong_SHIFT;
3919 }
3920 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003921}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003922
3923/* Bitwise and/xor/or operations */
3924
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003925static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003926long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003928 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 int nega, negb, negz;
3931 Py_ssize_t size_a, size_b, size_z, i;
3932 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003934 /* Bitwise operations for negative numbers operate as though
3935 on a two's complement representation. So convert arguments
3936 from sign-magnitude to two's complement, and convert the
3937 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003939 /* If a is negative, replace it by its two's complement. */
3940 size_a = ABS(Py_SIZE(a));
3941 nega = Py_SIZE(a) < 0;
3942 if (nega) {
3943 z = _PyLong_New(size_a);
3944 if (z == NULL)
3945 return NULL;
3946 v_complement(z->ob_digit, a->ob_digit, size_a);
3947 a = z;
3948 }
3949 else
3950 /* Keep reference count consistent. */
3951 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 /* Same for b. */
3954 size_b = ABS(Py_SIZE(b));
3955 negb = Py_SIZE(b) < 0;
3956 if (negb) {
3957 z = _PyLong_New(size_b);
3958 if (z == NULL) {
3959 Py_DECREF(a);
3960 return NULL;
3961 }
3962 v_complement(z->ob_digit, b->ob_digit, size_b);
3963 b = z;
3964 }
3965 else
3966 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 /* Swap a and b if necessary to ensure size_a >= size_b. */
3969 if (size_a < size_b) {
3970 z = a; a = b; b = z;
3971 size_z = size_a; size_a = size_b; size_b = size_z;
3972 negz = nega; nega = negb; negb = negz;
3973 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* JRH: The original logic here was to allocate the result value (z)
3976 as the longer of the two operands. However, there are some cases
3977 where the result is guaranteed to be shorter than that: AND of two
3978 positives, OR of two negatives: use the shorter number. AND with
3979 mixed signs: use the positive number. OR with mixed signs: use the
3980 negative number.
3981 */
3982 switch (op) {
3983 case '^':
3984 negz = nega ^ negb;
3985 size_z = size_a;
3986 break;
3987 case '&':
3988 negz = nega & negb;
3989 size_z = negb ? size_a : size_b;
3990 break;
3991 case '|':
3992 negz = nega | negb;
3993 size_z = negb ? size_b : size_a;
3994 break;
3995 default:
3996 PyErr_BadArgument();
3997 return NULL;
3998 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 /* We allow an extra digit if z is negative, to make sure that
4001 the final two's complement of z doesn't overflow. */
4002 z = _PyLong_New(size_z + negz);
4003 if (z == NULL) {
4004 Py_DECREF(a);
4005 Py_DECREF(b);
4006 return NULL;
4007 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 /* Compute digits for overlap of a and b. */
4010 switch(op) {
4011 case '&':
4012 for (i = 0; i < size_b; ++i)
4013 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4014 break;
4015 case '|':
4016 for (i = 0; i < size_b; ++i)
4017 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4018 break;
4019 case '^':
4020 for (i = 0; i < size_b; ++i)
4021 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4022 break;
4023 default:
4024 PyErr_BadArgument();
4025 return NULL;
4026 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 /* Copy any remaining digits of a, inverting if necessary. */
4029 if (op == '^' && negb)
4030 for (; i < size_z; ++i)
4031 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4032 else if (i < size_z)
4033 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4034 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004036 /* Complement result if negative. */
4037 if (negz) {
4038 Py_SIZE(z) = -(Py_SIZE(z));
4039 z->ob_digit[size_z] = PyLong_MASK;
4040 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4041 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 Py_DECREF(a);
4044 Py_DECREF(b);
4045 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004046}
4047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004048static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004049long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 PyObject *c;
4052 CHECK_BINOP(a, b);
4053 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4054 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004055}
4056
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004057static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004058long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 PyObject *c;
4061 CHECK_BINOP(a, b);
4062 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4063 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004064}
4065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004066static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004067long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 PyObject *c;
4070 CHECK_BINOP(a, b);
4071 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4072 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004073}
4074
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004075static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004076long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 if (PyLong_CheckExact(v))
4079 Py_INCREF(v);
4080 else
4081 v = _PyLong_Copy((PyLongObject *)v);
4082 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004083}
4084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004085static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004086long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 double result;
4089 result = PyLong_AsDouble(v);
4090 if (result == -1.0 && PyErr_Occurred())
4091 return NULL;
4092 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004093}
4094
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004095static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004096long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004097
Tim Peters6d6c1a32001-08-02 04:15:00 +00004098static PyObject *
4099long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4100{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004101 PyObject *obase = NULL, *x = NULL;
4102 long base;
4103 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 if (type != &PyLong_Type)
4107 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004108 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4109 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 return NULL;
4111 if (x == NULL)
4112 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004113 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004115
4116 base = PyLong_AsLongAndOverflow(obase, &overflow);
4117 if (base == -1 && PyErr_Occurred())
4118 return NULL;
4119 if (overflow || (base != 0 && base < 2) || base > 36) {
4120 PyErr_SetString(PyExc_ValueError,
4121 "int() arg 2 must be >= 2 and <= 36");
4122 return NULL;
4123 }
4124
4125 if (PyUnicode_Check(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4127 PyUnicode_GET_SIZE(x),
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004128 (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4130 /* Since PyLong_FromString doesn't have a length parameter,
4131 * check here for possible NULs in the string. */
4132 char *string;
4133 Py_ssize_t size = Py_SIZE(x);
4134 if (PyByteArray_Check(x))
4135 string = PyByteArray_AS_STRING(x);
4136 else
4137 string = PyBytes_AS_STRING(x);
4138 if (strlen(string) != (size_t)size) {
4139 /* We only see this if there's a null byte in x,
4140 x is a bytes or buffer, *and* a base is given. */
4141 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004142 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004143 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 return NULL;
4145 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004146 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 }
4148 else {
4149 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004150 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 return NULL;
4152 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004153}
4154
Guido van Rossumbef14172001-08-29 15:47:46 +00004155/* Wimpy, slow approach to tp_new calls for subtypes of long:
4156 first create a regular long from whatever arguments we got,
4157 then allocate a subtype instance and initialize it from
4158 the regular long. The regular long is then thrown away.
4159*/
4160static PyObject *
4161long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 PyLongObject *tmp, *newobj;
4164 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 assert(PyType_IsSubtype(type, &PyLong_Type));
4167 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4168 if (tmp == NULL)
4169 return NULL;
4170 assert(PyLong_CheckExact(tmp));
4171 n = Py_SIZE(tmp);
4172 if (n < 0)
4173 n = -n;
4174 newobj = (PyLongObject *)type->tp_alloc(type, n);
4175 if (newobj == NULL) {
4176 Py_DECREF(tmp);
4177 return NULL;
4178 }
4179 assert(PyLong_Check(newobj));
4180 Py_SIZE(newobj) = Py_SIZE(tmp);
4181 for (i = 0; i < n; i++)
4182 newobj->ob_digit[i] = tmp->ob_digit[i];
4183 Py_DECREF(tmp);
4184 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004185}
4186
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004187static PyObject *
4188long_getnewargs(PyLongObject *v)
4189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004191}
4192
Guido van Rossumb43daf72007-08-01 18:08:08 +00004193static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004194long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004196}
4197
4198static PyObject *
4199long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004201}
4202
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004203static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004204long__format__(PyObject *self, PyObject *args)
4205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004206 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004208 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4209 return NULL;
4210 return _PyLong_FormatAdvanced(self,
4211 PyUnicode_AS_UNICODE(format_spec),
4212 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004213}
4214
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004215/* Return a pair (q, r) such that a = b * q + r, and
4216 abs(r) <= abs(b)/2, with equality possible only if q is even.
4217 In other words, q == a / b, rounded to the nearest integer using
4218 round-half-to-even. */
4219
4220PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004221_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004222{
4223 PyLongObject *quo = NULL, *rem = NULL;
4224 PyObject *one = NULL, *twice_rem, *result, *temp;
4225 int cmp, quo_is_odd, quo_is_neg;
4226
4227 /* Equivalent Python code:
4228
4229 def divmod_near(a, b):
4230 q, r = divmod(a, b)
4231 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4232 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4233 # positive, 2 * r < b if b negative.
4234 greater_than_half = 2*r > b if b > 0 else 2*r < b
4235 exactly_half = 2*r == b
4236 if greater_than_half or exactly_half and q % 2 == 1:
4237 q += 1
4238 r -= b
4239 return q, r
4240
4241 */
4242 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4243 PyErr_SetString(PyExc_TypeError,
4244 "non-integer arguments in division");
4245 return NULL;
4246 }
4247
4248 /* Do a and b have different signs? If so, quotient is negative. */
4249 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4250
4251 one = PyLong_FromLong(1L);
4252 if (one == NULL)
4253 return NULL;
4254
4255 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4256 goto error;
4257
4258 /* compare twice the remainder with the divisor, to see
4259 if we need to adjust the quotient and remainder */
4260 twice_rem = long_lshift((PyObject *)rem, one);
4261 if (twice_rem == NULL)
4262 goto error;
4263 if (quo_is_neg) {
4264 temp = long_neg((PyLongObject*)twice_rem);
4265 Py_DECREF(twice_rem);
4266 twice_rem = temp;
4267 if (twice_rem == NULL)
4268 goto error;
4269 }
4270 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4271 Py_DECREF(twice_rem);
4272
4273 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4274 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4275 /* fix up quotient */
4276 if (quo_is_neg)
4277 temp = long_sub(quo, (PyLongObject *)one);
4278 else
4279 temp = long_add(quo, (PyLongObject *)one);
4280 Py_DECREF(quo);
4281 quo = (PyLongObject *)temp;
4282 if (quo == NULL)
4283 goto error;
4284 /* and remainder */
4285 if (quo_is_neg)
4286 temp = long_add(rem, (PyLongObject *)b);
4287 else
4288 temp = long_sub(rem, (PyLongObject *)b);
4289 Py_DECREF(rem);
4290 rem = (PyLongObject *)temp;
4291 if (rem == NULL)
4292 goto error;
4293 }
4294
4295 result = PyTuple_New(2);
4296 if (result == NULL)
4297 goto error;
4298
4299 /* PyTuple_SET_ITEM steals references */
4300 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4301 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4302 Py_DECREF(one);
4303 return result;
4304
4305 error:
4306 Py_XDECREF(quo);
4307 Py_XDECREF(rem);
4308 Py_XDECREF(one);
4309 return NULL;
4310}
4311
Eric Smith8c663262007-08-25 02:26:07 +00004312static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004313long_round(PyObject *self, PyObject *args)
4314{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004315 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004316
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004317 /* To round an integer m to the nearest 10**n (n positive), we make use of
4318 * the divmod_near operation, defined by:
4319 *
4320 * divmod_near(a, b) = (q, r)
4321 *
4322 * where q is the nearest integer to the quotient a / b (the
4323 * nearest even integer in the case of a tie) and r == a - q * b.
4324 * Hence q * b = a - r is the nearest multiple of b to a,
4325 * preferring even multiples in the case of a tie.
4326 *
4327 * So the nearest multiple of 10**n to m is:
4328 *
4329 * m - divmod_near(m, 10**n)[1].
4330 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4332 return NULL;
4333 if (o_ndigits == NULL)
4334 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004335
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004336 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 if (ndigits == NULL)
4338 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004339
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004340 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004341 if (Py_SIZE(ndigits) >= 0) {
4342 Py_DECREF(ndigits);
4343 return long_long(self);
4344 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004345
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004346 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4347 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004349 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004351 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004352
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004353 result = PyLong_FromLong(10L);
4354 if (result == NULL) {
4355 Py_DECREF(ndigits);
4356 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004358
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004359 temp = long_pow(result, ndigits, Py_None);
4360 Py_DECREF(ndigits);
4361 Py_DECREF(result);
4362 result = temp;
4363 if (result == NULL)
4364 return NULL;
4365
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004366 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004367 Py_DECREF(result);
4368 result = temp;
4369 if (result == NULL)
4370 return NULL;
4371
4372 temp = long_sub((PyLongObject *)self,
4373 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4374 Py_DECREF(result);
4375 result = temp;
4376
4377 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004378}
4379
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004380static PyObject *
4381long_sizeof(PyLongObject *v)
4382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4386 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004387}
4388
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004389static PyObject *
4390long_bit_length(PyLongObject *v)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 PyLongObject *result, *x, *y;
4393 Py_ssize_t ndigits, msd_bits = 0;
4394 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 assert(v != NULL);
4397 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 ndigits = ABS(Py_SIZE(v));
4400 if (ndigits == 0)
4401 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 msd = v->ob_digit[ndigits-1];
4404 while (msd >= 32) {
4405 msd_bits += 6;
4406 msd >>= 6;
4407 }
4408 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4411 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 /* expression above may overflow; use Python integers instead */
4414 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4415 if (result == NULL)
4416 return NULL;
4417 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4418 if (x == NULL)
4419 goto error;
4420 y = (PyLongObject *)long_mul(result, x);
4421 Py_DECREF(x);
4422 if (y == NULL)
4423 goto error;
4424 Py_DECREF(result);
4425 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4428 if (x == NULL)
4429 goto error;
4430 y = (PyLongObject *)long_add(result, x);
4431 Py_DECREF(x);
4432 if (y == NULL)
4433 goto error;
4434 Py_DECREF(result);
4435 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004438
Mark Dickinson22b20182010-05-10 21:27:53 +00004439 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 Py_DECREF(result);
4441 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004442}
4443
4444PyDoc_STRVAR(long_bit_length_doc,
4445"int.bit_length() -> int\n\
4446\n\
4447Number of bits necessary to represent self in binary.\n\
4448>>> bin(37)\n\
4449'0b100101'\n\
4450>>> (37).bit_length()\n\
44516");
4452
Christian Heimes53876d92008-04-19 00:31:39 +00004453#if 0
4454static PyObject *
4455long_is_finite(PyObject *v)
4456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004458}
4459#endif
4460
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004461
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004462static PyObject *
4463long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 PyObject *byteorder_str;
4466 PyObject *is_signed_obj = NULL;
4467 Py_ssize_t length;
4468 int little_endian;
4469 int is_signed;
4470 PyObject *bytes;
4471 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4474 &length, &byteorder_str,
4475 &is_signed_obj))
4476 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 if (args != NULL && Py_SIZE(args) > 2) {
4479 PyErr_SetString(PyExc_TypeError,
4480 "'signed' is a keyword-only argument");
4481 return NULL;
4482 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4485 little_endian = 1;
4486 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4487 little_endian = 0;
4488 else {
4489 PyErr_SetString(PyExc_ValueError,
4490 "byteorder must be either 'little' or 'big'");
4491 return NULL;
4492 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 if (is_signed_obj != NULL) {
4495 int cmp = PyObject_IsTrue(is_signed_obj);
4496 if (cmp < 0)
4497 return NULL;
4498 is_signed = cmp ? 1 : 0;
4499 }
4500 else {
4501 /* If the signed argument was omitted, use False as the
4502 default. */
4503 is_signed = 0;
4504 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 if (length < 0) {
4507 PyErr_SetString(PyExc_ValueError,
4508 "length argument must be non-negative");
4509 return NULL;
4510 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 bytes = PyBytes_FromStringAndSize(NULL, length);
4513 if (bytes == NULL)
4514 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4517 length, little_endian, is_signed) < 0) {
4518 Py_DECREF(bytes);
4519 return NULL;
4520 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004523}
4524
Mark Dickinson078c2532010-01-30 18:06:17 +00004525PyDoc_STRVAR(long_to_bytes_doc,
4526"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004527\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004528Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004529\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004531raised if the integer is not representable with the given number of\n\
4532bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004533\n\
4534The byteorder argument determines the byte order used to represent the\n\
4535integer. If byteorder is 'big', the most significant byte is at the\n\
4536beginning of the byte array. If byteorder is 'little', the most\n\
4537significant byte is at the end of the byte array. To request the native\n\
4538byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4539\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004540The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004542is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004543
4544static PyObject *
4545long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 PyObject *byteorder_str;
4548 PyObject *is_signed_obj = NULL;
4549 int little_endian;
4550 int is_signed;
4551 PyObject *obj;
4552 PyObject *bytes;
4553 PyObject *long_obj;
4554 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4557 &obj, &byteorder_str,
4558 &is_signed_obj))
4559 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 if (args != NULL && Py_SIZE(args) > 2) {
4562 PyErr_SetString(PyExc_TypeError,
4563 "'signed' is a keyword-only argument");
4564 return NULL;
4565 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4568 little_endian = 1;
4569 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4570 little_endian = 0;
4571 else {
4572 PyErr_SetString(PyExc_ValueError,
4573 "byteorder must be either 'little' or 'big'");
4574 return NULL;
4575 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 if (is_signed_obj != NULL) {
4578 int cmp = PyObject_IsTrue(is_signed_obj);
4579 if (cmp < 0)
4580 return NULL;
4581 is_signed = cmp ? 1 : 0;
4582 }
4583 else {
4584 /* If the signed argument was omitted, use False as the
4585 default. */
4586 is_signed = 0;
4587 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 bytes = PyObject_Bytes(obj);
4590 if (bytes == NULL)
4591 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 long_obj = _PyLong_FromByteArray(
4594 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4595 little_endian, is_signed);
4596 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 /* If from_bytes() was used on subclass, allocate new subclass
4599 * instance, initialize it with decoded long value and return it.
4600 */
4601 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4602 PyLongObject *newobj;
4603 int i;
4604 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 newobj = (PyLongObject *)type->tp_alloc(type, n);
4607 if (newobj == NULL) {
4608 Py_DECREF(long_obj);
4609 return NULL;
4610 }
4611 assert(PyLong_Check(newobj));
4612 Py_SIZE(newobj) = Py_SIZE(long_obj);
4613 for (i = 0; i < n; i++) {
4614 newobj->ob_digit[i] =
4615 ((PyLongObject *)long_obj)->ob_digit[i];
4616 }
4617 Py_DECREF(long_obj);
4618 return (PyObject *)newobj;
4619 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004622}
4623
Mark Dickinson078c2532010-01-30 18:06:17 +00004624PyDoc_STRVAR(long_from_bytes_doc,
4625"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4626\n\
4627Return the integer represented by the given array of bytes.\n\
4628\n\
4629The bytes argument must either support the buffer protocol or be an\n\
4630iterable object producing bytes. Bytes and bytearray are examples of\n\
4631built-in objects that support the buffer protocol.\n\
4632\n\
4633The byteorder argument determines the byte order used to represent the\n\
4634integer. If byteorder is 'big', the most significant byte is at the\n\
4635beginning of the byte array. If byteorder is 'little', the most\n\
4636significant byte is at the end of the byte array. To request the native\n\
4637byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4638\n\
4639The signed keyword-only argument indicates whether two's complement is\n\
4640used to represent the integer.");
4641
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004642static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4644 "Returns self, the complex conjugate of any int."},
4645 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4646 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004647#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4649 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004650#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 {"to_bytes", (PyCFunction)long_to_bytes,
4652 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4653 {"from_bytes", (PyCFunction)long_from_bytes,
4654 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4655 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4656 "Truncating an Integral returns itself."},
4657 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4658 "Flooring an Integral returns itself."},
4659 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4660 "Ceiling of an Integral returns itself."},
4661 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4662 "Rounding an Integral returns itself.\n"
4663 "Rounding with an ndigits argument also returns an integer."},
4664 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4665 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4666 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4667 "Returns size in memory, in bytes"},
4668 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004669};
4670
Guido van Rossumb43daf72007-08-01 18:08:08 +00004671static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004672 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004673 (getter)long_long, (setter)NULL,
4674 "the real part of a complex number",
4675 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004676 {"imag",
4677 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004678 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004679 NULL},
4680 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004681 (getter)long_long, (setter)NULL,
4682 "the numerator of a rational number in lowest terms",
4683 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004684 {"denominator",
4685 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004686 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004687 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004688 {NULL} /* Sentinel */
4689};
4690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004691PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004692"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004693\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004694Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004695point argument will be truncated towards zero (this does not include a\n\
4696string representation of a floating point number!) When converting a\n\
4697string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004698converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004700static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004701 (binaryfunc)long_add, /*nb_add*/
4702 (binaryfunc)long_sub, /*nb_subtract*/
4703 (binaryfunc)long_mul, /*nb_multiply*/
4704 long_mod, /*nb_remainder*/
4705 long_divmod, /*nb_divmod*/
4706 long_pow, /*nb_power*/
4707 (unaryfunc)long_neg, /*nb_negative*/
4708 (unaryfunc)long_long, /*tp_positive*/
4709 (unaryfunc)long_abs, /*tp_absolute*/
4710 (inquiry)long_bool, /*tp_bool*/
4711 (unaryfunc)long_invert, /*nb_invert*/
4712 long_lshift, /*nb_lshift*/
4713 (binaryfunc)long_rshift, /*nb_rshift*/
4714 long_and, /*nb_and*/
4715 long_xor, /*nb_xor*/
4716 long_or, /*nb_or*/
4717 long_long, /*nb_int*/
4718 0, /*nb_reserved*/
4719 long_float, /*nb_float*/
4720 0, /* nb_inplace_add */
4721 0, /* nb_inplace_subtract */
4722 0, /* nb_inplace_multiply */
4723 0, /* nb_inplace_remainder */
4724 0, /* nb_inplace_power */
4725 0, /* nb_inplace_lshift */
4726 0, /* nb_inplace_rshift */
4727 0, /* nb_inplace_and */
4728 0, /* nb_inplace_xor */
4729 0, /* nb_inplace_or */
4730 long_div, /* nb_floor_divide */
4731 long_true_divide, /* nb_true_divide */
4732 0, /* nb_inplace_floor_divide */
4733 0, /* nb_inplace_true_divide */
4734 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004735};
4736
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004737PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4739 "int", /* tp_name */
4740 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4741 sizeof(digit), /* tp_itemsize */
4742 long_dealloc, /* tp_dealloc */
4743 0, /* tp_print */
4744 0, /* tp_getattr */
4745 0, /* tp_setattr */
4746 0, /* tp_reserved */
4747 long_to_decimal_string, /* tp_repr */
4748 &long_as_number, /* tp_as_number */
4749 0, /* tp_as_sequence */
4750 0, /* tp_as_mapping */
4751 (hashfunc)long_hash, /* tp_hash */
4752 0, /* tp_call */
4753 long_to_decimal_string, /* tp_str */
4754 PyObject_GenericGetAttr, /* tp_getattro */
4755 0, /* tp_setattro */
4756 0, /* tp_as_buffer */
4757 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4758 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4759 long_doc, /* tp_doc */
4760 0, /* tp_traverse */
4761 0, /* tp_clear */
4762 long_richcompare, /* tp_richcompare */
4763 0, /* tp_weaklistoffset */
4764 0, /* tp_iter */
4765 0, /* tp_iternext */
4766 long_methods, /* tp_methods */
4767 0, /* tp_members */
4768 long_getset, /* tp_getset */
4769 0, /* tp_base */
4770 0, /* tp_dict */
4771 0, /* tp_descr_get */
4772 0, /* tp_descr_set */
4773 0, /* tp_dictoffset */
4774 0, /* tp_init */
4775 0, /* tp_alloc */
4776 long_new, /* tp_new */
4777 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004778};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004779
Mark Dickinsonbd792642009-03-18 20:06:12 +00004780static PyTypeObject Int_InfoType;
4781
4782PyDoc_STRVAR(int_info__doc__,
4783"sys.int_info\n\
4784\n\
4785A struct sequence that holds information about Python's\n\
4786internal representation of integers. The attributes are read only.");
4787
4788static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004790 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004792};
4793
4794static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 "sys.int_info", /* name */
4796 int_info__doc__, /* doc */
4797 int_info_fields, /* fields */
4798 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004799};
4800
4801PyObject *
4802PyLong_GetInfo(void)
4803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 PyObject* int_info;
4805 int field = 0;
4806 int_info = PyStructSequence_New(&Int_InfoType);
4807 if (int_info == NULL)
4808 return NULL;
4809 PyStructSequence_SET_ITEM(int_info, field++,
4810 PyLong_FromLong(PyLong_SHIFT));
4811 PyStructSequence_SET_ITEM(int_info, field++,
4812 PyLong_FromLong(sizeof(digit)));
4813 if (PyErr_Occurred()) {
4814 Py_CLEAR(int_info);
4815 return NULL;
4816 }
4817 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004818}
4819
Guido van Rossumddefaf32007-01-14 03:31:43 +00004820int
4821_PyLong_Init(void)
4822{
4823#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 int ival, size;
4825 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4828 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4829 if (Py_TYPE(v) == &PyLong_Type) {
4830 /* The element is already initialized, most likely
4831 * the Python interpreter was initialized before.
4832 */
4833 Py_ssize_t refcnt;
4834 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4837 _Py_NewReference(op);
4838 /* _Py_NewReference sets the ref count to 1 but
4839 * the ref count might be larger. Set the refcnt
4840 * to the original refcnt + 1 */
4841 Py_REFCNT(op) = refcnt + 1;
4842 assert(Py_SIZE(op) == size);
4843 assert(v->ob_digit[0] == abs(ival));
4844 }
4845 else {
4846 PyObject_INIT(v, &PyLong_Type);
4847 }
4848 Py_SIZE(v) = size;
4849 v->ob_digit[0] = abs(ival);
4850 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004851#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 /* initialize int_info */
4853 if (Int_InfoType.tp_name == 0)
4854 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004857}
4858
4859void
4860PyLong_Fini(void)
4861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 /* Integers are currently statically allocated. Py_DECREF is not
4863 needed, but Python must forget about the reference or multiple
4864 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004865#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 int i;
4867 PyLongObject *v = small_ints;
4868 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4869 _Py_DEC_REFTOTAL;
4870 _Py_ForgetReference((PyObject*)v);
4871 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004872#endif
4873}