blob: ab49f28f532908659dca787513c4ba67ceaaca2e [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
33int quick_int_allocs, quick_neg_int_allocs;
34#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
159 sdigit ival = src->ob_digit[0];
160 if (Py_SIZE(src) < 0)
161 ival = -ival;
162 CHECK_SMALL_INT(ival);
163 }
164 result = _PyLong_New(i);
165 if (result != NULL) {
166 Py_SIZE(result) = Py_SIZE(src);
167 while (--i >= 0)
168 result->ob_digit[i] = src->ob_digit[i];
169 }
170 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000171}
172
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000173/* Create a new long int object from a C long int */
174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000176PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyLongObject *v;
179 unsigned long abs_ival;
180 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
181 int ndigits = 0;
182 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (ival < 0) {
187 /* negate: can't write this as abs_ival = -ival since that
188 invokes undefined behaviour when ival is LONG_MIN */
189 abs_ival = 0U-(unsigned long)ival;
190 sign = -1;
191 }
192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Fast path for single-digit ints */
197 if (!(abs_ival >> PyLong_SHIFT)) {
198 v = _PyLong_New(1);
199 if (v) {
200 Py_SIZE(v) = sign;
201 v->ob_digit[0] = Py_SAFE_DOWNCAST(
202 abs_ival, unsigned long, digit);
203 }
204 return (PyObject*)v;
205 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206
Mark Dickinson249b8982009-04-27 19:41:00 +0000207#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* 2 digits */
209 if (!(abs_ival >> 2*PyLong_SHIFT)) {
210 v = _PyLong_New(2);
211 if (v) {
212 Py_SIZE(v) = 2*sign;
213 v->ob_digit[0] = Py_SAFE_DOWNCAST(
214 abs_ival & PyLong_MASK, unsigned long, digit);
215 v->ob_digit[1] = Py_SAFE_DOWNCAST(
216 abs_ival >> PyLong_SHIFT, unsigned long, digit);
217 }
218 return (PyObject*)v;
219 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000220#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 /* Larger numbers: loop to determine number of digits */
223 t = abs_ival;
224 while (t) {
225 ++ndigits;
226 t >>= PyLong_SHIFT;
227 }
228 v = _PyLong_New(ndigits);
229 if (v != NULL) {
230 digit *p = v->ob_digit;
231 Py_SIZE(v) = ndigits*sign;
232 t = abs_ival;
233 while (t) {
234 *p++ = Py_SAFE_DOWNCAST(
235 t & PyLong_MASK, unsigned long, digit);
236 t >>= PyLong_SHIFT;
237 }
238 }
239 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240}
241
Guido van Rossum53756b11997-01-03 17:14:46 +0000242/* Create a new long int object from a C unsigned long int */
243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000245PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyLongObject *v;
248 unsigned long t;
249 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (ival < PyLong_BASE)
252 return PyLong_FromLong(ival);
253 /* Count the number of Python digits. */
254 t = (unsigned long)ival;
255 while (t) {
256 ++ndigits;
257 t >>= PyLong_SHIFT;
258 }
259 v = _PyLong_New(ndigits);
260 if (v != NULL) {
261 digit *p = v->ob_digit;
262 Py_SIZE(v) = ndigits;
263 while (ival) {
264 *p++ = (digit)(ival & PyLong_MASK);
265 ival >>= PyLong_SHIFT;
266 }
267 }
268 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000269}
270
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271/* Create a new long int object from a C double */
272
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 PyLongObject *v;
277 double frac;
278 int i, ndig, expo, neg;
279 neg = 0;
280 if (Py_IS_INFINITY(dval)) {
281 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000282 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
284 }
285 if (Py_IS_NAN(dval)) {
286 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000287 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return NULL;
289 }
290 if (dval < 0.0) {
291 neg = 1;
292 dval = -dval;
293 }
294 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
295 if (expo <= 0)
296 return PyLong_FromLong(0L);
297 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
298 v = _PyLong_New(ndig);
299 if (v == NULL)
300 return NULL;
301 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
302 for (i = ndig; --i >= 0; ) {
303 digit bits = (digit)frac;
304 v->ob_digit[i] = bits;
305 frac = frac - (double)bits;
306 frac = ldexp(frac, PyLong_SHIFT);
307 }
308 if (neg)
309 Py_SIZE(v) = -(Py_SIZE(v));
310 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000311}
312
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
314 * anything about what happens when a signed integer operation overflows,
315 * and some compilers think they're doing you a favor by being "clever"
316 * then. The bit pattern for the largest postive signed long is
317 * (unsigned long)LONG_MAX, and for the smallest negative signed long
318 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
319 * However, some other compilers warn about applying unary minus to an
320 * unsigned operand. Hence the weird "0-".
321 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
323#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324
Mark Dickinson8d48b432011-10-23 20:47:14 +0100325/* Get a C long int from a long int object or any object that has an __int__
326 method.
327
328 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
329 the result. Otherwise *overflow is 0.
330
331 For other errors (e.g., TypeError), return -1 and set an error condition.
332 In this case *overflow will be 0.
333*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000334
335long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000336PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 /* This version by Tim Peters */
339 register PyLongObject *v;
340 unsigned long x, prev;
341 long res;
342 Py_ssize_t i;
343 int sign;
344 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 *overflow = 0;
347 if (vv == NULL) {
348 PyErr_BadInternalCall();
349 return -1;
350 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (!PyLong_Check(vv)) {
353 PyNumberMethods *nb;
354 nb = vv->ob_type->tp_as_number;
355 if (nb == NULL || nb->nb_int == NULL) {
356 PyErr_SetString(PyExc_TypeError,
357 "an integer is required");
358 return -1;
359 }
360 vv = (*nb->nb_int) (vv);
361 if (vv == NULL)
362 return -1;
363 do_decref = 1;
364 if (!PyLong_Check(vv)) {
365 Py_DECREF(vv);
366 PyErr_SetString(PyExc_TypeError,
367 "nb_int should return int object");
368 return -1;
369 }
370 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 res = -1;
373 v = (PyLongObject *)vv;
374 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 switch (i) {
377 case -1:
378 res = -(sdigit)v->ob_digit[0];
379 break;
380 case 0:
381 res = 0;
382 break;
383 case 1:
384 res = v->ob_digit[0];
385 break;
386 default:
387 sign = 1;
388 x = 0;
389 if (i < 0) {
390 sign = -1;
391 i = -(i);
392 }
393 while (--i >= 0) {
394 prev = x;
395 x = (x << PyLong_SHIFT) | v->ob_digit[i];
396 if ((x >> PyLong_SHIFT) != prev) {
397 *overflow = sign;
398 goto exit;
399 }
400 }
401 /* Haven't lost any bits, but casting to long requires extra
402 * care (see comment above).
403 */
404 if (x <= (unsigned long)LONG_MAX) {
405 res = (long)x * sign;
406 }
407 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
408 res = LONG_MIN;
409 }
410 else {
411 *overflow = sign;
412 /* res is already set to -1 */
413 }
414 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000415 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (do_decref) {
417 Py_DECREF(vv);
418 }
419 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000420}
421
Mark Dickinson8d48b432011-10-23 20:47:14 +0100422/* Get a C long int from a long int object or any object that has an __int__
423 method. Return -1 and set an error if overflow occurs. */
424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000426PyLong_AsLong(PyObject *obj)
427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 int overflow;
429 long result = PyLong_AsLongAndOverflow(obj, &overflow);
430 if (overflow) {
431 /* XXX: could be cute and give a different
432 message for overflow == -1 */
433 PyErr_SetString(PyExc_OverflowError,
434 "Python int too large to convert to C long");
435 }
436 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000437}
438
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000439/* Get a Py_ssize_t from a long int object.
440 Returns -1 and sets an error condition if overflow occurs. */
441
442Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000443PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 register PyLongObject *v;
445 size_t x, prev;
446 Py_ssize_t i;
447 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (vv == NULL) {
450 PyErr_BadInternalCall();
451 return -1;
452 }
453 if (!PyLong_Check(vv)) {
454 PyErr_SetString(PyExc_TypeError, "an integer is required");
455 return -1;
456 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 v = (PyLongObject *)vv;
459 i = Py_SIZE(v);
460 switch (i) {
461 case -1: return -(sdigit)v->ob_digit[0];
462 case 0: return 0;
463 case 1: return v->ob_digit[0];
464 }
465 sign = 1;
466 x = 0;
467 if (i < 0) {
468 sign = -1;
469 i = -(i);
470 }
471 while (--i >= 0) {
472 prev = x;
473 x = (x << PyLong_SHIFT) | v->ob_digit[i];
474 if ((x >> PyLong_SHIFT) != prev)
475 goto overflow;
476 }
477 /* Haven't lost any bits, but casting to a signed type requires
478 * extra care (see comment above).
479 */
480 if (x <= (size_t)PY_SSIZE_T_MAX) {
481 return (Py_ssize_t)x * sign;
482 }
483 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
484 return PY_SSIZE_T_MIN;
485 }
486 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487
Mark Dickinson22b20182010-05-10 21:27:53 +0000488 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyErr_SetString(PyExc_OverflowError,
490 "Python int too large to convert to C ssize_t");
491 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000492}
493
Guido van Rossumd8c80482002-08-13 00:24:58 +0000494/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000495 Returns -1 and sets an error condition if overflow occurs. */
496
497unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000498PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 register PyLongObject *v;
501 unsigned long x, prev;
502 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (vv == NULL) {
505 PyErr_BadInternalCall();
506 return (unsigned long)-1;
507 }
508 if (!PyLong_Check(vv)) {
509 PyErr_SetString(PyExc_TypeError, "an integer is required");
510 return (unsigned long)-1;
511 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 v = (PyLongObject *)vv;
514 i = Py_SIZE(v);
515 x = 0;
516 if (i < 0) {
517 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000518 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return (unsigned long) -1;
520 }
521 switch (i) {
522 case 0: return 0;
523 case 1: return v->ob_digit[0];
524 }
525 while (--i >= 0) {
526 prev = x;
527 x = (x << PyLong_SHIFT) | v->ob_digit[i];
528 if ((x >> PyLong_SHIFT) != prev) {
529 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000530 "python int too large to convert "
531 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return (unsigned long) -1;
533 }
534 }
535 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000536}
537
Stefan Krahb77c6c62011-09-12 16:22:47 +0200538/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
539 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000540
541size_t
542PyLong_AsSize_t(PyObject *vv)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 register PyLongObject *v;
545 size_t x, prev;
546 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (vv == NULL) {
549 PyErr_BadInternalCall();
550 return (size_t) -1;
551 }
552 if (!PyLong_Check(vv)) {
553 PyErr_SetString(PyExc_TypeError, "an integer is required");
554 return (size_t)-1;
555 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 v = (PyLongObject *)vv;
558 i = Py_SIZE(v);
559 x = 0;
560 if (i < 0) {
561 PyErr_SetString(PyExc_OverflowError,
562 "can't convert negative value to size_t");
563 return (size_t) -1;
564 }
565 switch (i) {
566 case 0: return 0;
567 case 1: return v->ob_digit[0];
568 }
569 while (--i >= 0) {
570 prev = x;
571 x = (x << PyLong_SHIFT) | v->ob_digit[i];
572 if ((x >> PyLong_SHIFT) != prev) {
573 PyErr_SetString(PyExc_OverflowError,
574 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200575 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 }
577 }
578 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000579}
580
Thomas Hellera4ea6032003-04-17 18:55:45 +0000581/* Get a C unsigned long int from a long int object, ignoring the high bits.
582 Returns -1 and sets an error condition if an error occurs. */
583
Guido van Rossumddefaf32007-01-14 03:31:43 +0000584static unsigned long
585_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 register PyLongObject *v;
588 unsigned long x;
589 Py_ssize_t i;
590 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (vv == NULL || !PyLong_Check(vv)) {
593 PyErr_BadInternalCall();
594 return (unsigned long) -1;
595 }
596 v = (PyLongObject *)vv;
597 i = Py_SIZE(v);
598 switch (i) {
599 case 0: return 0;
600 case 1: return v->ob_digit[0];
601 }
602 sign = 1;
603 x = 0;
604 if (i < 0) {
605 sign = -1;
606 i = -i;
607 }
608 while (--i >= 0) {
609 x = (x << PyLong_SHIFT) | v->ob_digit[i];
610 }
611 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000612}
613
Guido van Rossumddefaf32007-01-14 03:31:43 +0000614unsigned long
615PyLong_AsUnsignedLongMask(register PyObject *op)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyNumberMethods *nb;
618 PyLongObject *lo;
619 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (op && PyLong_Check(op))
622 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
625 nb->nb_int == NULL) {
626 PyErr_SetString(PyExc_TypeError, "an integer is required");
627 return (unsigned long)-1;
628 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 lo = (PyLongObject*) (*nb->nb_int) (op);
631 if (lo == NULL)
632 return (unsigned long)-1;
633 if (PyLong_Check(lo)) {
634 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
635 Py_DECREF(lo);
636 if (PyErr_Occurred())
637 return (unsigned long)-1;
638 return val;
639 }
640 else
641 {
642 Py_DECREF(lo);
643 PyErr_SetString(PyExc_TypeError,
644 "nb_int should return int object");
645 return (unsigned long)-1;
646 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000647}
648
Tim Peters5b8132f2003-01-31 15:52:05 +0000649int
650_PyLong_Sign(PyObject *vv)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(v != NULL);
655 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000658}
659
Tim Petersbaefd9e2003-01-28 20:37:45 +0000660size_t
661_PyLong_NumBits(PyObject *vv)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyLongObject *v = (PyLongObject *)vv;
664 size_t result = 0;
665 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 assert(v != NULL);
668 assert(PyLong_Check(v));
669 ndigits = ABS(Py_SIZE(v));
670 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
671 if (ndigits > 0) {
672 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 result = (ndigits - 1) * PyLong_SHIFT;
675 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
676 goto Overflow;
677 do {
678 ++result;
679 if (result == 0)
680 goto Overflow;
681 msd >>= 1;
682 } while (msd);
683 }
684 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000685
Mark Dickinson22b20182010-05-10 21:27:53 +0000686 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
688 "to express in a platform size_t");
689 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000690}
691
Tim Peters2a9b3672001-06-11 21:23:58 +0000692PyObject *
693_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000695{
Mark Dickinson22b20182010-05-10 21:27:53 +0000696 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 int incr; /* direction to move pstartbyte */
698 const unsigned char* pendbyte; /* MSB of bytes */
699 size_t numsignificantbytes; /* number of bytes that matter */
700 Py_ssize_t ndigits; /* number of Python long digits */
701 PyLongObject* v; /* result */
702 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (n == 0)
705 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (little_endian) {
708 pstartbyte = bytes;
709 pendbyte = bytes + n - 1;
710 incr = 1;
711 }
712 else {
713 pstartbyte = bytes + n - 1;
714 pendbyte = bytes;
715 incr = -1;
716 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (is_signed)
719 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200722 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 is positive, and leading 0xff bytes if negative. */
724 {
725 size_t i;
726 const unsigned char* p = pendbyte;
727 const int pincr = -incr; /* search MSB to LSB */
728 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 for (i = 0; i < n; ++i, p += pincr) {
731 if (*p != insignficant)
732 break;
733 }
734 numsignificantbytes = n - i;
735 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
736 actually has 2 significant bytes. OTOH, 0xff0001 ==
737 -0x00ffff, so we wouldn't *need* to bump it there; but we
738 do for 0xffff = -0x0001. To be safe without bothering to
739 check every case, bump it regardless. */
740 if (is_signed && numsignificantbytes < n)
741 ++numsignificantbytes;
742 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 /* How many Python long digits do we need? We have
745 8*numsignificantbytes bits, and each Python long digit has
746 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
747 /* catch overflow before it happens */
748 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
749 PyErr_SetString(PyExc_OverflowError,
750 "byte array too long to convert to int");
751 return NULL;
752 }
753 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
754 v = _PyLong_New(ndigits);
755 if (v == NULL)
756 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* Copy the bits over. The tricky parts are computing 2's-comp on
759 the fly for signed numbers, and dealing with the mismatch between
760 8-bit bytes and (probably) 15-bit Python digits.*/
761 {
762 size_t i;
763 twodigits carry = 1; /* for 2's-comp calculation */
764 twodigits accum = 0; /* sliding register */
765 unsigned int accumbits = 0; /* number of bits in accum */
766 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
769 twodigits thisbyte = *p;
770 /* Compute correction for 2's comp, if needed. */
771 if (is_signed) {
772 thisbyte = (0xff ^ thisbyte) + carry;
773 carry = thisbyte >> 8;
774 thisbyte &= 0xff;
775 }
776 /* Because we're going LSB to MSB, thisbyte is
777 more significant than what's already in accum,
778 so needs to be prepended to accum. */
779 accum |= (twodigits)thisbyte << accumbits;
780 accumbits += 8;
781 if (accumbits >= PyLong_SHIFT) {
782 /* There's enough to fill a Python digit. */
783 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000784 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 ++idigit;
786 accum >>= PyLong_SHIFT;
787 accumbits -= PyLong_SHIFT;
788 assert(accumbits < PyLong_SHIFT);
789 }
790 }
791 assert(accumbits < PyLong_SHIFT);
792 if (accumbits) {
793 assert(idigit < ndigits);
794 v->ob_digit[idigit] = (digit)accum;
795 ++idigit;
796 }
797 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_SIZE(v) = is_signed ? -idigit : idigit;
800 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000801}
802
803int
804_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 unsigned char* bytes, size_t n,
806 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000809 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000811 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
813 digit carry; /* for computing 2's-comp */
814 size_t j; /* # bytes filled */
815 unsigned char* p; /* pointer to next byte in bytes */
816 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (Py_SIZE(v) < 0) {
821 ndigits = -(Py_SIZE(v));
822 if (!is_signed) {
823 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000824 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return -1;
826 }
827 do_twos_comp = 1;
828 }
829 else {
830 ndigits = Py_SIZE(v);
831 do_twos_comp = 0;
832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (little_endian) {
835 p = bytes;
836 pincr = 1;
837 }
838 else {
839 p = bytes + n - 1;
840 pincr = -1;
841 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Copy over all the Python digits.
844 It's crucial that every Python digit except for the MSD contribute
845 exactly PyLong_SHIFT bits to the total, so first assert that the long is
846 normalized. */
847 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
848 j = 0;
849 accum = 0;
850 accumbits = 0;
851 carry = do_twos_comp ? 1 : 0;
852 for (i = 0; i < ndigits; ++i) {
853 digit thisdigit = v->ob_digit[i];
854 if (do_twos_comp) {
855 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
856 carry = thisdigit >> PyLong_SHIFT;
857 thisdigit &= PyLong_MASK;
858 }
859 /* Because we're going LSB to MSB, thisdigit is more
860 significant than what's already in accum, so needs to be
861 prepended to accum. */
862 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* The most-significant digit may be (probably is) at least
865 partly empty. */
866 if (i == ndigits - 1) {
867 /* Count # of sign bits -- they needn't be stored,
868 * although for signed conversion we need later to
869 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000870 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 while (s != 0) {
872 s >>= 1;
873 accumbits++;
874 }
875 }
876 else
877 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Store as many bytes as possible. */
880 while (accumbits >= 8) {
881 if (j >= n)
882 goto Overflow;
883 ++j;
884 *p = (unsigned char)(accum & 0xff);
885 p += pincr;
886 accumbits -= 8;
887 accum >>= 8;
888 }
889 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Store the straggler (if any). */
892 assert(accumbits < 8);
893 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
894 if (accumbits > 0) {
895 if (j >= n)
896 goto Overflow;
897 ++j;
898 if (do_twos_comp) {
899 /* Fill leading bits of the byte with sign bits
900 (appropriately pretending that the long had an
901 infinite supply of sign bits). */
902 accum |= (~(twodigits)0) << accumbits;
903 }
904 *p = (unsigned char)(accum & 0xff);
905 p += pincr;
906 }
907 else if (j == n && n > 0 && is_signed) {
908 /* The main loop filled the byte array exactly, so the code
909 just above didn't get to ensure there's a sign bit, and the
910 loop below wouldn't add one either. Make sure a sign bit
911 exists. */
912 unsigned char msb = *(p - pincr);
913 int sign_bit_set = msb >= 0x80;
914 assert(accumbits == 0);
915 if (sign_bit_set == do_twos_comp)
916 return 0;
917 else
918 goto Overflow;
919 }
Tim Peters05607ad2001-06-13 21:01:27 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Fill remaining bytes with copies of the sign bit. */
922 {
923 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
924 for ( ; j < n; ++j, p += pincr)
925 *p = signbyte;
926 }
Tim Peters05607ad2001-06-13 21:01:27 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000929
Mark Dickinson22b20182010-05-10 21:27:53 +0000930 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
932 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000933
Tim Peters2a9b3672001-06-11 21:23:58 +0000934}
935
Mark Dickinson8d48b432011-10-23 20:47:14 +0100936/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000937
938PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000939PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000940{
Tim Peters70128a12001-06-16 08:48:40 +0000941#ifndef HAVE_LONG_LONG
942# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
943#endif
944#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000945# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000946#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* special-case null pointer */
948 if (!p)
949 return PyLong_FromLong(0);
950 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000951
Guido van Rossum78694d91998-09-18 14:14:13 +0000952}
953
Mark Dickinson8d48b432011-10-23 20:47:14 +0100954/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000955
956void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000957PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000958{
Tim Peters70128a12001-06-16 08:48:40 +0000959#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
963 x = PyLong_AsLong(vv);
964 else
965 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000966#else
Tim Peters70128a12001-06-16 08:48:40 +0000967
968#ifndef HAVE_LONG_LONG
969# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
970#endif
971#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000972# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
977 x = PyLong_AsLongLong(vv);
978 else
979 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000980
981#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (x == -1 && PyErr_Occurred())
984 return NULL;
985 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000986}
987
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000988#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000989
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000991 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000992 */
993
Tim Peterscf37dfc2001-06-14 18:42:50 +0000994#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000995#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000996
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000997/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000998
999PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001000PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyLongObject *v;
1003 unsigned PY_LONG_LONG abs_ival;
1004 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1005 int ndigits = 0;
1006 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 CHECK_SMALL_INT(ival);
1009 if (ival < 0) {
1010 /* avoid signed overflow on negation; see comments
1011 in PyLong_FromLong above. */
1012 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1013 negative = 1;
1014 }
1015 else {
1016 abs_ival = (unsigned PY_LONG_LONG)ival;
1017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* Count the number of Python digits.
1020 We used to pick 5 ("big enough for anything"), but that's a
1021 waste of time and space given that 5*15 = 75 bits are rarely
1022 needed. */
1023 t = abs_ival;
1024 while (t) {
1025 ++ndigits;
1026 t >>= PyLong_SHIFT;
1027 }
1028 v = _PyLong_New(ndigits);
1029 if (v != NULL) {
1030 digit *p = v->ob_digit;
1031 Py_SIZE(v) = negative ? -ndigits : ndigits;
1032 t = abs_ival;
1033 while (t) {
1034 *p++ = (digit)(t & PyLong_MASK);
1035 t >>= PyLong_SHIFT;
1036 }
1037 }
1038 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039}
1040
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001042
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001044PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyLongObject *v;
1047 unsigned PY_LONG_LONG t;
1048 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (ival < PyLong_BASE)
1051 return PyLong_FromLong((long)ival);
1052 /* Count the number of Python digits. */
1053 t = (unsigned PY_LONG_LONG)ival;
1054 while (t) {
1055 ++ndigits;
1056 t >>= PyLong_SHIFT;
1057 }
1058 v = _PyLong_New(ndigits);
1059 if (v != NULL) {
1060 digit *p = v->ob_digit;
1061 Py_SIZE(v) = ndigits;
1062 while (ival) {
1063 *p++ = (digit)(ival & PyLong_MASK);
1064 ival >>= PyLong_SHIFT;
1065 }
1066 }
1067 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001068}
1069
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070/* Create a new long int object from a C Py_ssize_t. */
1071
1072PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001073PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyLongObject *v;
1076 size_t abs_ival;
1077 size_t t; /* unsigned so >> doesn't propagate sign bit */
1078 int ndigits = 0;
1079 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 CHECK_SMALL_INT(ival);
1082 if (ival < 0) {
1083 /* avoid signed overflow when ival = SIZE_T_MIN */
1084 abs_ival = (size_t)(-1-ival)+1;
1085 negative = 1;
1086 }
1087 else {
1088 abs_ival = (size_t)ival;
1089 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 /* Count the number of Python digits. */
1092 t = abs_ival;
1093 while (t) {
1094 ++ndigits;
1095 t >>= PyLong_SHIFT;
1096 }
1097 v = _PyLong_New(ndigits);
1098 if (v != NULL) {
1099 digit *p = v->ob_digit;
1100 Py_SIZE(v) = negative ? -ndigits : ndigits;
1101 t = abs_ival;
1102 while (t) {
1103 *p++ = (digit)(t & PyLong_MASK);
1104 t >>= PyLong_SHIFT;
1105 }
1106 }
1107 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108}
1109
1110/* Create a new long int object from a C size_t. */
1111
1112PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001113PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyLongObject *v;
1116 size_t t;
1117 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (ival < PyLong_BASE)
1120 return PyLong_FromLong((long)ival);
1121 /* Count the number of Python digits. */
1122 t = ival;
1123 while (t) {
1124 ++ndigits;
1125 t >>= PyLong_SHIFT;
1126 }
1127 v = _PyLong_New(ndigits);
1128 if (v != NULL) {
1129 digit *p = v->ob_digit;
1130 Py_SIZE(v) = ndigits;
1131 while (ival) {
1132 *p++ = (digit)(ival & PyLong_MASK);
1133 ival >>= PyLong_SHIFT;
1134 }
1135 }
1136 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137}
1138
Mark Dickinson8d48b432011-10-23 20:47:14 +01001139/* Get a C long long int from a long int object or any object that has an
1140 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001142PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001143PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyLongObject *v;
1146 PY_LONG_LONG bytes;
1147 int one = 1;
1148 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (vv == NULL) {
1151 PyErr_BadInternalCall();
1152 return -1;
1153 }
1154 if (!PyLong_Check(vv)) {
1155 PyNumberMethods *nb;
1156 PyObject *io;
1157 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1158 nb->nb_int == NULL) {
1159 PyErr_SetString(PyExc_TypeError, "an integer is required");
1160 return -1;
1161 }
1162 io = (*nb->nb_int) (vv);
1163 if (io == NULL)
1164 return -1;
1165 if (PyLong_Check(io)) {
1166 bytes = PyLong_AsLongLong(io);
1167 Py_DECREF(io);
1168 return bytes;
1169 }
1170 Py_DECREF(io);
1171 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1172 return -1;
1173 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 v = (PyLongObject*)vv;
1176 switch(Py_SIZE(v)) {
1177 case -1: return -(sdigit)v->ob_digit[0];
1178 case 0: return 0;
1179 case 1: return v->ob_digit[0];
1180 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001181 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1182 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1185 if (res < 0)
1186 return (PY_LONG_LONG)-1;
1187 else
1188 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001189}
1190
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001191/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001192 Return -1 and set an error if overflow occurs. */
1193
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001194unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001195PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyLongObject *v;
1198 unsigned PY_LONG_LONG bytes;
1199 int one = 1;
1200 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001201
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001202 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyErr_BadInternalCall();
1204 return (unsigned PY_LONG_LONG)-1;
1205 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001206 if (!PyLong_Check(vv)) {
1207 PyErr_SetString(PyExc_TypeError, "an integer is required");
1208 return (unsigned PY_LONG_LONG)-1;
1209 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 v = (PyLongObject*)vv;
1212 switch(Py_SIZE(v)) {
1213 case 0: return 0;
1214 case 1: return v->ob_digit[0];
1215 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001216
Mark Dickinson22b20182010-05-10 21:27:53 +00001217 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1218 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1221 if (res < 0)
1222 return (unsigned PY_LONG_LONG)res;
1223 else
1224 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001225}
Tim Petersd1a7da62001-06-13 00:35:57 +00001226
Thomas Hellera4ea6032003-04-17 18:55:45 +00001227/* Get a C unsigned long int from a long int object, ignoring the high bits.
1228 Returns -1 and sets an error condition if an error occurs. */
1229
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230static unsigned PY_LONG_LONG
1231_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 register PyLongObject *v;
1234 unsigned PY_LONG_LONG x;
1235 Py_ssize_t i;
1236 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (vv == NULL || !PyLong_Check(vv)) {
1239 PyErr_BadInternalCall();
1240 return (unsigned long) -1;
1241 }
1242 v = (PyLongObject *)vv;
1243 switch(Py_SIZE(v)) {
1244 case 0: return 0;
1245 case 1: return v->ob_digit[0];
1246 }
1247 i = Py_SIZE(v);
1248 sign = 1;
1249 x = 0;
1250 if (i < 0) {
1251 sign = -1;
1252 i = -i;
1253 }
1254 while (--i >= 0) {
1255 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1256 }
1257 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001258}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001259
1260unsigned PY_LONG_LONG
1261PyLong_AsUnsignedLongLongMask(register PyObject *op)
1262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyNumberMethods *nb;
1264 PyLongObject *lo;
1265 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (op && PyLong_Check(op))
1268 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1271 nb->nb_int == NULL) {
1272 PyErr_SetString(PyExc_TypeError, "an integer is required");
1273 return (unsigned PY_LONG_LONG)-1;
1274 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 lo = (PyLongObject*) (*nb->nb_int) (op);
1277 if (lo == NULL)
1278 return (unsigned PY_LONG_LONG)-1;
1279 if (PyLong_Check(lo)) {
1280 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1281 Py_DECREF(lo);
1282 if (PyErr_Occurred())
1283 return (unsigned PY_LONG_LONG)-1;
1284 return val;
1285 }
1286 else
1287 {
1288 Py_DECREF(lo);
1289 PyErr_SetString(PyExc_TypeError,
1290 "nb_int should return int object");
1291 return (unsigned PY_LONG_LONG)-1;
1292 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001293}
Tim Petersd1a7da62001-06-13 00:35:57 +00001294#undef IS_LITTLE_ENDIAN
1295
Mark Dickinson8d48b432011-10-23 20:47:14 +01001296/* Get a C long long int from a long int object or any object that has an
1297 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001298
Mark Dickinson8d48b432011-10-23 20:47:14 +01001299 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1300 the result. Otherwise *overflow is 0.
1301
1302 For other errors (e.g., TypeError), return -1 and set an error condition.
1303 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001304*/
1305
1306PY_LONG_LONG
1307PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /* This version by Tim Peters */
1310 register PyLongObject *v;
1311 unsigned PY_LONG_LONG x, prev;
1312 PY_LONG_LONG res;
1313 Py_ssize_t i;
1314 int sign;
1315 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 *overflow = 0;
1318 if (vv == NULL) {
1319 PyErr_BadInternalCall();
1320 return -1;
1321 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (!PyLong_Check(vv)) {
1324 PyNumberMethods *nb;
1325 nb = vv->ob_type->tp_as_number;
1326 if (nb == NULL || nb->nb_int == NULL) {
1327 PyErr_SetString(PyExc_TypeError,
1328 "an integer is required");
1329 return -1;
1330 }
1331 vv = (*nb->nb_int) (vv);
1332 if (vv == NULL)
1333 return -1;
1334 do_decref = 1;
1335 if (!PyLong_Check(vv)) {
1336 Py_DECREF(vv);
1337 PyErr_SetString(PyExc_TypeError,
1338 "nb_int should return int object");
1339 return -1;
1340 }
1341 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 res = -1;
1344 v = (PyLongObject *)vv;
1345 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 switch (i) {
1348 case -1:
1349 res = -(sdigit)v->ob_digit[0];
1350 break;
1351 case 0:
1352 res = 0;
1353 break;
1354 case 1:
1355 res = v->ob_digit[0];
1356 break;
1357 default:
1358 sign = 1;
1359 x = 0;
1360 if (i < 0) {
1361 sign = -1;
1362 i = -(i);
1363 }
1364 while (--i >= 0) {
1365 prev = x;
1366 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1367 if ((x >> PyLong_SHIFT) != prev) {
1368 *overflow = sign;
1369 goto exit;
1370 }
1371 }
1372 /* Haven't lost any bits, but casting to long requires extra
1373 * care (see comment above).
1374 */
1375 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1376 res = (PY_LONG_LONG)x * sign;
1377 }
1378 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1379 res = PY_LLONG_MIN;
1380 }
1381 else {
1382 *overflow = sign;
1383 /* res is already set to -1 */
1384 }
1385 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001386 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (do_decref) {
1388 Py_DECREF(vv);
1389 }
1390 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001391}
1392
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001393#endif /* HAVE_LONG_LONG */
1394
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001395#define CHECK_BINOP(v,w) \
1396 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001397 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1398 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001399 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001400
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001401/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1402 2**k if d is nonzero, else 0. */
1403
1404static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1406 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001407};
1408
1409static int
1410bits_in_digit(digit d)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 int d_bits = 0;
1413 while (d >= 32) {
1414 d_bits += 6;
1415 d >>= 6;
1416 }
1417 d_bits += (int)BitLengthTable[d];
1418 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001419}
1420
Tim Peters877a2122002-08-12 05:09:36 +00001421/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1422 * is modified in place, by adding y to it. Carries are propagated as far as
1423 * x[m-1], and the remaining carry (0 or 1) is returned.
1424 */
1425static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001426v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 Py_ssize_t i;
1429 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 assert(m >= n);
1432 for (i = 0; i < n; ++i) {
1433 carry += x[i] + y[i];
1434 x[i] = carry & PyLong_MASK;
1435 carry >>= PyLong_SHIFT;
1436 assert((carry & 1) == carry);
1437 }
1438 for (; carry && i < m; ++i) {
1439 carry += x[i];
1440 x[i] = carry & PyLong_MASK;
1441 carry >>= PyLong_SHIFT;
1442 assert((carry & 1) == carry);
1443 }
1444 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001445}
1446
1447/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1448 * is modified in place, by subtracting y from it. Borrows are propagated as
1449 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1450 */
1451static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i;
1455 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 assert(m >= n);
1458 for (i = 0; i < n; ++i) {
1459 borrow = x[i] - y[i] - borrow;
1460 x[i] = borrow & PyLong_MASK;
1461 borrow >>= PyLong_SHIFT;
1462 borrow &= 1; /* keep only 1 sign bit */
1463 }
1464 for (; borrow && i < m; ++i) {
1465 borrow = x[i] - borrow;
1466 x[i] = borrow & PyLong_MASK;
1467 borrow >>= PyLong_SHIFT;
1468 borrow &= 1;
1469 }
1470 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001471}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001472
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001473/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1474 * result in z[0:m], and return the d bits shifted out of the top.
1475 */
1476static digit
1477v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 Py_ssize_t i;
1480 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 assert(0 <= d && d < PyLong_SHIFT);
1483 for (i=0; i < m; i++) {
1484 twodigits acc = (twodigits)a[i] << d | carry;
1485 z[i] = (digit)acc & PyLong_MASK;
1486 carry = (digit)(acc >> PyLong_SHIFT);
1487 }
1488 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001489}
1490
1491/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1492 * result in z[0:m], and return the d bits shifted out of the bottom.
1493 */
1494static digit
1495v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_ssize_t i;
1498 digit carry = 0;
1499 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 assert(0 <= d && d < PyLong_SHIFT);
1502 for (i=m; i-- > 0;) {
1503 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1504 carry = (digit)acc & mask;
1505 z[i] = (digit)(acc >> d);
1506 }
1507 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001508}
1509
Tim Peters212e6142001-07-14 12:23:19 +00001510/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1511 in pout, and returning the remainder. pin and pout point at the LSD.
1512 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001513 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001514 immutable. */
1515
1516static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001517inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 assert(n > 0 && n <= PyLong_MASK);
1522 pin += size;
1523 pout += size;
1524 while (--size >= 0) {
1525 digit hi;
1526 rem = (rem << PyLong_SHIFT) | *--pin;
1527 *--pout = hi = (digit)(rem / n);
1528 rem -= (twodigits)hi * n;
1529 }
1530 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001531}
1532
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001533/* Divide a long integer by a digit, returning both the quotient
1534 (as function result) and the remainder (through *prem).
1535 The sign of a is ignored; n should not be zero. */
1536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001537static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001538divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 const Py_ssize_t size = ABS(Py_SIZE(a));
1541 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 assert(n > 0 && n <= PyLong_MASK);
1544 z = _PyLong_New(size);
1545 if (z == NULL)
1546 return NULL;
1547 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1548 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001549}
1550
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001551/* Convert a long integer to a base 10 string. Returns a new non-shared
1552 string. (Return value is non-shared so that callers can modify the
1553 returned value if necessary.) */
1554
1555static PyObject *
1556long_to_decimal_string(PyObject *aa)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyLongObject *scratch, *a;
1559 PyObject *str;
1560 Py_ssize_t size, strlen, size_a, i, j;
1561 digit *pout, *pin, rem, tenpow;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001562 unsigned char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 a = (PyLongObject *)aa;
1566 if (a == NULL || !PyLong_Check(a)) {
1567 PyErr_BadInternalCall();
1568 return NULL;
1569 }
1570 size_a = ABS(Py_SIZE(a));
1571 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* quick and dirty upper bound for the number of digits
1574 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 But log2(a) < size_a * PyLong_SHIFT, and
1579 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1580 > 3 * _PyLong_DECIMAL_SHIFT
1581 */
1582 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1583 PyErr_SetString(PyExc_OverflowError,
1584 "long is too large to format");
1585 return NULL;
1586 }
1587 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1588 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1589 scratch = _PyLong_New(size);
1590 if (scratch == NULL)
1591 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* convert array of base _PyLong_BASE digits in pin to an array of
1594 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1595 Volume 2 (3rd edn), section 4.4, Method 1b). */
1596 pin = a->ob_digit;
1597 pout = scratch->ob_digit;
1598 size = 0;
1599 for (i = size_a; --i >= 0; ) {
1600 digit hi = pin[i];
1601 for (j = 0; j < size; j++) {
1602 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1603 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1604 pout[j] = (digit)(z - (twodigits)hi *
1605 _PyLong_DECIMAL_BASE);
1606 }
1607 while (hi) {
1608 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1609 hi /= _PyLong_DECIMAL_BASE;
1610 }
1611 /* check for keyboard interrupt */
1612 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001613 Py_DECREF(scratch);
1614 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001615 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
1617 /* pout should have at least one digit, so that the case when a = 0
1618 works correctly */
1619 if (size == 0)
1620 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* calculate exact length of output string, and allocate */
1623 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1624 tenpow = 10;
1625 rem = pout[size-1];
1626 while (rem >= tenpow) {
1627 tenpow *= 10;
1628 strlen++;
1629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001630 str = PyUnicode_New(strlen, '9');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (str == NULL) {
1632 Py_DECREF(scratch);
1633 return NULL;
1634 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 /* fill the string right-to-left */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637 assert(PyUnicode_KIND(str) == PyUnicode_1BYTE_KIND);
1638 p = PyUnicode_1BYTE_DATA(str) + strlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 *p = '\0';
1640 /* pout[0] through pout[size-2] contribute exactly
1641 _PyLong_DECIMAL_SHIFT digits each */
1642 for (i=0; i < size - 1; i++) {
1643 rem = pout[i];
1644 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1645 *--p = '0' + rem % 10;
1646 rem /= 10;
1647 }
1648 }
1649 /* pout[size-1]: always produce at least one decimal digit */
1650 rem = pout[i];
1651 do {
1652 *--p = '0' + rem % 10;
1653 rem /= 10;
1654 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 /* and sign */
1657 if (negative)
1658 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 /* check we've counted correctly */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 assert(p == PyUnicode_1BYTE_DATA(str));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 Py_DECREF(scratch);
1663 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001664}
1665
Mark Dickinsoncd068122009-09-18 14:53:08 +00001666/* Convert a long int object to a string, using a given conversion base,
1667 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001668 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001669
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001670PyObject *
1671_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 Py_ssize_t i, sz;
1676 Py_ssize_t size_a;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677 char *p;
1678 char sign = '\0';
1679 char *buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 assert(base == 2 || base == 8 || base == 10 || base == 16);
1683 if (base == 10)
1684 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 if (a == NULL || !PyLong_Check(a)) {
1687 PyErr_BadInternalCall();
1688 return NULL;
1689 }
1690 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* Compute a rough upper bound for the length of the string */
1693 switch (base) {
1694 case 16:
1695 bits = 4;
1696 break;
1697 case 8:
1698 bits = 3;
1699 break;
1700 case 2:
1701 bits = 1;
1702 break;
1703 default:
1704 assert(0); /* shouldn't ever get here */
1705 bits = 0; /* to silence gcc warning */
1706 }
1707 /* compute length of output string: allow 2 characters for prefix and
1708 1 for possible '-' sign. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT / sizeof(Py_UCS4)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyErr_SetString(PyExc_OverflowError,
1711 "int is too large to format");
1712 return NULL;
1713 }
1714 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1715 is safe from overflow */
1716 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1717 assert(sz >= 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718 buffer = PyMem_Malloc(sz);
1719 if (buffer == NULL) {
1720 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001722 }
1723 p = &buffer[sz];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (Py_SIZE(a) < 0)
1725 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 if (Py_SIZE(a) == 0) {
1728 *--p = '0';
1729 }
1730 else {
1731 /* JRH: special case for power-of-2 bases */
1732 twodigits accum = 0;
1733 int accumbits = 0; /* # of bits in accum */
1734 for (i = 0; i < size_a; ++i) {
1735 accum |= (twodigits)a->ob_digit[i] << accumbits;
1736 accumbits += PyLong_SHIFT;
1737 assert(accumbits >= bits);
1738 do {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 char cdigit;
1740 cdigit = (char)(accum & (base - 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 assert(p > buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 *--p = cdigit;
1744 accumbits -= bits;
1745 accum >>= bits;
1746 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1747 }
1748 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (base == 16)
1751 *--p = 'x';
1752 else if (base == 8)
1753 *--p = 'o';
1754 else /* (base == 2) */
1755 *--p = 'b';
1756 *--p = '0';
1757 if (sign)
1758 *--p = sign;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759 v = PyUnicode_DecodeASCII(p, &buffer[sz] - p, NULL);
1760 PyMem_Free(buffer);
1761 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001762}
1763
Thomas Wouters477c8d52006-05-27 19:21:47 +00001764/* Table of digit values for 8-bit string -> integer conversion.
1765 * '0' maps to 0, ..., '9' maps to 9.
1766 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1767 * All other indices map to 37.
1768 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001769 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001770 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001771unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1773 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1774 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1775 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1776 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1777 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1778 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1779 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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,
1785 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1786 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1787 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788};
1789
1790/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001791 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1792 * non-digit (which may be *str!). A normalized long is returned.
1793 * The point to this routine is that it takes time linear in the number of
1794 * string characters.
1795 */
1796static PyLongObject *
1797long_from_binary_base(char **str, int base)
1798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 char *p = *str;
1800 char *start = p;
1801 int bits_per_char;
1802 Py_ssize_t n;
1803 PyLongObject *z;
1804 twodigits accum;
1805 int bits_in_accum;
1806 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1809 n = base;
1810 for (bits_per_char = -1; n; ++bits_per_char)
1811 n >>= 1;
1812 /* n <- total # of bits needed, while setting p to end-of-string */
1813 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1814 ++p;
1815 *str = p;
1816 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1817 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1818 if (n / bits_per_char < p - start) {
1819 PyErr_SetString(PyExc_ValueError,
1820 "int string too large to convert");
1821 return NULL;
1822 }
1823 n = n / PyLong_SHIFT;
1824 z = _PyLong_New(n);
1825 if (z == NULL)
1826 return NULL;
1827 /* Read string from right, and fill in long from left; i.e.,
1828 * from least to most significant in both.
1829 */
1830 accum = 0;
1831 bits_in_accum = 0;
1832 pdigit = z->ob_digit;
1833 while (--p >= start) {
1834 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1835 assert(k >= 0 && k < base);
1836 accum |= (twodigits)k << bits_in_accum;
1837 bits_in_accum += bits_per_char;
1838 if (bits_in_accum >= PyLong_SHIFT) {
1839 *pdigit++ = (digit)(accum & PyLong_MASK);
1840 assert(pdigit - z->ob_digit <= n);
1841 accum >>= PyLong_SHIFT;
1842 bits_in_accum -= PyLong_SHIFT;
1843 assert(bits_in_accum < PyLong_SHIFT);
1844 }
1845 }
1846 if (bits_in_accum) {
1847 assert(bits_in_accum <= PyLong_SHIFT);
1848 *pdigit++ = (digit)accum;
1849 assert(pdigit - z->ob_digit <= n);
1850 }
1851 while (pdigit - z->ob_digit < n)
1852 *pdigit++ = 0;
1853 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001854}
1855
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001856PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001857PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 int sign = 1, error_if_nonzero = 0;
1860 char *start, *orig_str = str;
1861 PyLongObject *z = NULL;
1862 PyObject *strobj;
1863 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 if ((base != 0 && base < 2) || base > 36) {
1866 PyErr_SetString(PyExc_ValueError,
1867 "int() arg 2 must be >= 2 and <= 36");
1868 return NULL;
1869 }
1870 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1871 str++;
1872 if (*str == '+')
1873 ++str;
1874 else if (*str == '-') {
1875 ++str;
1876 sign = -1;
1877 }
1878 if (base == 0) {
1879 if (str[0] != '0')
1880 base = 10;
1881 else if (str[1] == 'x' || str[1] == 'X')
1882 base = 16;
1883 else if (str[1] == 'o' || str[1] == 'O')
1884 base = 8;
1885 else if (str[1] == 'b' || str[1] == 'B')
1886 base = 2;
1887 else {
1888 /* "old" (C-style) octal literal, now invalid.
1889 it might still be zero though */
1890 error_if_nonzero = 1;
1891 base = 10;
1892 }
1893 }
1894 if (str[0] == '0' &&
1895 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1896 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1897 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1898 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 start = str;
1901 if ((base & (base - 1)) == 0)
1902 z = long_from_binary_base(&str, base);
1903 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904/***
1905Binary bases can be converted in time linear in the number of digits, because
1906Python's representation base is binary. Other bases (including decimal!) use
1907the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001908
Thomas Wouters477c8d52006-05-27 19:21:47 +00001909First some math: the largest integer that can be expressed in N base-B digits
1910is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1911case number of Python digits needed to hold it is the smallest integer n s.t.
1912
1913 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1914 BASE**n >= B**N [taking logs to base BASE]
1915 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1916
1917The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1918this quickly. A Python long with that much space is reserved near the start,
1919and the result is computed into it.
1920
1921The input string is actually treated as being in base base**i (i.e., i digits
1922are processed at a time), where two more static arrays hold:
1923
1924 convwidth_base[base] = the largest integer i such that base**i <= BASE
1925 convmultmax_base[base] = base ** convwidth_base[base]
1926
1927The first of these is the largest i such that i consecutive input digits
1928must fit in a single Python digit. The second is effectively the input
1929base we're really using.
1930
1931Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1932convmultmax_base[base], the result is "simply"
1933
1934 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1935
1936where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001937
1938Error analysis: as above, the number of Python digits `n` needed is worst-
1939case
1940
1941 n >= N * log(B)/log(BASE)
1942
1943where `N` is the number of input digits in base `B`. This is computed via
1944
1945 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1946
1947below. Two numeric concerns are how much space this can waste, and whether
1948the computed result can be too small. To be concrete, assume BASE = 2**15,
1949which is the default (and it's unlikely anyone changes that).
1950
1951Waste isn't a problem: provided the first input digit isn't 0, the difference
1952between the worst-case input with N digits and the smallest input with N
1953digits is about a factor of B, but B is small compared to BASE so at most
1954one allocated Python digit can remain unused on that count. If
1955N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1956and adding 1 returns a result 1 larger than necessary. However, that can't
1957happen: whenever B is a power of 2, long_from_binary_base() is called
1958instead, and it's impossible for B**i to be an integer power of 2**15 when
1959B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1960an exact integer when B is not a power of 2, since B**i has a prime factor
1961other than 2 in that case, but (2**15)**j's only prime factor is 2).
1962
1963The computed result can be too small if the true value of N*log(B)/log(BASE)
1964is a little bit larger than an exact integer, but due to roundoff errors (in
1965computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1966yields a numeric result a little less than that integer. Unfortunately, "how
1967close can a transcendental function get to an integer over some range?"
1968questions are generally theoretically intractable. Computer analysis via
1969continued fractions is practical: expand log(B)/log(BASE) via continued
1970fractions, giving a sequence i/j of "the best" rational approximations. Then
1971j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1972we can get very close to being in trouble, but very rarely. For example,
197376573 is a denominator in one of the continued-fraction approximations to
1974log(10)/log(2**15), and indeed:
1975
1976 >>> log(10)/log(2**15)*76573
1977 16958.000000654003
1978
1979is very close to an integer. If we were working with IEEE single-precision,
1980rounding errors could kill us. Finding worst cases in IEEE double-precision
1981requires better-than-double-precision log() functions, and Tim didn't bother.
1982Instead the code checks to see whether the allocated space is enough as each
1983new Python digit is added, and copies the whole thing to a larger long if not.
1984This should happen extremely rarely, and in fact I don't have a test case
1985that triggers it(!). Instead the code was tested by artificially allocating
1986just 1 digit at the start, so that the copying code was exercised for every
1987digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001988***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 register twodigits c; /* current input character */
1990 Py_ssize_t size_z;
1991 int i;
1992 int convwidth;
1993 twodigits convmultmax, convmult;
1994 digit *pz, *pzstop;
1995 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 static double log_base_BASE[37] = {0.0e0,};
1998 static int convwidth_base[37] = {0,};
1999 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 if (log_base_BASE[base] == 0.0) {
2002 twodigits convmax = base;
2003 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002004
Mark Dickinson22b20182010-05-10 21:27:53 +00002005 log_base_BASE[base] = (log((double)base) /
2006 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 for (;;) {
2008 twodigits next = convmax * base;
2009 if (next > PyLong_BASE)
2010 break;
2011 convmax = next;
2012 ++i;
2013 }
2014 convmultmax_base[base] = convmax;
2015 assert(i > 0);
2016 convwidth_base[base] = i;
2017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 /* Find length of the string of numeric characters. */
2020 scan = str;
2021 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2022 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Create a long object that can contain the largest possible
2025 * integer with this base and length. Note that there's no
2026 * need to initialize z->ob_digit -- no slot is read up before
2027 * being stored into.
2028 */
2029 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2030 /* Uncomment next line to test exceedingly rare copy code */
2031 /* size_z = 1; */
2032 assert(size_z > 0);
2033 z = _PyLong_New(size_z);
2034 if (z == NULL)
2035 return NULL;
2036 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* `convwidth` consecutive input digits are treated as a single
2039 * digit in base `convmultmax`.
2040 */
2041 convwidth = convwidth_base[base];
2042 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* Work ;-) */
2045 while (str < scan) {
2046 /* grab up to convwidth digits from the input string */
2047 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2048 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2049 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002050 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 assert(c < PyLong_BASE);
2052 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 convmult = convmultmax;
2055 /* Calculate the shift only if we couldn't get
2056 * convwidth digits.
2057 */
2058 if (i != convwidth) {
2059 convmult = base;
2060 for ( ; i > 1; --i)
2061 convmult *= base;
2062 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Multiply z by convmult, and add c. */
2065 pz = z->ob_digit;
2066 pzstop = pz + Py_SIZE(z);
2067 for (; pz < pzstop; ++pz) {
2068 c += (twodigits)*pz * convmult;
2069 *pz = (digit)(c & PyLong_MASK);
2070 c >>= PyLong_SHIFT;
2071 }
2072 /* carry off the current end? */
2073 if (c) {
2074 assert(c < PyLong_BASE);
2075 if (Py_SIZE(z) < size_z) {
2076 *pz = (digit)c;
2077 ++Py_SIZE(z);
2078 }
2079 else {
2080 PyLongObject *tmp;
2081 /* Extremely rare. Get more space. */
2082 assert(Py_SIZE(z) == size_z);
2083 tmp = _PyLong_New(size_z + 1);
2084 if (tmp == NULL) {
2085 Py_DECREF(z);
2086 return NULL;
2087 }
2088 memcpy(tmp->ob_digit,
2089 z->ob_digit,
2090 sizeof(digit) * size_z);
2091 Py_DECREF(z);
2092 z = tmp;
2093 z->ob_digit[size_z] = (digit)c;
2094 ++size_z;
2095 }
2096 }
2097 }
2098 }
2099 if (z == NULL)
2100 return NULL;
2101 if (error_if_nonzero) {
2102 /* reset the base to 0, else the exception message
2103 doesn't make too much sense */
2104 base = 0;
2105 if (Py_SIZE(z) != 0)
2106 goto onError;
2107 /* there might still be other problems, therefore base
2108 remains zero here for the same reason */
2109 }
2110 if (str == start)
2111 goto onError;
2112 if (sign < 0)
2113 Py_SIZE(z) = -(Py_SIZE(z));
2114 while (*str && isspace(Py_CHARMASK(*str)))
2115 str++;
2116 if (*str != '\0')
2117 goto onError;
2118 if (pend)
2119 *pend = str;
2120 long_normalize(z);
2121 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002122
Mark Dickinson22b20182010-05-10 21:27:53 +00002123 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_XDECREF(z);
2125 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2126 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2127 if (strobj == NULL)
2128 return NULL;
2129 PyErr_Format(PyExc_ValueError,
2130 "invalid literal for int() with base %d: %R",
2131 base, strobj);
2132 Py_DECREF(strobj);
2133 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002134}
2135
2136PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002137PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002138{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002139 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2140 if (unicode == NULL)
2141 return NULL;
2142 v = PyLong_FromUnicodeObject(unicode, base);
2143 Py_DECREF(unicode);
2144 return v;
2145}
2146
2147PyObject *
2148PyLong_FromUnicodeObject(PyObject *u, int base)
2149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002151 PyObject *asciidig;
2152 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002153 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002154
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002155 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002156 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002159 if (buffer == NULL) {
2160 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 return NULL;
2162 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002163 result = PyLong_FromString(buffer, &end, base);
2164 if (result != NULL && end != buffer + buflen) {
2165 PyErr_SetString(PyExc_ValueError,
2166 "null byte in argument for int()");
2167 Py_DECREF(result);
2168 result = NULL;
2169 }
2170 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002172}
2173
Tim Peters9f688bf2000-07-07 15:53:28 +00002174/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002175static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002177static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002178
2179/* Long division with remainder, top-level routine */
2180
Guido van Rossume32e0141992-01-19 16:31:05 +00002181static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002182long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2186 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (size_b == 0) {
2189 PyErr_SetString(PyExc_ZeroDivisionError,
2190 "integer division or modulo by zero");
2191 return -1;
2192 }
2193 if (size_a < size_b ||
2194 (size_a == size_b &&
2195 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2196 /* |a| < |b|. */
2197 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2198 if (*pdiv == NULL)
2199 return -1;
2200 Py_INCREF(a);
2201 *prem = (PyLongObject *) a;
2202 return 0;
2203 }
2204 if (size_b == 1) {
2205 digit rem = 0;
2206 z = divrem1(a, b->ob_digit[0], &rem);
2207 if (z == NULL)
2208 return -1;
2209 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2210 if (*prem == NULL) {
2211 Py_DECREF(z);
2212 return -1;
2213 }
2214 }
2215 else {
2216 z = x_divrem(a, b, prem);
2217 if (z == NULL)
2218 return -1;
2219 }
2220 /* Set the signs.
2221 The quotient z has the sign of a*b;
2222 the remainder r has the sign of a,
2223 so a = b*z + r. */
2224 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2225 NEGATE(z);
2226 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2227 NEGATE(*prem);
2228 *pdiv = maybe_small_long(z);
2229 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002230}
2231
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002232/* Unsigned long division with remainder -- the algorithm. The arguments v1
2233 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002236x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 PyLongObject *v, *w, *a;
2239 Py_ssize_t i, k, size_v, size_w;
2240 int d;
2241 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2242 twodigits vv;
2243 sdigit zhi;
2244 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2247 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2248 handle the special case when the initial estimate q for a quotient
2249 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2250 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 /* allocate space; w will also be used to hold the final remainder */
2253 size_v = ABS(Py_SIZE(v1));
2254 size_w = ABS(Py_SIZE(w1));
2255 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2256 v = _PyLong_New(size_v+1);
2257 if (v == NULL) {
2258 *prem = NULL;
2259 return NULL;
2260 }
2261 w = _PyLong_New(size_w);
2262 if (w == NULL) {
2263 Py_DECREF(v);
2264 *prem = NULL;
2265 return NULL;
2266 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2269 shift v1 left by the same amount. Results go into w and v. */
2270 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2271 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2272 assert(carry == 0);
2273 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2274 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2275 v->ob_digit[size_v] = carry;
2276 size_v++;
2277 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2280 at most (and usually exactly) k = size_v - size_w digits. */
2281 k = size_v - size_w;
2282 assert(k >= 0);
2283 a = _PyLong_New(k);
2284 if (a == NULL) {
2285 Py_DECREF(w);
2286 Py_DECREF(v);
2287 *prem = NULL;
2288 return NULL;
2289 }
2290 v0 = v->ob_digit;
2291 w0 = w->ob_digit;
2292 wm1 = w0[size_w-1];
2293 wm2 = w0[size_w-2];
2294 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2295 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2296 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002299 Py_DECREF(a);
2300 Py_DECREF(w);
2301 Py_DECREF(v);
2302 *prem = NULL;
2303 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002304 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* estimate quotient digit q; may overestimate by 1 (rare) */
2307 vtop = vk[size_w];
2308 assert(vtop <= wm1);
2309 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2310 q = (digit)(vv / wm1);
2311 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2312 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2313 | vk[size_w-2])) {
2314 --q;
2315 r += wm1;
2316 if (r >= PyLong_BASE)
2317 break;
2318 }
2319 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2322 zhi = 0;
2323 for (i = 0; i < size_w; ++i) {
2324 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2325 -PyLong_BASE * q <= z < PyLong_BASE */
2326 z = (sdigit)vk[i] + zhi -
2327 (stwodigits)q * (stwodigits)w0[i];
2328 vk[i] = (digit)z & PyLong_MASK;
2329 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002330 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* add w back if q was too large (this branch taken rarely) */
2334 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2335 if ((sdigit)vtop + zhi < 0) {
2336 carry = 0;
2337 for (i = 0; i < size_w; ++i) {
2338 carry += vk[i] + w0[i];
2339 vk[i] = carry & PyLong_MASK;
2340 carry >>= PyLong_SHIFT;
2341 }
2342 --q;
2343 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 /* store quotient digit */
2346 assert(q < PyLong_BASE);
2347 *--ak = q;
2348 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* unshift remainder; we reuse w to store the result */
2351 carry = v_rshift(w0, v0, size_w, d);
2352 assert(carry==0);
2353 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 *prem = long_normalize(w);
2356 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357}
2358
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002359/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2360 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2361 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2362 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2363 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2364 -1.0. */
2365
2366/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2367#if DBL_MANT_DIG == 53
2368#define EXP2_DBL_MANT_DIG 9007199254740992.0
2369#else
2370#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2371#endif
2372
2373double
2374_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2377 /* See below for why x_digits is always large enough. */
2378 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2379 double dx;
2380 /* Correction term for round-half-to-even rounding. For a digit x,
2381 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2382 multiple of 4, rounding ties to a multiple of 8. */
2383 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 a_size = ABS(Py_SIZE(a));
2386 if (a_size == 0) {
2387 /* Special case for 0: significand 0.0, exponent 0. */
2388 *e = 0;
2389 return 0.0;
2390 }
2391 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2392 /* The following is an overflow-free version of the check
2393 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2394 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2395 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2396 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002397 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2401 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 Number of digits needed for result: write // for floor division.
2404 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2413 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2416 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2417 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 in both cases.
2424 */
2425 if (a_bits <= DBL_MANT_DIG + 2) {
2426 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2427 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2428 x_size = 0;
2429 while (x_size < shift_digits)
2430 x_digits[x_size++] = 0;
2431 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2432 (int)shift_bits);
2433 x_size += a_size;
2434 x_digits[x_size++] = rem;
2435 }
2436 else {
2437 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2438 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2439 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2440 a_size - shift_digits, (int)shift_bits);
2441 x_size = a_size - shift_digits;
2442 /* For correct rounding below, we need the least significant
2443 bit of x to be 'sticky' for this shift: if any of the bits
2444 shifted out was nonzero, we set the least significant bit
2445 of x. */
2446 if (rem)
2447 x_digits[0] |= 1;
2448 else
2449 while (shift_digits > 0)
2450 if (a->ob_digit[--shift_digits]) {
2451 x_digits[0] |= 1;
2452 break;
2453 }
2454 }
Victor Stinner63941882011-09-29 00:42:28 +02002455 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* Round, and convert to double. */
2458 x_digits[0] += half_even_correction[x_digits[0] & 7];
2459 dx = x_digits[--x_size];
2460 while (x_size > 0)
2461 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* Rescale; make correction if result is 1.0. */
2464 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2465 if (dx == 1.0) {
2466 if (a_bits == PY_SSIZE_T_MAX)
2467 goto overflow;
2468 dx = 0.5;
2469 a_bits += 1;
2470 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 *e = a_bits;
2473 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002474
2475 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* exponent > PY_SSIZE_T_MAX */
2477 PyErr_SetString(PyExc_OverflowError,
2478 "huge integer: number of bits overflows a Py_ssize_t");
2479 *e = 0;
2480 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002481}
2482
2483/* Get a C double from a long int object. Rounds to the nearest double,
2484 using the round-half-to-even rule in the case of a tie. */
2485
2486double
2487PyLong_AsDouble(PyObject *v)
2488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 Py_ssize_t exponent;
2490 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002491
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002492 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 PyErr_BadInternalCall();
2494 return -1.0;
2495 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002496 if (!PyLong_Check(v)) {
2497 PyErr_SetString(PyExc_TypeError, "an integer is required");
2498 return -1.0;
2499 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2501 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2502 PyErr_SetString(PyExc_OverflowError,
2503 "long int too large to convert to float");
2504 return -1.0;
2505 }
2506 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002507}
2508
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002509/* Methods */
2510
2511static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002512long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002515}
2516
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002517static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002518long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (Py_SIZE(a) != Py_SIZE(b)) {
2523 sign = Py_SIZE(a) - Py_SIZE(b);
2524 }
2525 else {
2526 Py_ssize_t i = ABS(Py_SIZE(a));
2527 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2528 ;
2529 if (i < 0)
2530 sign = 0;
2531 else {
2532 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2533 if (Py_SIZE(a) < 0)
2534 sign = -sign;
2535 }
2536 }
2537 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002538}
2539
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002540#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002542
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002543static PyObject *
2544long_richcompare(PyObject *self, PyObject *other, int op)
2545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 int result;
2547 PyObject *v;
2548 CHECK_BINOP(self, other);
2549 if (self == other)
2550 result = 0;
2551 else
2552 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2553 /* Convert the return value to a Boolean */
2554 switch (op) {
2555 case Py_EQ:
2556 v = TEST_COND(result == 0);
2557 break;
2558 case Py_NE:
2559 v = TEST_COND(result != 0);
2560 break;
2561 case Py_LE:
2562 v = TEST_COND(result <= 0);
2563 break;
2564 case Py_GE:
2565 v = TEST_COND(result >= 0);
2566 break;
2567 case Py_LT:
2568 v = TEST_COND(result == -1);
2569 break;
2570 case Py_GT:
2571 v = TEST_COND(result == 1);
2572 break;
2573 default:
2574 PyErr_BadArgument();
2575 return NULL;
2576 }
2577 Py_INCREF(v);
2578 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002579}
2580
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002581static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002582long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002583{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002584 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 Py_ssize_t i;
2586 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 i = Py_SIZE(v);
2589 switch(i) {
2590 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2591 case 0: return 0;
2592 case 1: return v->ob_digit[0];
2593 }
2594 sign = 1;
2595 x = 0;
2596 if (i < 0) {
2597 sign = -1;
2598 i = -(i);
2599 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002601 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2602 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2603 _PyHASH_MODULUS.
2604
2605 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2606 amounts to a rotation of the bits of x. To see this, write
2607
2608 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2609
2610 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2611 PyLong_SHIFT bits of x (those that are shifted out of the
2612 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2613 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2614 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2615 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2616 congruent to y modulo _PyHASH_MODULUS. So
2617
2618 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2619
2620 The right-hand side is just the result of rotating the
2621 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2622 not all _PyHASH_BITS bits of x are 1s, the same is true
2623 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2624 the reduction of x*2**PyLong_SHIFT modulo
2625 _PyHASH_MODULUS. */
2626 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2627 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002629 if (x >= _PyHASH_MODULUS)
2630 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 }
2632 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002633 if (x == (Py_uhash_t)-1)
2634 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002635 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002636}
2637
2638
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002639/* Add the absolute values of two long integers. */
2640
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002641static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002642x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2645 PyLongObject *z;
2646 Py_ssize_t i;
2647 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 /* Ensure a is the larger of the two: */
2650 if (size_a < size_b) {
2651 { PyLongObject *temp = a; a = b; b = temp; }
2652 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002653 size_a = size_b;
2654 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 }
2656 z = _PyLong_New(size_a+1);
2657 if (z == NULL)
2658 return NULL;
2659 for (i = 0; i < size_b; ++i) {
2660 carry += a->ob_digit[i] + b->ob_digit[i];
2661 z->ob_digit[i] = carry & PyLong_MASK;
2662 carry >>= PyLong_SHIFT;
2663 }
2664 for (; i < size_a; ++i) {
2665 carry += a->ob_digit[i];
2666 z->ob_digit[i] = carry & PyLong_MASK;
2667 carry >>= PyLong_SHIFT;
2668 }
2669 z->ob_digit[i] = carry;
2670 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002671}
2672
2673/* Subtract the absolute values of two integers. */
2674
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002675static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002676x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2679 PyLongObject *z;
2680 Py_ssize_t i;
2681 int sign = 1;
2682 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 /* Ensure a is the larger of the two: */
2685 if (size_a < size_b) {
2686 sign = -1;
2687 { PyLongObject *temp = a; a = b; b = temp; }
2688 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002689 size_a = size_b;
2690 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 }
2692 else if (size_a == size_b) {
2693 /* Find highest digit where a and b differ: */
2694 i = size_a;
2695 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2696 ;
2697 if (i < 0)
2698 return (PyLongObject *)PyLong_FromLong(0);
2699 if (a->ob_digit[i] < b->ob_digit[i]) {
2700 sign = -1;
2701 { PyLongObject *temp = a; a = b; b = temp; }
2702 }
2703 size_a = size_b = i+1;
2704 }
2705 z = _PyLong_New(size_a);
2706 if (z == NULL)
2707 return NULL;
2708 for (i = 0; i < size_b; ++i) {
2709 /* The following assumes unsigned arithmetic
2710 works module 2**N for some N>PyLong_SHIFT. */
2711 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2712 z->ob_digit[i] = borrow & PyLong_MASK;
2713 borrow >>= PyLong_SHIFT;
2714 borrow &= 1; /* Keep only one sign bit */
2715 }
2716 for (; i < size_a; ++i) {
2717 borrow = a->ob_digit[i] - borrow;
2718 z->ob_digit[i] = borrow & PyLong_MASK;
2719 borrow >>= PyLong_SHIFT;
2720 borrow &= 1; /* Keep only one sign bit */
2721 }
2722 assert(borrow == 0);
2723 if (sign < 0)
2724 NEGATE(z);
2725 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002726}
2727
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002728static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002729long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2736 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2737 MEDIUM_VALUE(b));
2738 return result;
2739 }
2740 if (Py_SIZE(a) < 0) {
2741 if (Py_SIZE(b) < 0) {
2742 z = x_add(a, b);
2743 if (z != NULL && Py_SIZE(z) != 0)
2744 Py_SIZE(z) = -(Py_SIZE(z));
2745 }
2746 else
2747 z = x_sub(b, a);
2748 }
2749 else {
2750 if (Py_SIZE(b) < 0)
2751 z = x_sub(a, b);
2752 else
2753 z = x_add(a, b);
2754 }
2755 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002756}
2757
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002758static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002759long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2766 PyObject* r;
2767 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2768 return r;
2769 }
2770 if (Py_SIZE(a) < 0) {
2771 if (Py_SIZE(b) < 0)
2772 z = x_sub(a, b);
2773 else
2774 z = x_add(a, b);
2775 if (z != NULL && Py_SIZE(z) != 0)
2776 Py_SIZE(z) = -(Py_SIZE(z));
2777 }
2778 else {
2779 if (Py_SIZE(b) < 0)
2780 z = x_add(a, b);
2781 else
2782 z = x_sub(a, b);
2783 }
2784 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002785}
2786
Tim Peters5af4e6c2002-08-12 02:31:19 +00002787/* Grade school multiplication, ignoring the signs.
2788 * Returns the absolute value of the product, or NULL if error.
2789 */
2790static PyLongObject *
2791x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 PyLongObject *z;
2794 Py_ssize_t size_a = ABS(Py_SIZE(a));
2795 Py_ssize_t size_b = ABS(Py_SIZE(b));
2796 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 z = _PyLong_New(size_a + size_b);
2799 if (z == NULL)
2800 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2803 if (a == b) {
2804 /* Efficient squaring per HAC, Algorithm 14.16:
2805 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2806 * Gives slightly less than a 2x speedup when a == b,
2807 * via exploiting that each entry in the multiplication
2808 * pyramid appears twice (except for the size_a squares).
2809 */
2810 for (i = 0; i < size_a; ++i) {
2811 twodigits carry;
2812 twodigits f = a->ob_digit[i];
2813 digit *pz = z->ob_digit + (i << 1);
2814 digit *pa = a->ob_digit + i + 1;
2815 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002818 Py_DECREF(z);
2819 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002820 });
Tim Peters0973b992004-08-29 22:16:50 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 carry = *pz + f * f;
2823 *pz++ = (digit)(carry & PyLong_MASK);
2824 carry >>= PyLong_SHIFT;
2825 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* Now f is added in twice in each column of the
2828 * pyramid it appears. Same as adding f<<1 once.
2829 */
2830 f <<= 1;
2831 while (pa < paend) {
2832 carry += *pz + *pa++ * f;
2833 *pz++ = (digit)(carry & PyLong_MASK);
2834 carry >>= PyLong_SHIFT;
2835 assert(carry <= (PyLong_MASK << 1));
2836 }
2837 if (carry) {
2838 carry += *pz;
2839 *pz++ = (digit)(carry & PyLong_MASK);
2840 carry >>= PyLong_SHIFT;
2841 }
2842 if (carry)
2843 *pz += (digit)(carry & PyLong_MASK);
2844 assert((carry >> PyLong_SHIFT) == 0);
2845 }
2846 }
2847 else { /* a is not the same as b -- gradeschool long mult */
2848 for (i = 0; i < size_a; ++i) {
2849 twodigits carry = 0;
2850 twodigits f = a->ob_digit[i];
2851 digit *pz = z->ob_digit + i;
2852 digit *pb = b->ob_digit;
2853 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002856 Py_DECREF(z);
2857 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002858 });
Tim Peters0973b992004-08-29 22:16:50 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 while (pb < pbend) {
2861 carry += *pz + *pb++ * f;
2862 *pz++ = (digit)(carry & PyLong_MASK);
2863 carry >>= PyLong_SHIFT;
2864 assert(carry <= PyLong_MASK);
2865 }
2866 if (carry)
2867 *pz += (digit)(carry & PyLong_MASK);
2868 assert((carry >> PyLong_SHIFT) == 0);
2869 }
2870 }
2871 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002872}
2873
2874/* A helper for Karatsuba multiplication (k_mul).
2875 Takes a long "n" and an integer "size" representing the place to
2876 split, and sets low and high such that abs(n) == (high << size) + low,
2877 viewing the shift as being by digits. The sign bit is ignored, and
2878 the return values are >= 0.
2879 Returns 0 on success, -1 on failure.
2880*/
2881static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002882kmul_split(PyLongObject *n,
2883 Py_ssize_t size,
2884 PyLongObject **high,
2885 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyLongObject *hi, *lo;
2888 Py_ssize_t size_lo, size_hi;
2889 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 size_lo = MIN(size_n, size);
2892 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 if ((hi = _PyLong_New(size_hi)) == NULL)
2895 return -1;
2896 if ((lo = _PyLong_New(size_lo)) == NULL) {
2897 Py_DECREF(hi);
2898 return -1;
2899 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2902 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 *high = long_normalize(hi);
2905 *low = long_normalize(lo);
2906 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002907}
2908
Tim Peters60004642002-08-12 22:01:34 +00002909static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2910
Tim Peters5af4e6c2002-08-12 02:31:19 +00002911/* Karatsuba multiplication. Ignores the input signs, and returns the
2912 * absolute value of the product (or NULL if error).
2913 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2914 */
2915static PyLongObject *
2916k_mul(PyLongObject *a, PyLongObject *b)
2917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 Py_ssize_t asize = ABS(Py_SIZE(a));
2919 Py_ssize_t bsize = ABS(Py_SIZE(b));
2920 PyLongObject *ah = NULL;
2921 PyLongObject *al = NULL;
2922 PyLongObject *bh = NULL;
2923 PyLongObject *bl = NULL;
2924 PyLongObject *ret = NULL;
2925 PyLongObject *t1, *t2, *t3;
2926 Py_ssize_t shift; /* the number of digits we split off */
2927 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2930 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2931 * Then the original product is
2932 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2933 * By picking X to be a power of 2, "*X" is just shifting, and it's
2934 * been reduced to 3 multiplies on numbers half the size.
2935 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 /* We want to split based on the larger number; fiddle so that b
2938 * is largest.
2939 */
2940 if (asize > bsize) {
2941 t1 = a;
2942 a = b;
2943 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 i = asize;
2946 asize = bsize;
2947 bsize = i;
2948 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 /* Use gradeschool math when either number is too small. */
2951 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2952 if (asize <= i) {
2953 if (asize == 0)
2954 return (PyLongObject *)PyLong_FromLong(0);
2955 else
2956 return x_mul(a, b);
2957 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 /* If a is small compared to b, splitting on b gives a degenerate
2960 * case with ah==0, and Karatsuba may be (even much) less efficient
2961 * than "grade school" then. However, we can still win, by viewing
2962 * b as a string of "big digits", each of width a->ob_size. That
2963 * leads to a sequence of balanced calls to k_mul.
2964 */
2965 if (2 * asize <= bsize)
2966 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 /* Split a & b into hi & lo pieces. */
2969 shift = bsize >> 1;
2970 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2971 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 if (a == b) {
2974 bh = ah;
2975 bl = al;
2976 Py_INCREF(bh);
2977 Py_INCREF(bl);
2978 }
2979 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 /* The plan:
2982 * 1. Allocate result space (asize + bsize digits: that's always
2983 * enough).
2984 * 2. Compute ah*bh, and copy into result at 2*shift.
2985 * 3. Compute al*bl, and copy into result at 0. Note that this
2986 * can't overlap with #2.
2987 * 4. Subtract al*bl from the result, starting at shift. This may
2988 * underflow (borrow out of the high digit), but we don't care:
2989 * we're effectively doing unsigned arithmetic mod
2990 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2991 * borrows and carries out of the high digit can be ignored.
2992 * 5. Subtract ah*bh from the result, starting at shift.
2993 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2994 * at shift.
2995 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 /* 1. Allocate result space. */
2998 ret = _PyLong_New(asize + bsize);
2999 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003000#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 /* Fill with trash, to catch reference to uninitialized digits. */
3002 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003003#endif
Tim Peters44121a62002-08-12 06:17:58 +00003004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3006 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3007 assert(Py_SIZE(t1) >= 0);
3008 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3009 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3010 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 /* Zero-out the digits higher than the ah*bh copy. */
3013 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3014 if (i)
3015 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3016 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 /* 3. t2 <- al*bl, and copy into the low digits. */
3019 if ((t2 = k_mul(al, bl)) == NULL) {
3020 Py_DECREF(t1);
3021 goto fail;
3022 }
3023 assert(Py_SIZE(t2) >= 0);
3024 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3025 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 /* Zero out remaining digits. */
3028 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3029 if (i)
3030 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3033 * because it's fresher in cache.
3034 */
3035 i = Py_SIZE(ret) - shift; /* # digits after shift */
3036 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3037 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3040 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3043 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3044 Py_DECREF(ah);
3045 Py_DECREF(al);
3046 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 if (a == b) {
3049 t2 = t1;
3050 Py_INCREF(t2);
3051 }
3052 else if ((t2 = x_add(bh, bl)) == NULL) {
3053 Py_DECREF(t1);
3054 goto fail;
3055 }
3056 Py_DECREF(bh);
3057 Py_DECREF(bl);
3058 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 t3 = k_mul(t1, t2);
3061 Py_DECREF(t1);
3062 Py_DECREF(t2);
3063 if (t3 == NULL) goto fail;
3064 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 /* Add t3. It's not obvious why we can't run out of room here.
3067 * See the (*) comment after this function.
3068 */
3069 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3070 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003073
Mark Dickinson22b20182010-05-10 21:27:53 +00003074 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 Py_XDECREF(ret);
3076 Py_XDECREF(ah);
3077 Py_XDECREF(al);
3078 Py_XDECREF(bh);
3079 Py_XDECREF(bl);
3080 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003081}
3082
Tim Petersd6974a52002-08-13 20:37:51 +00003083/* (*) Why adding t3 can't "run out of room" above.
3084
Tim Petersab86c2b2002-08-15 20:06:00 +00003085Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3086to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003087
Tim Petersab86c2b2002-08-15 20:06:00 +000030881. For any integer i, i = c(i/2) + f(i/2). In particular,
3089 bsize = c(bsize/2) + f(bsize/2).
30902. shift = f(bsize/2)
30913. asize <= bsize
30924. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3093 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003094
Tim Petersab86c2b2002-08-15 20:06:00 +00003095We allocated asize + bsize result digits, and add t3 into them at an offset
3096of shift. This leaves asize+bsize-shift allocated digit positions for t3
3097to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3098asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003099
Tim Petersab86c2b2002-08-15 20:06:00 +00003100bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3101at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003102
Tim Petersab86c2b2002-08-15 20:06:00 +00003103If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3104digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3105most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003106
Tim Petersab86c2b2002-08-15 20:06:00 +00003107The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003108
Tim Petersab86c2b2002-08-15 20:06:00 +00003109 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003110
Tim Petersab86c2b2002-08-15 20:06:00 +00003111and we have asize + c(bsize/2) available digit positions. We need to show
3112this is always enough. An instance of c(bsize/2) cancels out in both, so
3113the question reduces to whether asize digits is enough to hold
3114(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3115then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3116asize 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 +00003117digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003118asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003119c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3120is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3121bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003122
Tim Peters48d52c02002-08-14 17:07:32 +00003123Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3124clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3125ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003126*/
3127
Tim Peters60004642002-08-12 22:01:34 +00003128/* b has at least twice the digits of a, and a is big enough that Karatsuba
3129 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3130 * of slices, each with a->ob_size digits, and multiply the slices by a,
3131 * one at a time. This gives k_mul balanced inputs to work with, and is
3132 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003133 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003134 * single-width slice overlap between successive partial sums).
3135 */
3136static PyLongObject *
3137k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 const Py_ssize_t asize = ABS(Py_SIZE(a));
3140 Py_ssize_t bsize = ABS(Py_SIZE(b));
3141 Py_ssize_t nbdone; /* # of b digits already multiplied */
3142 PyLongObject *ret;
3143 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 assert(asize > KARATSUBA_CUTOFF);
3146 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* Allocate result space, and zero it out. */
3149 ret = _PyLong_New(asize + bsize);
3150 if (ret == NULL)
3151 return NULL;
3152 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* Successive slices of b are copied into bslice. */
3155 bslice = _PyLong_New(asize);
3156 if (bslice == NULL)
3157 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 nbdone = 0;
3160 while (bsize > 0) {
3161 PyLongObject *product;
3162 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* Multiply the next slice of b by a. */
3165 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3166 nbtouse * sizeof(digit));
3167 Py_SIZE(bslice) = nbtouse;
3168 product = k_mul(a, bslice);
3169 if (product == NULL)
3170 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 /* Add into result. */
3173 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3174 product->ob_digit, Py_SIZE(product));
3175 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 bsize -= nbtouse;
3178 nbdone += nbtouse;
3179 }
Tim Peters60004642002-08-12 22:01:34 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 Py_DECREF(bslice);
3182 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003183
Mark Dickinson22b20182010-05-10 21:27:53 +00003184 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 Py_DECREF(ret);
3186 Py_XDECREF(bslice);
3187 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003188}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003189
3190static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003191long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 /* fast path for single-digit multiplication */
3198 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3199 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003200#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003202#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* if we don't have long long then we're almost certainly
3204 using 15-bit digits, so v will fit in a long. In the
3205 unlikely event that we're using 30-bit digits on a platform
3206 without long long, a large v will just cause us to fall
3207 through to the general multiplication code below. */
3208 if (v >= LONG_MIN && v <= LONG_MAX)
3209 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003210#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 z = k_mul(a, b);
3214 /* Negate if exactly one of the inputs is negative. */
3215 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3216 NEGATE(z);
3217 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003218}
3219
Guido van Rossume32e0141992-01-19 16:31:05 +00003220/* The / and % operators are now defined in terms of divmod().
3221 The expression a mod b has the value a - b*floor(a/b).
3222 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003223 |a| by |b|, with the sign of a. This is also expressed
3224 as a - b*trunc(a/b), if trunc truncates towards zero.
3225 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 a b a rem b a mod b
3227 13 10 3 3
3228 -13 10 -3 7
3229 13 -10 3 -7
3230 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003231 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003232 have different signs. We then subtract one from the 'div'
3233 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003234
Tim Peters47e52ee2004-08-30 02:44:38 +00003235/* Compute
3236 * *pdiv, *pmod = divmod(v, w)
3237 * NULL can be passed for pdiv or pmod, in which case that part of
3238 * the result is simply thrown away. The caller owns a reference to
3239 * each of these it requests (does not pass NULL for).
3240 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003241static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003242l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 if (long_divrem(v, w, &div, &mod) < 0)
3248 return -1;
3249 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3250 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3251 PyLongObject *temp;
3252 PyLongObject *one;
3253 temp = (PyLongObject *) long_add(mod, w);
3254 Py_DECREF(mod);
3255 mod = temp;
3256 if (mod == NULL) {
3257 Py_DECREF(div);
3258 return -1;
3259 }
3260 one = (PyLongObject *) PyLong_FromLong(1L);
3261 if (one == NULL ||
3262 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3263 Py_DECREF(mod);
3264 Py_DECREF(div);
3265 Py_XDECREF(one);
3266 return -1;
3267 }
3268 Py_DECREF(one);
3269 Py_DECREF(div);
3270 div = temp;
3271 }
3272 if (pdiv != NULL)
3273 *pdiv = div;
3274 else
3275 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (pmod != NULL)
3278 *pmod = mod;
3279 else
3280 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003283}
3284
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003285static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003286long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 CHECK_BINOP(a, b);
3291 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3292 div = NULL;
3293 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003294}
3295
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003296/* PyLong/PyLong -> float, with correctly rounded result. */
3297
3298#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3299#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003301static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003302long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 PyLongObject *a, *b, *x;
3305 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3306 digit mask, low;
3307 int inexact, negate, a_is_small, b_is_small;
3308 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 CHECK_BINOP(v, w);
3311 a = (PyLongObject *)v;
3312 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 /*
3315 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3318 1. choose a suitable integer 'shift'
3319 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3320 3. adjust x for correct rounding
3321 4. convert x to a double dx with the same value
3322 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3327 returns either 0.0 or -0.0, depending on the sign of b. For a and
3328 b both nonzero, ignore signs of a and b, and add the sign back in
3329 at the end. Now write a_bits and b_bits for the bit lengths of a
3330 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3331 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3336 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3337 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3338 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 1. The integer 'shift' is chosen so that x has the right number of
3343 bits for a double, plus two or three extra bits that will be used
3344 in the rounding decisions. Writing a_bits and b_bits for the
3345 number of significant bits in a and b respectively, a
3346 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 This is fine in the usual case, but if a/b is smaller than the
3351 smallest normal float then it can lead to double rounding on an
3352 IEEE 754 platform, giving incorrectly rounded results. So we
3353 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 2. The quantity x is computed by first shifting a (left -shift bits
3358 if shift <= 0, right shift bits if shift > 0) and then dividing by
3359 b. For both the shift and the division, we keep track of whether
3360 the result is inexact, in a flag 'inexact'; this information is
3361 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 With the choice of shift above, together with our assumption that
3364 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3365 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3368 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 For float representability, we need x/2**extra_bits <
3373 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3374 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 To round, we just modify the bottom digit of x in-place; this can
3379 end up giving a digit with value > PyLONG_MASK, but that's not a
3380 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 With the original choices for shift above, extra_bits will always
3383 be 2 or 3. Then rounding under the round-half-to-even rule, we
3384 round up iff the most significant of the extra bits is 1, and
3385 either: (a) the computation of x in step 2 had an inexact result,
3386 or (b) at least one other of the extra bits is 1, or (c) the least
3387 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 4. Conversion to a double is straightforward; all floating-point
3390 operations involved in the conversion are exact, so there's no
3391 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3394 The result will always be exactly representable as a double, except
3395 in the case that it overflows. To avoid dependence on the exact
3396 behaviour of ldexp on overflow, we check for overflow before
3397 applying ldexp. The result of ldexp is adjusted for sign before
3398 returning.
3399 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* Reduce to case where a and b are both positive. */
3402 a_size = ABS(Py_SIZE(a));
3403 b_size = ABS(Py_SIZE(b));
3404 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3405 if (b_size == 0) {
3406 PyErr_SetString(PyExc_ZeroDivisionError,
3407 "division by zero");
3408 goto error;
3409 }
3410 if (a_size == 0)
3411 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 /* Fast path for a and b small (exactly representable in a double).
3414 Relies on floating-point division being correctly rounded; results
3415 may be subject to double rounding on x86 machines that operate with
3416 the x87 FPU set to 64-bit precision. */
3417 a_is_small = a_size <= MANT_DIG_DIGITS ||
3418 (a_size == MANT_DIG_DIGITS+1 &&
3419 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3420 b_is_small = b_size <= MANT_DIG_DIGITS ||
3421 (b_size == MANT_DIG_DIGITS+1 &&
3422 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3423 if (a_is_small && b_is_small) {
3424 double da, db;
3425 da = a->ob_digit[--a_size];
3426 while (a_size > 0)
3427 da = da * PyLong_BASE + a->ob_digit[--a_size];
3428 db = b->ob_digit[--b_size];
3429 while (b_size > 0)
3430 db = db * PyLong_BASE + b->ob_digit[--b_size];
3431 result = da / db;
3432 goto success;
3433 }
Tim Peterse2a60002001-09-04 06:17:36 +00003434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 /* Catch obvious cases of underflow and overflow */
3436 diff = a_size - b_size;
3437 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3438 /* Extreme overflow */
3439 goto overflow;
3440 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3441 /* Extreme underflow */
3442 goto underflow_or_zero;
3443 /* Next line is now safe from overflowing a Py_ssize_t */
3444 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3445 bits_in_digit(b->ob_digit[b_size - 1]);
3446 /* Now diff = a_bits - b_bits. */
3447 if (diff > DBL_MAX_EXP)
3448 goto overflow;
3449 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3450 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 /* Choose value for shift; see comments for step 1 above. */
3453 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 /* x = abs(a * 2**-shift) */
3458 if (shift <= 0) {
3459 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3460 digit rem;
3461 /* x = a << -shift */
3462 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3463 /* In practice, it's probably impossible to end up
3464 here. Both a and b would have to be enormous,
3465 using close to SIZE_T_MAX bytes of memory each. */
3466 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003467 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 goto error;
3469 }
3470 x = _PyLong_New(a_size + shift_digits + 1);
3471 if (x == NULL)
3472 goto error;
3473 for (i = 0; i < shift_digits; i++)
3474 x->ob_digit[i] = 0;
3475 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3476 a_size, -shift % PyLong_SHIFT);
3477 x->ob_digit[a_size + shift_digits] = rem;
3478 }
3479 else {
3480 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3481 digit rem;
3482 /* x = a >> shift */
3483 assert(a_size >= shift_digits);
3484 x = _PyLong_New(a_size - shift_digits);
3485 if (x == NULL)
3486 goto error;
3487 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3488 a_size - shift_digits, shift % PyLong_SHIFT);
3489 /* set inexact if any of the bits shifted out is nonzero */
3490 if (rem)
3491 inexact = 1;
3492 while (!inexact && shift_digits > 0)
3493 if (a->ob_digit[--shift_digits])
3494 inexact = 1;
3495 }
3496 long_normalize(x);
3497 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3500 reference to x, so it's safe to modify it in-place. */
3501 if (b_size == 1) {
3502 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3503 b->ob_digit[0]);
3504 long_normalize(x);
3505 if (rem)
3506 inexact = 1;
3507 }
3508 else {
3509 PyLongObject *div, *rem;
3510 div = x_divrem(x, b, &rem);
3511 Py_DECREF(x);
3512 x = div;
3513 if (x == NULL)
3514 goto error;
3515 if (Py_SIZE(rem))
3516 inexact = 1;
3517 Py_DECREF(rem);
3518 }
3519 x_size = ABS(Py_SIZE(x));
3520 assert(x_size > 0); /* result of division is never zero */
3521 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 /* The number of extra bits that have to be rounded away. */
3524 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3525 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 /* Round by directly modifying the low digit of x. */
3528 mask = (digit)1 << (extra_bits - 1);
3529 low = x->ob_digit[0] | inexact;
3530 if (low & mask && low & (3*mask-1))
3531 low += mask;
3532 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 /* Convert x to a double dx; the conversion is exact. */
3535 dx = x->ob_digit[--x_size];
3536 while (x_size > 0)
3537 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3538 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 /* Check whether ldexp result will overflow a double. */
3541 if (shift + x_bits >= DBL_MAX_EXP &&
3542 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3543 goto overflow;
3544 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003545
3546 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003548
3549 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003551
3552 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 PyErr_SetString(PyExc_OverflowError,
3554 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003555 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003557}
3558
3559static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003560long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 CHECK_BINOP(a, b);
3565
3566 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3567 mod = NULL;
3568 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003569}
3570
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003571static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003572long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 PyLongObject *div, *mod;
3575 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3580 return NULL;
3581 }
3582 z = PyTuple_New(2);
3583 if (z != NULL) {
3584 PyTuple_SetItem(z, 0, (PyObject *) div);
3585 PyTuple_SetItem(z, 1, (PyObject *) mod);
3586 }
3587 else {
3588 Py_DECREF(div);
3589 Py_DECREF(mod);
3590 }
3591 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003592}
3593
Tim Peters47e52ee2004-08-30 02:44:38 +00003594/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003595static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003596long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3599 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 PyLongObject *z = NULL; /* accumulated result */
3602 Py_ssize_t i, j, k; /* counters */
3603 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 /* 5-ary values. If the exponent is large enough, table is
3606 * precomputed so that table[i] == a**i % c for i in range(32).
3607 */
3608 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3609 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 /* a, b, c = v, w, x */
3612 CHECK_BINOP(v, w);
3613 a = (PyLongObject*)v; Py_INCREF(a);
3614 b = (PyLongObject*)w; Py_INCREF(b);
3615 if (PyLong_Check(x)) {
3616 c = (PyLongObject *)x;
3617 Py_INCREF(x);
3618 }
3619 else if (x == Py_None)
3620 c = NULL;
3621 else {
3622 Py_DECREF(a);
3623 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003624 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 }
Tim Peters4c483c42001-09-05 06:24:58 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3628 if (c) {
3629 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003630 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 goto Error;
3632 }
3633 else {
3634 /* else return a float. This works because we know
3635 that this calls float_pow() which converts its
3636 arguments to double. */
3637 Py_DECREF(a);
3638 Py_DECREF(b);
3639 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3640 }
3641 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 if (c) {
3644 /* if modulus == 0:
3645 raise ValueError() */
3646 if (Py_SIZE(c) == 0) {
3647 PyErr_SetString(PyExc_ValueError,
3648 "pow() 3rd argument cannot be 0");
3649 goto Error;
3650 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 /* if modulus < 0:
3653 negativeOutput = True
3654 modulus = -modulus */
3655 if (Py_SIZE(c) < 0) {
3656 negativeOutput = 1;
3657 temp = (PyLongObject *)_PyLong_Copy(c);
3658 if (temp == NULL)
3659 goto Error;
3660 Py_DECREF(c);
3661 c = temp;
3662 temp = NULL;
3663 NEGATE(c);
3664 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 /* if modulus == 1:
3667 return 0 */
3668 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3669 z = (PyLongObject *)PyLong_FromLong(0L);
3670 goto Done;
3671 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 /* if base < 0:
3674 base = base % modulus
3675 Having the base positive just makes things easier. */
3676 if (Py_SIZE(a) < 0) {
3677 if (l_divmod(a, c, NULL, &temp) < 0)
3678 goto Error;
3679 Py_DECREF(a);
3680 a = temp;
3681 temp = NULL;
3682 }
3683 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 /* At this point a, b, and c are guaranteed non-negative UNLESS
3686 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 z = (PyLongObject *)PyLong_FromLong(1L);
3689 if (z == NULL)
3690 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 /* Perform a modular reduction, X = X % c, but leave X alone if c
3693 * is NULL.
3694 */
3695#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003696 do { \
3697 if (c != NULL) { \
3698 if (l_divmod(X, c, NULL, &temp) < 0) \
3699 goto Error; \
3700 Py_XDECREF(X); \
3701 X = temp; \
3702 temp = NULL; \
3703 } \
3704 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 /* Multiply two values, then reduce the result:
3707 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003708#define MULT(X, Y, result) \
3709 do { \
3710 temp = (PyLongObject *)long_mul(X, Y); \
3711 if (temp == NULL) \
3712 goto Error; \
3713 Py_XDECREF(result); \
3714 result = temp; \
3715 temp = NULL; \
3716 REDUCE(result); \
3717 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3720 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3721 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3722 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3723 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003726 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003727 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003728 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 }
3730 }
3731 }
3732 else {
3733 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3734 Py_INCREF(z); /* still holds 1L */
3735 table[0] = z;
3736 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003737 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3740 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3743 const int index = (bi >> j) & 0x1f;
3744 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003745 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003747 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 }
3749 }
3750 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 if (negativeOutput && (Py_SIZE(z) != 0)) {
3753 temp = (PyLongObject *)long_sub(z, c);
3754 if (temp == NULL)
3755 goto Error;
3756 Py_DECREF(z);
3757 z = temp;
3758 temp = NULL;
3759 }
3760 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003761
Mark Dickinson22b20182010-05-10 21:27:53 +00003762 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 if (z != NULL) {
3764 Py_DECREF(z);
3765 z = NULL;
3766 }
3767 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003768 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3770 for (i = 0; i < 32; ++i)
3771 Py_XDECREF(table[i]);
3772 }
3773 Py_DECREF(a);
3774 Py_DECREF(b);
3775 Py_XDECREF(c);
3776 Py_XDECREF(temp);
3777 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003778}
3779
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003780static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003781long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 /* Implement ~x as -(x+1) */
3784 PyLongObject *x;
3785 PyLongObject *w;
3786 if (ABS(Py_SIZE(v)) <=1)
3787 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3788 w = (PyLongObject *)PyLong_FromLong(1L);
3789 if (w == NULL)
3790 return NULL;
3791 x = (PyLongObject *) long_add(v, w);
3792 Py_DECREF(w);
3793 if (x == NULL)
3794 return NULL;
3795 Py_SIZE(x) = -(Py_SIZE(x));
3796 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003797}
3798
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003799static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003800long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 PyLongObject *z;
3803 if (ABS(Py_SIZE(v)) <= 1)
3804 return PyLong_FromLong(-MEDIUM_VALUE(v));
3805 z = (PyLongObject *)_PyLong_Copy(v);
3806 if (z != NULL)
3807 Py_SIZE(z) = -(Py_SIZE(v));
3808 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003809}
3810
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003811static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003812long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 if (Py_SIZE(v) < 0)
3815 return long_neg(v);
3816 else
3817 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003818}
3819
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003820static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003821long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003824}
3825
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003826static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003827long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 PyLongObject *z = NULL;
3830 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3831 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003835 if (Py_SIZE(a) < 0) {
3836 /* Right shifting negative numbers is harder */
3837 PyLongObject *a1, *a2;
3838 a1 = (PyLongObject *) long_invert(a);
3839 if (a1 == NULL)
3840 goto rshift_error;
3841 a2 = (PyLongObject *) long_rshift(a1, b);
3842 Py_DECREF(a1);
3843 if (a2 == NULL)
3844 goto rshift_error;
3845 z = (PyLongObject *) long_invert(a2);
3846 Py_DECREF(a2);
3847 }
3848 else {
3849 shiftby = PyLong_AsSsize_t((PyObject *)b);
3850 if (shiftby == -1L && PyErr_Occurred())
3851 goto rshift_error;
3852 if (shiftby < 0) {
3853 PyErr_SetString(PyExc_ValueError,
3854 "negative shift count");
3855 goto rshift_error;
3856 }
3857 wordshift = shiftby / PyLong_SHIFT;
3858 newsize = ABS(Py_SIZE(a)) - wordshift;
3859 if (newsize <= 0)
3860 return PyLong_FromLong(0);
3861 loshift = shiftby % PyLong_SHIFT;
3862 hishift = PyLong_SHIFT - loshift;
3863 lomask = ((digit)1 << hishift) - 1;
3864 himask = PyLong_MASK ^ lomask;
3865 z = _PyLong_New(newsize);
3866 if (z == NULL)
3867 goto rshift_error;
3868 if (Py_SIZE(a) < 0)
3869 Py_SIZE(z) = -(Py_SIZE(z));
3870 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3871 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3872 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003873 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 }
3875 z = long_normalize(z);
3876 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003877 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003878 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003879
Guido van Rossumc6913e71991-11-19 20:26:46 +00003880}
3881
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003882static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003883long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 /* This version due to Tim Peters */
3886 PyLongObject *a = (PyLongObject*)v;
3887 PyLongObject *b = (PyLongObject*)w;
3888 PyLongObject *z = NULL;
3889 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3890 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 shiftby = PyLong_AsSsize_t((PyObject *)b);
3895 if (shiftby == -1L && PyErr_Occurred())
3896 goto lshift_error;
3897 if (shiftby < 0) {
3898 PyErr_SetString(PyExc_ValueError, "negative shift count");
3899 goto lshift_error;
3900 }
3901 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3902 wordshift = shiftby / PyLong_SHIFT;
3903 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 oldsize = ABS(Py_SIZE(a));
3906 newsize = oldsize + wordshift;
3907 if (remshift)
3908 ++newsize;
3909 z = _PyLong_New(newsize);
3910 if (z == NULL)
3911 goto lshift_error;
3912 if (Py_SIZE(a) < 0)
3913 NEGATE(z);
3914 for (i = 0; i < wordshift; i++)
3915 z->ob_digit[i] = 0;
3916 accum = 0;
3917 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3918 accum |= (twodigits)a->ob_digit[j] << remshift;
3919 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3920 accum >>= PyLong_SHIFT;
3921 }
3922 if (remshift)
3923 z->ob_digit[newsize-1] = (digit)accum;
3924 else
3925 assert(!accum);
3926 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003927 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003929}
3930
Mark Dickinson27a87a22009-10-25 20:43:34 +00003931/* Compute two's complement of digit vector a[0:m], writing result to
3932 z[0:m]. The digit vector a need not be normalized, but should not
3933 be entirely zero. a and z may point to the same digit vector. */
3934
3935static void
3936v_complement(digit *z, digit *a, Py_ssize_t m)
3937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 Py_ssize_t i;
3939 digit carry = 1;
3940 for (i = 0; i < m; ++i) {
3941 carry += a[i] ^ PyLong_MASK;
3942 z[i] = carry & PyLong_MASK;
3943 carry >>= PyLong_SHIFT;
3944 }
3945 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003946}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003947
3948/* Bitwise and/xor/or operations */
3949
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003950static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003951long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003953 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 int nega, negb, negz;
3956 Py_ssize_t size_a, size_b, size_z, i;
3957 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 /* Bitwise operations for negative numbers operate as though
3960 on a two's complement representation. So convert arguments
3961 from sign-magnitude to two's complement, and convert the
3962 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 /* If a is negative, replace it by its two's complement. */
3965 size_a = ABS(Py_SIZE(a));
3966 nega = Py_SIZE(a) < 0;
3967 if (nega) {
3968 z = _PyLong_New(size_a);
3969 if (z == NULL)
3970 return NULL;
3971 v_complement(z->ob_digit, a->ob_digit, size_a);
3972 a = z;
3973 }
3974 else
3975 /* Keep reference count consistent. */
3976 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 /* Same for b. */
3979 size_b = ABS(Py_SIZE(b));
3980 negb = Py_SIZE(b) < 0;
3981 if (negb) {
3982 z = _PyLong_New(size_b);
3983 if (z == NULL) {
3984 Py_DECREF(a);
3985 return NULL;
3986 }
3987 v_complement(z->ob_digit, b->ob_digit, size_b);
3988 b = z;
3989 }
3990 else
3991 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 /* Swap a and b if necessary to ensure size_a >= size_b. */
3994 if (size_a < size_b) {
3995 z = a; a = b; b = z;
3996 size_z = size_a; size_a = size_b; size_b = size_z;
3997 negz = nega; nega = negb; negb = negz;
3998 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 /* JRH: The original logic here was to allocate the result value (z)
4001 as the longer of the two operands. However, there are some cases
4002 where the result is guaranteed to be shorter than that: AND of two
4003 positives, OR of two negatives: use the shorter number. AND with
4004 mixed signs: use the positive number. OR with mixed signs: use the
4005 negative number.
4006 */
4007 switch (op) {
4008 case '^':
4009 negz = nega ^ negb;
4010 size_z = size_a;
4011 break;
4012 case '&':
4013 negz = nega & negb;
4014 size_z = negb ? size_a : size_b;
4015 break;
4016 case '|':
4017 negz = nega | negb;
4018 size_z = negb ? size_b : size_a;
4019 break;
4020 default:
4021 PyErr_BadArgument();
4022 return NULL;
4023 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 /* We allow an extra digit if z is negative, to make sure that
4026 the final two's complement of z doesn't overflow. */
4027 z = _PyLong_New(size_z + negz);
4028 if (z == NULL) {
4029 Py_DECREF(a);
4030 Py_DECREF(b);
4031 return NULL;
4032 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 /* Compute digits for overlap of a and b. */
4035 switch(op) {
4036 case '&':
4037 for (i = 0; i < size_b; ++i)
4038 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4039 break;
4040 case '|':
4041 for (i = 0; i < size_b; ++i)
4042 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4043 break;
4044 case '^':
4045 for (i = 0; i < size_b; ++i)
4046 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4047 break;
4048 default:
4049 PyErr_BadArgument();
4050 return NULL;
4051 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 /* Copy any remaining digits of a, inverting if necessary. */
4054 if (op == '^' && negb)
4055 for (; i < size_z; ++i)
4056 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4057 else if (i < size_z)
4058 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4059 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004061 /* Complement result if negative. */
4062 if (negz) {
4063 Py_SIZE(z) = -(Py_SIZE(z));
4064 z->ob_digit[size_z] = PyLong_MASK;
4065 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4066 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 Py_DECREF(a);
4069 Py_DECREF(b);
4070 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004071}
4072
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004073static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004074long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 PyObject *c;
4077 CHECK_BINOP(a, b);
4078 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4079 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004080}
4081
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004082static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004083long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 PyObject *c;
4086 CHECK_BINOP(a, b);
4087 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4088 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004089}
4090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004091static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004092long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 PyObject *c;
4095 CHECK_BINOP(a, b);
4096 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4097 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004098}
4099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004100static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004101long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 if (PyLong_CheckExact(v))
4104 Py_INCREF(v);
4105 else
4106 v = _PyLong_Copy((PyLongObject *)v);
4107 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004108}
4109
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004110static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004111long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 double result;
4114 result = PyLong_AsDouble(v);
4115 if (result == -1.0 && PyErr_Occurred())
4116 return NULL;
4117 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004118}
4119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004120static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004121long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004122
Tim Peters6d6c1a32001-08-02 04:15:00 +00004123static PyObject *
4124long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4125{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004126 PyObject *obase = NULL, *x = NULL;
4127 long base;
4128 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004129 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 if (type != &PyLong_Type)
4132 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004133 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4134 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 return NULL;
4136 if (x == NULL)
4137 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004138 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004140
4141 base = PyLong_AsLongAndOverflow(obase, &overflow);
4142 if (base == -1 && PyErr_Occurred())
4143 return NULL;
4144 if (overflow || (base != 0 && base < 2) || base > 36) {
4145 PyErr_SetString(PyExc_ValueError,
4146 "int() arg 2 must be >= 2 and <= 36");
4147 return NULL;
4148 }
4149
4150 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004151 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4153 /* Since PyLong_FromString doesn't have a length parameter,
4154 * check here for possible NULs in the string. */
4155 char *string;
4156 Py_ssize_t size = Py_SIZE(x);
4157 if (PyByteArray_Check(x))
4158 string = PyByteArray_AS_STRING(x);
4159 else
4160 string = PyBytes_AS_STRING(x);
4161 if (strlen(string) != (size_t)size) {
4162 /* We only see this if there's a null byte in x,
4163 x is a bytes or buffer, *and* a base is given. */
4164 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004165 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004166 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004167 return NULL;
4168 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004169 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 }
4171 else {
4172 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004173 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 return NULL;
4175 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004176}
4177
Guido van Rossumbef14172001-08-29 15:47:46 +00004178/* Wimpy, slow approach to tp_new calls for subtypes of long:
4179 first create a regular long from whatever arguments we got,
4180 then allocate a subtype instance and initialize it from
4181 the regular long. The regular long is then thrown away.
4182*/
4183static PyObject *
4184long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 PyLongObject *tmp, *newobj;
4187 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 assert(PyType_IsSubtype(type, &PyLong_Type));
4190 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4191 if (tmp == NULL)
4192 return NULL;
4193 assert(PyLong_CheckExact(tmp));
4194 n = Py_SIZE(tmp);
4195 if (n < 0)
4196 n = -n;
4197 newobj = (PyLongObject *)type->tp_alloc(type, n);
4198 if (newobj == NULL) {
4199 Py_DECREF(tmp);
4200 return NULL;
4201 }
4202 assert(PyLong_Check(newobj));
4203 Py_SIZE(newobj) = Py_SIZE(tmp);
4204 for (i = 0; i < n; i++)
4205 newobj->ob_digit[i] = tmp->ob_digit[i];
4206 Py_DECREF(tmp);
4207 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004208}
4209
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004210static PyObject *
4211long_getnewargs(PyLongObject *v)
4212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004214}
4215
Guido van Rossumb43daf72007-08-01 18:08:08 +00004216static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004217long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004219}
4220
4221static PyObject *
4222long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004224}
4225
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004226static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004227long__format__(PyObject *self, PyObject *args)
4228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004231 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4232 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004233 return _PyLong_FormatAdvanced(self, format_spec, 0,
4234 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004235}
4236
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004237/* Return a pair (q, r) such that a = b * q + r, and
4238 abs(r) <= abs(b)/2, with equality possible only if q is even.
4239 In other words, q == a / b, rounded to the nearest integer using
4240 round-half-to-even. */
4241
4242PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004243_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004244{
4245 PyLongObject *quo = NULL, *rem = NULL;
4246 PyObject *one = NULL, *twice_rem, *result, *temp;
4247 int cmp, quo_is_odd, quo_is_neg;
4248
4249 /* Equivalent Python code:
4250
4251 def divmod_near(a, b):
4252 q, r = divmod(a, b)
4253 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4254 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4255 # positive, 2 * r < b if b negative.
4256 greater_than_half = 2*r > b if b > 0 else 2*r < b
4257 exactly_half = 2*r == b
4258 if greater_than_half or exactly_half and q % 2 == 1:
4259 q += 1
4260 r -= b
4261 return q, r
4262
4263 */
4264 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4265 PyErr_SetString(PyExc_TypeError,
4266 "non-integer arguments in division");
4267 return NULL;
4268 }
4269
4270 /* Do a and b have different signs? If so, quotient is negative. */
4271 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4272
4273 one = PyLong_FromLong(1L);
4274 if (one == NULL)
4275 return NULL;
4276
4277 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4278 goto error;
4279
4280 /* compare twice the remainder with the divisor, to see
4281 if we need to adjust the quotient and remainder */
4282 twice_rem = long_lshift((PyObject *)rem, one);
4283 if (twice_rem == NULL)
4284 goto error;
4285 if (quo_is_neg) {
4286 temp = long_neg((PyLongObject*)twice_rem);
4287 Py_DECREF(twice_rem);
4288 twice_rem = temp;
4289 if (twice_rem == NULL)
4290 goto error;
4291 }
4292 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4293 Py_DECREF(twice_rem);
4294
4295 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4296 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4297 /* fix up quotient */
4298 if (quo_is_neg)
4299 temp = long_sub(quo, (PyLongObject *)one);
4300 else
4301 temp = long_add(quo, (PyLongObject *)one);
4302 Py_DECREF(quo);
4303 quo = (PyLongObject *)temp;
4304 if (quo == NULL)
4305 goto error;
4306 /* and remainder */
4307 if (quo_is_neg)
4308 temp = long_add(rem, (PyLongObject *)b);
4309 else
4310 temp = long_sub(rem, (PyLongObject *)b);
4311 Py_DECREF(rem);
4312 rem = (PyLongObject *)temp;
4313 if (rem == NULL)
4314 goto error;
4315 }
4316
4317 result = PyTuple_New(2);
4318 if (result == NULL)
4319 goto error;
4320
4321 /* PyTuple_SET_ITEM steals references */
4322 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4323 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4324 Py_DECREF(one);
4325 return result;
4326
4327 error:
4328 Py_XDECREF(quo);
4329 Py_XDECREF(rem);
4330 Py_XDECREF(one);
4331 return NULL;
4332}
4333
Eric Smith8c663262007-08-25 02:26:07 +00004334static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004335long_round(PyObject *self, PyObject *args)
4336{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004337 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004338
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004339 /* To round an integer m to the nearest 10**n (n positive), we make use of
4340 * the divmod_near operation, defined by:
4341 *
4342 * divmod_near(a, b) = (q, r)
4343 *
4344 * where q is the nearest integer to the quotient a / b (the
4345 * nearest even integer in the case of a tie) and r == a - q * b.
4346 * Hence q * b = a - r is the nearest multiple of b to a,
4347 * preferring even multiples in the case of a tie.
4348 *
4349 * So the nearest multiple of 10**n to m is:
4350 *
4351 * m - divmod_near(m, 10**n)[1].
4352 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4354 return NULL;
4355 if (o_ndigits == NULL)
4356 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004357
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004358 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 if (ndigits == NULL)
4360 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004361
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004362 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 if (Py_SIZE(ndigits) >= 0) {
4364 Py_DECREF(ndigits);
4365 return long_long(self);
4366 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004367
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004368 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4369 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004371 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004372 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004373 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004374
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004375 result = PyLong_FromLong(10L);
4376 if (result == NULL) {
4377 Py_DECREF(ndigits);
4378 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004380
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004381 temp = long_pow(result, ndigits, Py_None);
4382 Py_DECREF(ndigits);
4383 Py_DECREF(result);
4384 result = temp;
4385 if (result == NULL)
4386 return NULL;
4387
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004388 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004389 Py_DECREF(result);
4390 result = temp;
4391 if (result == NULL)
4392 return NULL;
4393
4394 temp = long_sub((PyLongObject *)self,
4395 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4396 Py_DECREF(result);
4397 result = temp;
4398
4399 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004400}
4401
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004402static PyObject *
4403long_sizeof(PyLongObject *v)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4408 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004409}
4410
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004411static PyObject *
4412long_bit_length(PyLongObject *v)
4413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 PyLongObject *result, *x, *y;
4415 Py_ssize_t ndigits, msd_bits = 0;
4416 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004418 assert(v != NULL);
4419 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 ndigits = ABS(Py_SIZE(v));
4422 if (ndigits == 0)
4423 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 msd = v->ob_digit[ndigits-1];
4426 while (msd >= 32) {
4427 msd_bits += 6;
4428 msd >>= 6;
4429 }
4430 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4433 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 /* expression above may overflow; use Python integers instead */
4436 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4437 if (result == NULL)
4438 return NULL;
4439 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4440 if (x == NULL)
4441 goto error;
4442 y = (PyLongObject *)long_mul(result, x);
4443 Py_DECREF(x);
4444 if (y == NULL)
4445 goto error;
4446 Py_DECREF(result);
4447 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4450 if (x == NULL)
4451 goto error;
4452 y = (PyLongObject *)long_add(result, x);
4453 Py_DECREF(x);
4454 if (y == NULL)
4455 goto error;
4456 Py_DECREF(result);
4457 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004460
Mark Dickinson22b20182010-05-10 21:27:53 +00004461 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 Py_DECREF(result);
4463 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004464}
4465
4466PyDoc_STRVAR(long_bit_length_doc,
4467"int.bit_length() -> int\n\
4468\n\
4469Number of bits necessary to represent self in binary.\n\
4470>>> bin(37)\n\
4471'0b100101'\n\
4472>>> (37).bit_length()\n\
44736");
4474
Christian Heimes53876d92008-04-19 00:31:39 +00004475#if 0
4476static PyObject *
4477long_is_finite(PyObject *v)
4478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004480}
4481#endif
4482
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004483
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004484static PyObject *
4485long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 PyObject *byteorder_str;
4488 PyObject *is_signed_obj = NULL;
4489 Py_ssize_t length;
4490 int little_endian;
4491 int is_signed;
4492 PyObject *bytes;
4493 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4496 &length, &byteorder_str,
4497 &is_signed_obj))
4498 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (args != NULL && Py_SIZE(args) > 2) {
4501 PyErr_SetString(PyExc_TypeError,
4502 "'signed' is a keyword-only argument");
4503 return NULL;
4504 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4507 little_endian = 1;
4508 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4509 little_endian = 0;
4510 else {
4511 PyErr_SetString(PyExc_ValueError,
4512 "byteorder must be either 'little' or 'big'");
4513 return NULL;
4514 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 if (is_signed_obj != NULL) {
4517 int cmp = PyObject_IsTrue(is_signed_obj);
4518 if (cmp < 0)
4519 return NULL;
4520 is_signed = cmp ? 1 : 0;
4521 }
4522 else {
4523 /* If the signed argument was omitted, use False as the
4524 default. */
4525 is_signed = 0;
4526 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (length < 0) {
4529 PyErr_SetString(PyExc_ValueError,
4530 "length argument must be non-negative");
4531 return NULL;
4532 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 bytes = PyBytes_FromStringAndSize(NULL, length);
4535 if (bytes == NULL)
4536 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004538 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4539 length, little_endian, is_signed) < 0) {
4540 Py_DECREF(bytes);
4541 return NULL;
4542 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004545}
4546
Mark Dickinson078c2532010-01-30 18:06:17 +00004547PyDoc_STRVAR(long_to_bytes_doc,
4548"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004549\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004550Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004551\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004553raised if the integer is not representable with the given number of\n\
4554bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004555\n\
4556The byteorder argument determines the byte order used to represent the\n\
4557integer. If byteorder is 'big', the most significant byte is at the\n\
4558beginning of the byte array. If byteorder is 'little', the most\n\
4559significant byte is at the end of the byte array. To request the native\n\
4560byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4561\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004562The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004564is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004565
4566static PyObject *
4567long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 PyObject *byteorder_str;
4570 PyObject *is_signed_obj = NULL;
4571 int little_endian;
4572 int is_signed;
4573 PyObject *obj;
4574 PyObject *bytes;
4575 PyObject *long_obj;
4576 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4579 &obj, &byteorder_str,
4580 &is_signed_obj))
4581 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (args != NULL && Py_SIZE(args) > 2) {
4584 PyErr_SetString(PyExc_TypeError,
4585 "'signed' is a keyword-only argument");
4586 return NULL;
4587 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4590 little_endian = 1;
4591 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4592 little_endian = 0;
4593 else {
4594 PyErr_SetString(PyExc_ValueError,
4595 "byteorder must be either 'little' or 'big'");
4596 return NULL;
4597 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004599 if (is_signed_obj != NULL) {
4600 int cmp = PyObject_IsTrue(is_signed_obj);
4601 if (cmp < 0)
4602 return NULL;
4603 is_signed = cmp ? 1 : 0;
4604 }
4605 else {
4606 /* If the signed argument was omitted, use False as the
4607 default. */
4608 is_signed = 0;
4609 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 bytes = PyObject_Bytes(obj);
4612 if (bytes == NULL)
4613 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 long_obj = _PyLong_FromByteArray(
4616 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4617 little_endian, is_signed);
4618 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 /* If from_bytes() was used on subclass, allocate new subclass
4621 * instance, initialize it with decoded long value and return it.
4622 */
4623 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4624 PyLongObject *newobj;
4625 int i;
4626 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 newobj = (PyLongObject *)type->tp_alloc(type, n);
4629 if (newobj == NULL) {
4630 Py_DECREF(long_obj);
4631 return NULL;
4632 }
4633 assert(PyLong_Check(newobj));
4634 Py_SIZE(newobj) = Py_SIZE(long_obj);
4635 for (i = 0; i < n; i++) {
4636 newobj->ob_digit[i] =
4637 ((PyLongObject *)long_obj)->ob_digit[i];
4638 }
4639 Py_DECREF(long_obj);
4640 return (PyObject *)newobj;
4641 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004644}
4645
Mark Dickinson078c2532010-01-30 18:06:17 +00004646PyDoc_STRVAR(long_from_bytes_doc,
4647"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4648\n\
4649Return the integer represented by the given array of bytes.\n\
4650\n\
4651The bytes argument must either support the buffer protocol or be an\n\
4652iterable object producing bytes. Bytes and bytearray are examples of\n\
4653built-in objects that support the buffer protocol.\n\
4654\n\
4655The byteorder argument determines the byte order used to represent the\n\
4656integer. If byteorder is 'big', the most significant byte is at the\n\
4657beginning of the byte array. If byteorder is 'little', the most\n\
4658significant byte is at the end of the byte array. To request the native\n\
4659byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4660\n\
4661The signed keyword-only argument indicates whether two's complement is\n\
4662used to represent the integer.");
4663
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004664static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4666 "Returns self, the complex conjugate of any int."},
4667 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4668 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004669#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4671 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004672#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 {"to_bytes", (PyCFunction)long_to_bytes,
4674 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4675 {"from_bytes", (PyCFunction)long_from_bytes,
4676 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4677 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4678 "Truncating an Integral returns itself."},
4679 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4680 "Flooring an Integral returns itself."},
4681 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4682 "Ceiling of an Integral returns itself."},
4683 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4684 "Rounding an Integral returns itself.\n"
4685 "Rounding with an ndigits argument also returns an integer."},
4686 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4687 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4688 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4689 "Returns size in memory, in bytes"},
4690 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004691};
4692
Guido van Rossumb43daf72007-08-01 18:08:08 +00004693static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004694 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004695 (getter)long_long, (setter)NULL,
4696 "the real part of a complex number",
4697 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004698 {"imag",
4699 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004700 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004701 NULL},
4702 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004703 (getter)long_long, (setter)NULL,
4704 "the numerator of a rational number in lowest terms",
4705 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004706 {"denominator",
4707 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004708 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004709 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004710 {NULL} /* Sentinel */
4711};
4712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004713PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004714"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004715\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004716Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004717point argument will be truncated towards zero (this does not include a\n\
4718string representation of a floating point number!) When converting a\n\
4719string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004720converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004721
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004722static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004723 (binaryfunc)long_add, /*nb_add*/
4724 (binaryfunc)long_sub, /*nb_subtract*/
4725 (binaryfunc)long_mul, /*nb_multiply*/
4726 long_mod, /*nb_remainder*/
4727 long_divmod, /*nb_divmod*/
4728 long_pow, /*nb_power*/
4729 (unaryfunc)long_neg, /*nb_negative*/
4730 (unaryfunc)long_long, /*tp_positive*/
4731 (unaryfunc)long_abs, /*tp_absolute*/
4732 (inquiry)long_bool, /*tp_bool*/
4733 (unaryfunc)long_invert, /*nb_invert*/
4734 long_lshift, /*nb_lshift*/
4735 (binaryfunc)long_rshift, /*nb_rshift*/
4736 long_and, /*nb_and*/
4737 long_xor, /*nb_xor*/
4738 long_or, /*nb_or*/
4739 long_long, /*nb_int*/
4740 0, /*nb_reserved*/
4741 long_float, /*nb_float*/
4742 0, /* nb_inplace_add */
4743 0, /* nb_inplace_subtract */
4744 0, /* nb_inplace_multiply */
4745 0, /* nb_inplace_remainder */
4746 0, /* nb_inplace_power */
4747 0, /* nb_inplace_lshift */
4748 0, /* nb_inplace_rshift */
4749 0, /* nb_inplace_and */
4750 0, /* nb_inplace_xor */
4751 0, /* nb_inplace_or */
4752 long_div, /* nb_floor_divide */
4753 long_true_divide, /* nb_true_divide */
4754 0, /* nb_inplace_floor_divide */
4755 0, /* nb_inplace_true_divide */
4756 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004757};
4758
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004759PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4761 "int", /* tp_name */
4762 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4763 sizeof(digit), /* tp_itemsize */
4764 long_dealloc, /* tp_dealloc */
4765 0, /* tp_print */
4766 0, /* tp_getattr */
4767 0, /* tp_setattr */
4768 0, /* tp_reserved */
4769 long_to_decimal_string, /* tp_repr */
4770 &long_as_number, /* tp_as_number */
4771 0, /* tp_as_sequence */
4772 0, /* tp_as_mapping */
4773 (hashfunc)long_hash, /* tp_hash */
4774 0, /* tp_call */
4775 long_to_decimal_string, /* tp_str */
4776 PyObject_GenericGetAttr, /* tp_getattro */
4777 0, /* tp_setattro */
4778 0, /* tp_as_buffer */
4779 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4780 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4781 long_doc, /* tp_doc */
4782 0, /* tp_traverse */
4783 0, /* tp_clear */
4784 long_richcompare, /* tp_richcompare */
4785 0, /* tp_weaklistoffset */
4786 0, /* tp_iter */
4787 0, /* tp_iternext */
4788 long_methods, /* tp_methods */
4789 0, /* tp_members */
4790 long_getset, /* tp_getset */
4791 0, /* tp_base */
4792 0, /* tp_dict */
4793 0, /* tp_descr_get */
4794 0, /* tp_descr_set */
4795 0, /* tp_dictoffset */
4796 0, /* tp_init */
4797 0, /* tp_alloc */
4798 long_new, /* tp_new */
4799 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004800};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004801
Mark Dickinsonbd792642009-03-18 20:06:12 +00004802static PyTypeObject Int_InfoType;
4803
4804PyDoc_STRVAR(int_info__doc__,
4805"sys.int_info\n\
4806\n\
4807A struct sequence that holds information about Python's\n\
4808internal representation of integers. The attributes are read only.");
4809
4810static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004812 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004814};
4815
4816static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004817 "sys.int_info", /* name */
4818 int_info__doc__, /* doc */
4819 int_info_fields, /* fields */
4820 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004821};
4822
4823PyObject *
4824PyLong_GetInfo(void)
4825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 PyObject* int_info;
4827 int field = 0;
4828 int_info = PyStructSequence_New(&Int_InfoType);
4829 if (int_info == NULL)
4830 return NULL;
4831 PyStructSequence_SET_ITEM(int_info, field++,
4832 PyLong_FromLong(PyLong_SHIFT));
4833 PyStructSequence_SET_ITEM(int_info, field++,
4834 PyLong_FromLong(sizeof(digit)));
4835 if (PyErr_Occurred()) {
4836 Py_CLEAR(int_info);
4837 return NULL;
4838 }
4839 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004840}
4841
Guido van Rossumddefaf32007-01-14 03:31:43 +00004842int
4843_PyLong_Init(void)
4844{
4845#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 int ival, size;
4847 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4850 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4851 if (Py_TYPE(v) == &PyLong_Type) {
4852 /* The element is already initialized, most likely
4853 * the Python interpreter was initialized before.
4854 */
4855 Py_ssize_t refcnt;
4856 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004858 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4859 _Py_NewReference(op);
4860 /* _Py_NewReference sets the ref count to 1 but
4861 * the ref count might be larger. Set the refcnt
4862 * to the original refcnt + 1 */
4863 Py_REFCNT(op) = refcnt + 1;
4864 assert(Py_SIZE(op) == size);
4865 assert(v->ob_digit[0] == abs(ival));
4866 }
4867 else {
4868 PyObject_INIT(v, &PyLong_Type);
4869 }
4870 Py_SIZE(v) = size;
4871 v->ob_digit[0] = abs(ival);
4872 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004873#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004874 /* initialize int_info */
4875 if (Int_InfoType.tp_name == 0)
4876 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004879}
4880
4881void
4882PyLong_Fini(void)
4883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004884 /* Integers are currently statically allocated. Py_DECREF is not
4885 needed, but Python must forget about the reference or multiple
4886 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004887#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 int i;
4889 PyLongObject *v = small_ints;
4890 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4891 _Py_DEC_REFTOTAL;
4892 _Py_ForgetReference((PyObject*)v);
4893 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004894#endif
4895}