blob: b47be40627221f5a6c6da35c2bf98666fc100276 [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 */
Victor Stinner08a80b12013-07-17 22:33:42 +020020#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
21 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010034Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000035#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000042#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
50#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
52 return get_small_int((sdigit)ival); \
53 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000056maybe_small_long(PyLongObject *v)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (v && ABS(Py_SIZE(v)) <= 1) {
59 sdigit ival = MEDIUM_VALUE(v);
60 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Guido van Rossumddefaf32007-01-14 03:31:43 +000072/* If a freshly-allocated long is already shared, it must
73 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020074Py_LOCAL_INLINE(void)
75_PyLong_Negate(PyLongObject **x_p)
76{
77 PyLongObject *x;
78
79 x = (PyLongObject *)*x_p;
80 if (Py_REFCNT(x) == 1) {
81 Py_SIZE(x) = -Py_SIZE(x);
82 return;
83 }
84
85 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
86 Py_DECREF(x);
87}
88
Tim Peters5af4e6c2002-08-12 02:31:19 +000089/* For long multiplication, use the O(N**2) school algorithm unless
90 * both operands contain more than KARATSUBA_CUTOFF digits (this
91 * being an internal Python long digit, in base BASE).
92 */
Tim Peters0973b992004-08-29 22:16:50 +000093#define KARATSUBA_CUTOFF 70
94#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000095
Tim Peters47e52ee2004-08-30 02:44:38 +000096/* For exponentiation, use the binary left-to-right algorithm
97 * unless the exponent contains more than FIVEARY_CUTOFF digits.
98 * In that case, do 5 bits at a time. The potential drawback is that
99 * a table of 2**5 intermediate results is computed.
100 */
101#define FIVEARY_CUTOFF 8
102
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000103#define SIGCHECK(PyTryBlock) \
104 do { \
105 if (PyErr_CheckSignals()) PyTryBlock \
106 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000107
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108/* Normalize (remove leading zeros from) a long int object.
109 Doesn't attempt to free the storage--in most cases, due to the nature
110 of the algorithms used, this could save at most be one word anyway. */
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000113long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_ssize_t j = ABS(Py_SIZE(v));
116 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 while (i > 0 && v->ob_digit[i-1] == 0)
119 --i;
120 if (i != j)
121 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
122 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000123}
124
125/* Allocate a new long int object with size digits.
126 Return NULL and set exception if we run out of memory. */
127
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000128#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000130
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000131PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000132_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 PyLongObject *result;
135 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
136 sizeof(digit)*size. Previous incarnations of this code used
137 sizeof(PyVarObject) instead of the offsetof, but this risks being
138 incorrect in the presence of padding between the PyVarObject header
139 and the digits. */
140 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
141 PyErr_SetString(PyExc_OverflowError,
142 "too many digits in integer");
143 return NULL;
144 }
145 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
146 size*sizeof(digit));
147 if (!result) {
148 PyErr_NoMemory();
149 return NULL;
150 }
151 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000152}
153
Tim Peters64b5ce32001-09-10 20:52:51 +0000154PyObject *
155_PyLong_Copy(PyLongObject *src)
156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyLongObject *result;
158 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 assert(src != NULL);
161 i = Py_SIZE(src);
162 if (i < 0)
163 i = -(i);
164 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100165 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 CHECK_SMALL_INT(ival);
167 }
168 result = _PyLong_New(i);
169 if (result != NULL) {
170 Py_SIZE(result) = Py_SIZE(src);
171 while (--i >= 0)
172 result->ob_digit[i] = src->ob_digit[i];
173 }
174 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000175}
176
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177/* Create a new long int object from a C long int */
178
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000180PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyLongObject *v;
183 unsigned long abs_ival;
184 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
185 int ndigits = 0;
186 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (ival < 0) {
191 /* negate: can't write this as abs_ival = -ival since that
192 invokes undefined behaviour when ival is LONG_MIN */
193 abs_ival = 0U-(unsigned long)ival;
194 sign = -1;
195 }
196 else {
197 abs_ival = (unsigned long)ival;
198 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 /* Fast path for single-digit ints */
201 if (!(abs_ival >> PyLong_SHIFT)) {
202 v = _PyLong_New(1);
203 if (v) {
204 Py_SIZE(v) = sign;
205 v->ob_digit[0] = Py_SAFE_DOWNCAST(
206 abs_ival, unsigned long, digit);
207 }
208 return (PyObject*)v;
209 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000210
Mark Dickinson249b8982009-04-27 19:41:00 +0000211#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 /* 2 digits */
213 if (!(abs_ival >> 2*PyLong_SHIFT)) {
214 v = _PyLong_New(2);
215 if (v) {
216 Py_SIZE(v) = 2*sign;
217 v->ob_digit[0] = Py_SAFE_DOWNCAST(
218 abs_ival & PyLong_MASK, unsigned long, digit);
219 v->ob_digit[1] = Py_SAFE_DOWNCAST(
220 abs_ival >> PyLong_SHIFT, unsigned long, digit);
221 }
222 return (PyObject*)v;
223 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000224#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 /* Larger numbers: loop to determine number of digits */
227 t = abs_ival;
228 while (t) {
229 ++ndigits;
230 t >>= PyLong_SHIFT;
231 }
232 v = _PyLong_New(ndigits);
233 if (v != NULL) {
234 digit *p = v->ob_digit;
235 Py_SIZE(v) = ndigits*sign;
236 t = abs_ival;
237 while (t) {
238 *p++ = Py_SAFE_DOWNCAST(
239 t & PyLong_MASK, unsigned long, digit);
240 t >>= PyLong_SHIFT;
241 }
242 }
243 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000244}
245
Guido van Rossum53756b11997-01-03 17:14:46 +0000246/* Create a new long int object from a C unsigned long int */
247
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000249PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyLongObject *v;
252 unsigned long t;
253 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (ival < PyLong_BASE)
256 return PyLong_FromLong(ival);
257 /* Count the number of Python digits. */
258 t = (unsigned long)ival;
259 while (t) {
260 ++ndigits;
261 t >>= PyLong_SHIFT;
262 }
263 v = _PyLong_New(ndigits);
264 if (v != NULL) {
265 digit *p = v->ob_digit;
266 Py_SIZE(v) = ndigits;
267 while (ival) {
268 *p++ = (digit)(ival & PyLong_MASK);
269 ival >>= PyLong_SHIFT;
270 }
271 }
272 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000273}
274
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275/* Create a new long int object from a C double */
276
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000277PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000278PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyLongObject *v;
281 double frac;
282 int i, ndig, expo, neg;
283 neg = 0;
284 if (Py_IS_INFINITY(dval)) {
285 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000286 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return NULL;
288 }
289 if (Py_IS_NAN(dval)) {
290 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000291 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return NULL;
293 }
294 if (dval < 0.0) {
295 neg = 1;
296 dval = -dval;
297 }
298 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
299 if (expo <= 0)
300 return PyLong_FromLong(0L);
301 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
302 v = _PyLong_New(ndig);
303 if (v == NULL)
304 return NULL;
305 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
306 for (i = ndig; --i >= 0; ) {
307 digit bits = (digit)frac;
308 v->ob_digit[i] = bits;
309 frac = frac - (double)bits;
310 frac = ldexp(frac, PyLong_SHIFT);
311 }
312 if (neg)
313 Py_SIZE(v) = -(Py_SIZE(v));
314 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000315}
316
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
318 * anything about what happens when a signed integer operation overflows,
319 * and some compilers think they're doing you a favor by being "clever"
320 * then. The bit pattern for the largest postive signed long is
321 * (unsigned long)LONG_MAX, and for the smallest negative signed long
322 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
323 * However, some other compilers warn about applying unary minus to an
324 * unsigned operand. Hence the weird "0-".
325 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
327#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000328
Mark Dickinson8d48b432011-10-23 20:47:14 +0100329/* Get a C long int from a long int object or any object that has an __int__
330 method.
331
332 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
333 the result. Otherwise *overflow is 0.
334
335 For other errors (e.g., TypeError), return -1 and set an error condition.
336 In this case *overflow will be 0.
337*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000338
339long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000340PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 /* This version by Tim Peters */
343 register PyLongObject *v;
344 unsigned long x, prev;
345 long res;
346 Py_ssize_t i;
347 int sign;
348 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 *overflow = 0;
351 if (vv == NULL) {
352 PyErr_BadInternalCall();
353 return -1;
354 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (!PyLong_Check(vv)) {
357 PyNumberMethods *nb;
358 nb = vv->ob_type->tp_as_number;
359 if (nb == NULL || nb->nb_int == NULL) {
360 PyErr_SetString(PyExc_TypeError,
361 "an integer is required");
362 return -1;
363 }
364 vv = (*nb->nb_int) (vv);
365 if (vv == NULL)
366 return -1;
367 do_decref = 1;
368 if (!PyLong_Check(vv)) {
369 Py_DECREF(vv);
370 PyErr_SetString(PyExc_TypeError,
371 "nb_int should return int object");
372 return -1;
373 }
374 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 res = -1;
377 v = (PyLongObject *)vv;
378 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 switch (i) {
381 case -1:
382 res = -(sdigit)v->ob_digit[0];
383 break;
384 case 0:
385 res = 0;
386 break;
387 case 1:
388 res = v->ob_digit[0];
389 break;
390 default:
391 sign = 1;
392 x = 0;
393 if (i < 0) {
394 sign = -1;
395 i = -(i);
396 }
397 while (--i >= 0) {
398 prev = x;
399 x = (x << PyLong_SHIFT) | v->ob_digit[i];
400 if ((x >> PyLong_SHIFT) != prev) {
401 *overflow = sign;
402 goto exit;
403 }
404 }
405 /* Haven't lost any bits, but casting to long requires extra
406 * care (see comment above).
407 */
408 if (x <= (unsigned long)LONG_MAX) {
409 res = (long)x * sign;
410 }
411 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
412 res = LONG_MIN;
413 }
414 else {
415 *overflow = sign;
416 /* res is already set to -1 */
417 }
418 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000419 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (do_decref) {
421 Py_DECREF(vv);
422 }
423 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000424}
425
Mark Dickinson8d48b432011-10-23 20:47:14 +0100426/* Get a C long int from a long int object or any object that has an __int__
427 method. Return -1 and set an error if overflow occurs. */
428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000430PyLong_AsLong(PyObject *obj)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 int overflow;
433 long result = PyLong_AsLongAndOverflow(obj, &overflow);
434 if (overflow) {
435 /* XXX: could be cute and give a different
436 message for overflow == -1 */
437 PyErr_SetString(PyExc_OverflowError,
438 "Python int too large to convert to C long");
439 }
440 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000441}
442
Serhiy Storchaka78980432013-01-15 01:12:17 +0200443/* Get a C int from a long int object or any object that has an __int__
444 method. Return -1 and set an error if overflow occurs. */
445
446int
447_PyLong_AsInt(PyObject *obj)
448{
449 int overflow;
450 long result = PyLong_AsLongAndOverflow(obj, &overflow);
451 if (overflow || result > INT_MAX || result < INT_MIN) {
452 /* XXX: could be cute and give a different
453 message for overflow == -1 */
454 PyErr_SetString(PyExc_OverflowError,
455 "Python int too large to convert to C int");
456 return -1;
457 }
458 return (int)result;
459}
460
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000461/* Get a Py_ssize_t from a long int object.
462 Returns -1 and sets an error condition if overflow occurs. */
463
464Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000465PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 register PyLongObject *v;
467 size_t x, prev;
468 Py_ssize_t i;
469 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (vv == NULL) {
472 PyErr_BadInternalCall();
473 return -1;
474 }
475 if (!PyLong_Check(vv)) {
476 PyErr_SetString(PyExc_TypeError, "an integer is required");
477 return -1;
478 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 v = (PyLongObject *)vv;
481 i = Py_SIZE(v);
482 switch (i) {
483 case -1: return -(sdigit)v->ob_digit[0];
484 case 0: return 0;
485 case 1: return v->ob_digit[0];
486 }
487 sign = 1;
488 x = 0;
489 if (i < 0) {
490 sign = -1;
491 i = -(i);
492 }
493 while (--i >= 0) {
494 prev = x;
495 x = (x << PyLong_SHIFT) | v->ob_digit[i];
496 if ((x >> PyLong_SHIFT) != prev)
497 goto overflow;
498 }
499 /* Haven't lost any bits, but casting to a signed type requires
500 * extra care (see comment above).
501 */
502 if (x <= (size_t)PY_SSIZE_T_MAX) {
503 return (Py_ssize_t)x * sign;
504 }
505 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
506 return PY_SSIZE_T_MIN;
507 }
508 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000509
Mark Dickinson22b20182010-05-10 21:27:53 +0000510 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 PyErr_SetString(PyExc_OverflowError,
512 "Python int too large to convert to C ssize_t");
513 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000514}
515
Guido van Rossumd8c80482002-08-13 00:24:58 +0000516/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000517 Returns -1 and sets an error condition if overflow occurs. */
518
519unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000520PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 register PyLongObject *v;
523 unsigned long x, prev;
524 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (vv == NULL) {
527 PyErr_BadInternalCall();
528 return (unsigned long)-1;
529 }
530 if (!PyLong_Check(vv)) {
531 PyErr_SetString(PyExc_TypeError, "an integer is required");
532 return (unsigned long)-1;
533 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 v = (PyLongObject *)vv;
536 i = Py_SIZE(v);
537 x = 0;
538 if (i < 0) {
539 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000540 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return (unsigned long) -1;
542 }
543 switch (i) {
544 case 0: return 0;
545 case 1: return v->ob_digit[0];
546 }
547 while (--i >= 0) {
548 prev = x;
549 x = (x << PyLong_SHIFT) | v->ob_digit[i];
550 if ((x >> PyLong_SHIFT) != prev) {
551 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100552 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000553 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return (unsigned long) -1;
555 }
556 }
557 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000558}
559
Stefan Krahb77c6c62011-09-12 16:22:47 +0200560/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
561 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000562
563size_t
564PyLong_AsSize_t(PyObject *vv)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 register PyLongObject *v;
567 size_t x, prev;
568 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (vv == NULL) {
571 PyErr_BadInternalCall();
572 return (size_t) -1;
573 }
574 if (!PyLong_Check(vv)) {
575 PyErr_SetString(PyExc_TypeError, "an integer is required");
576 return (size_t)-1;
577 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 v = (PyLongObject *)vv;
580 i = Py_SIZE(v);
581 x = 0;
582 if (i < 0) {
583 PyErr_SetString(PyExc_OverflowError,
584 "can't convert negative value to size_t");
585 return (size_t) -1;
586 }
587 switch (i) {
588 case 0: return 0;
589 case 1: return v->ob_digit[0];
590 }
591 while (--i >= 0) {
592 prev = x;
593 x = (x << PyLong_SHIFT) | v->ob_digit[i];
594 if ((x >> PyLong_SHIFT) != prev) {
595 PyErr_SetString(PyExc_OverflowError,
596 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200597 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 }
599 }
600 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000601}
602
Thomas Hellera4ea6032003-04-17 18:55:45 +0000603/* Get a C unsigned long int from a long int object, ignoring the high bits.
604 Returns -1 and sets an error condition if an error occurs. */
605
Guido van Rossumddefaf32007-01-14 03:31:43 +0000606static unsigned long
607_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 register PyLongObject *v;
610 unsigned long x;
611 Py_ssize_t i;
612 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (vv == NULL || !PyLong_Check(vv)) {
615 PyErr_BadInternalCall();
616 return (unsigned long) -1;
617 }
618 v = (PyLongObject *)vv;
619 i = Py_SIZE(v);
620 switch (i) {
621 case 0: return 0;
622 case 1: return v->ob_digit[0];
623 }
624 sign = 1;
625 x = 0;
626 if (i < 0) {
627 sign = -1;
628 i = -i;
629 }
630 while (--i >= 0) {
631 x = (x << PyLong_SHIFT) | v->ob_digit[i];
632 }
633 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000634}
635
Guido van Rossumddefaf32007-01-14 03:31:43 +0000636unsigned long
637PyLong_AsUnsignedLongMask(register PyObject *op)
638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyNumberMethods *nb;
640 PyLongObject *lo;
641 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (op && PyLong_Check(op))
644 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
647 nb->nb_int == NULL) {
648 PyErr_SetString(PyExc_TypeError, "an integer is required");
649 return (unsigned long)-1;
650 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 lo = (PyLongObject*) (*nb->nb_int) (op);
653 if (lo == NULL)
654 return (unsigned long)-1;
655 if (PyLong_Check(lo)) {
656 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
657 Py_DECREF(lo);
658 if (PyErr_Occurred())
659 return (unsigned long)-1;
660 return val;
661 }
662 else
663 {
664 Py_DECREF(lo);
665 PyErr_SetString(PyExc_TypeError,
666 "nb_int should return int object");
667 return (unsigned long)-1;
668 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000669}
670
Tim Peters5b8132f2003-01-31 15:52:05 +0000671int
672_PyLong_Sign(PyObject *vv)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 assert(v != NULL);
677 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000680}
681
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682size_t
683_PyLong_NumBits(PyObject *vv)
684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyLongObject *v = (PyLongObject *)vv;
686 size_t result = 0;
687 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 assert(v != NULL);
690 assert(PyLong_Check(v));
691 ndigits = ABS(Py_SIZE(v));
692 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
693 if (ndigits > 0) {
694 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100695 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100697 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 do {
699 ++result;
700 if (result == 0)
701 goto Overflow;
702 msd >>= 1;
703 } while (msd);
704 }
705 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000706
Mark Dickinson22b20182010-05-10 21:27:53 +0000707 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
709 "to express in a platform size_t");
710 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000711}
712
Tim Peters2a9b3672001-06-11 21:23:58 +0000713PyObject *
714_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000716{
Mark Dickinson22b20182010-05-10 21:27:53 +0000717 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 int incr; /* direction to move pstartbyte */
719 const unsigned char* pendbyte; /* MSB of bytes */
720 size_t numsignificantbytes; /* number of bytes that matter */
721 Py_ssize_t ndigits; /* number of Python long digits */
722 PyLongObject* v; /* result */
723 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (n == 0)
726 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (little_endian) {
729 pstartbyte = bytes;
730 pendbyte = bytes + n - 1;
731 incr = 1;
732 }
733 else {
734 pstartbyte = bytes + n - 1;
735 pendbyte = bytes;
736 incr = -1;
737 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 if (is_signed)
740 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200743 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 is positive, and leading 0xff bytes if negative. */
745 {
746 size_t i;
747 const unsigned char* p = pendbyte;
748 const int pincr = -incr; /* search MSB to LSB */
749 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 for (i = 0; i < n; ++i, p += pincr) {
752 if (*p != insignficant)
753 break;
754 }
755 numsignificantbytes = n - i;
756 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
757 actually has 2 significant bytes. OTOH, 0xff0001 ==
758 -0x00ffff, so we wouldn't *need* to bump it there; but we
759 do for 0xffff = -0x0001. To be safe without bothering to
760 check every case, bump it regardless. */
761 if (is_signed && numsignificantbytes < n)
762 ++numsignificantbytes;
763 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 /* How many Python long digits do we need? We have
766 8*numsignificantbytes bits, and each Python long digit has
767 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
768 /* catch overflow before it happens */
769 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
770 PyErr_SetString(PyExc_OverflowError,
771 "byte array too long to convert to int");
772 return NULL;
773 }
774 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
775 v = _PyLong_New(ndigits);
776 if (v == NULL)
777 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 /* Copy the bits over. The tricky parts are computing 2's-comp on
780 the fly for signed numbers, and dealing with the mismatch between
781 8-bit bytes and (probably) 15-bit Python digits.*/
782 {
783 size_t i;
784 twodigits carry = 1; /* for 2's-comp calculation */
785 twodigits accum = 0; /* sliding register */
786 unsigned int accumbits = 0; /* number of bits in accum */
787 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
790 twodigits thisbyte = *p;
791 /* Compute correction for 2's comp, if needed. */
792 if (is_signed) {
793 thisbyte = (0xff ^ thisbyte) + carry;
794 carry = thisbyte >> 8;
795 thisbyte &= 0xff;
796 }
797 /* Because we're going LSB to MSB, thisbyte is
798 more significant than what's already in accum,
799 so needs to be prepended to accum. */
800 accum |= (twodigits)thisbyte << accumbits;
801 accumbits += 8;
802 if (accumbits >= PyLong_SHIFT) {
803 /* There's enough to fill a Python digit. */
804 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000805 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 ++idigit;
807 accum >>= PyLong_SHIFT;
808 accumbits -= PyLong_SHIFT;
809 assert(accumbits < PyLong_SHIFT);
810 }
811 }
812 assert(accumbits < PyLong_SHIFT);
813 if (accumbits) {
814 assert(idigit < ndigits);
815 v->ob_digit[idigit] = (digit)accum;
816 ++idigit;
817 }
818 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 Py_SIZE(v) = is_signed ? -idigit : idigit;
821 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000822}
823
824int
825_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 unsigned char* bytes, size_t n,
827 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000830 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000832 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
834 digit carry; /* for computing 2's-comp */
835 size_t j; /* # bytes filled */
836 unsigned char* p; /* pointer to next byte in bytes */
837 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (Py_SIZE(v) < 0) {
842 ndigits = -(Py_SIZE(v));
843 if (!is_signed) {
844 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000845 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return -1;
847 }
848 do_twos_comp = 1;
849 }
850 else {
851 ndigits = Py_SIZE(v);
852 do_twos_comp = 0;
853 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (little_endian) {
856 p = bytes;
857 pincr = 1;
858 }
859 else {
860 p = bytes + n - 1;
861 pincr = -1;
862 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* Copy over all the Python digits.
865 It's crucial that every Python digit except for the MSD contribute
866 exactly PyLong_SHIFT bits to the total, so first assert that the long is
867 normalized. */
868 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
869 j = 0;
870 accum = 0;
871 accumbits = 0;
872 carry = do_twos_comp ? 1 : 0;
873 for (i = 0; i < ndigits; ++i) {
874 digit thisdigit = v->ob_digit[i];
875 if (do_twos_comp) {
876 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
877 carry = thisdigit >> PyLong_SHIFT;
878 thisdigit &= PyLong_MASK;
879 }
880 /* Because we're going LSB to MSB, thisdigit is more
881 significant than what's already in accum, so needs to be
882 prepended to accum. */
883 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* The most-significant digit may be (probably is) at least
886 partly empty. */
887 if (i == ndigits - 1) {
888 /* Count # of sign bits -- they needn't be stored,
889 * although for signed conversion we need later to
890 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000891 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 while (s != 0) {
893 s >>= 1;
894 accumbits++;
895 }
896 }
897 else
898 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* Store as many bytes as possible. */
901 while (accumbits >= 8) {
902 if (j >= n)
903 goto Overflow;
904 ++j;
905 *p = (unsigned char)(accum & 0xff);
906 p += pincr;
907 accumbits -= 8;
908 accum >>= 8;
909 }
910 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Store the straggler (if any). */
913 assert(accumbits < 8);
914 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
915 if (accumbits > 0) {
916 if (j >= n)
917 goto Overflow;
918 ++j;
919 if (do_twos_comp) {
920 /* Fill leading bits of the byte with sign bits
921 (appropriately pretending that the long had an
922 infinite supply of sign bits). */
923 accum |= (~(twodigits)0) << accumbits;
924 }
925 *p = (unsigned char)(accum & 0xff);
926 p += pincr;
927 }
928 else if (j == n && n > 0 && is_signed) {
929 /* The main loop filled the byte array exactly, so the code
930 just above didn't get to ensure there's a sign bit, and the
931 loop below wouldn't add one either. Make sure a sign bit
932 exists. */
933 unsigned char msb = *(p - pincr);
934 int sign_bit_set = msb >= 0x80;
935 assert(accumbits == 0);
936 if (sign_bit_set == do_twos_comp)
937 return 0;
938 else
939 goto Overflow;
940 }
Tim Peters05607ad2001-06-13 21:01:27 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Fill remaining bytes with copies of the sign bit. */
943 {
944 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
945 for ( ; j < n; ++j, p += pincr)
946 *p = signbyte;
947 }
Tim Peters05607ad2001-06-13 21:01:27 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000950
Mark Dickinson22b20182010-05-10 21:27:53 +0000951 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
953 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000954
Tim Peters2a9b3672001-06-11 21:23:58 +0000955}
956
Mark Dickinson8d48b432011-10-23 20:47:14 +0100957/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000958
959PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000960PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000961{
Mark Dickinson91044792012-10-18 19:21:43 +0100962#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100963 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
964#else
965
Tim Peters70128a12001-06-16 08:48:40 +0000966#ifndef HAVE_LONG_LONG
967# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
968#endif
969#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000971#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100973#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000974
Guido van Rossum78694d91998-09-18 14:14:13 +0000975}
976
Mark Dickinson8d48b432011-10-23 20:47:14 +0100977/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000978
979void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000980PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000981{
Tim Peters70128a12001-06-16 08:48:40 +0000982#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
986 x = PyLong_AsLong(vv);
987 else
988 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000989#else
Tim Peters70128a12001-06-16 08:48:40 +0000990
991#ifndef HAVE_LONG_LONG
992# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
993#endif
994#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000996#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1000 x = PyLong_AsLongLong(vv);
1001 else
1002 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001003
1004#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (x == -1 && PyErr_Occurred())
1007 return NULL;
1008 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009}
1010
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001011#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001012
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001013/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001014 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001015 */
1016
Mark Dickinson22b20182010-05-10 21:27:53 +00001017#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001018
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001019/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001020
1021PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001022PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 PyLongObject *v;
1025 unsigned PY_LONG_LONG abs_ival;
1026 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1027 int ndigits = 0;
1028 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 CHECK_SMALL_INT(ival);
1031 if (ival < 0) {
1032 /* avoid signed overflow on negation; see comments
1033 in PyLong_FromLong above. */
1034 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1035 negative = 1;
1036 }
1037 else {
1038 abs_ival = (unsigned PY_LONG_LONG)ival;
1039 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* Count the number of Python digits.
1042 We used to pick 5 ("big enough for anything"), but that's a
1043 waste of time and space given that 5*15 = 75 bits are rarely
1044 needed. */
1045 t = abs_ival;
1046 while (t) {
1047 ++ndigits;
1048 t >>= PyLong_SHIFT;
1049 }
1050 v = _PyLong_New(ndigits);
1051 if (v != NULL) {
1052 digit *p = v->ob_digit;
1053 Py_SIZE(v) = negative ? -ndigits : ndigits;
1054 t = abs_ival;
1055 while (t) {
1056 *p++ = (digit)(t & PyLong_MASK);
1057 t >>= PyLong_SHIFT;
1058 }
1059 }
1060 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001061}
1062
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001063/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001064
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001065PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001066PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyLongObject *v;
1069 unsigned PY_LONG_LONG t;
1070 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (ival < PyLong_BASE)
1073 return PyLong_FromLong((long)ival);
1074 /* Count the number of Python digits. */
1075 t = (unsigned PY_LONG_LONG)ival;
1076 while (t) {
1077 ++ndigits;
1078 t >>= PyLong_SHIFT;
1079 }
1080 v = _PyLong_New(ndigits);
1081 if (v != NULL) {
1082 digit *p = v->ob_digit;
1083 Py_SIZE(v) = ndigits;
1084 while (ival) {
1085 *p++ = (digit)(ival & PyLong_MASK);
1086 ival >>= PyLong_SHIFT;
1087 }
1088 }
1089 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001090}
1091
Martin v. Löwis18e16552006-02-15 17:27:45 +00001092/* Create a new long int object from a C Py_ssize_t. */
1093
1094PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001095PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyLongObject *v;
1098 size_t abs_ival;
1099 size_t t; /* unsigned so >> doesn't propagate sign bit */
1100 int ndigits = 0;
1101 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 CHECK_SMALL_INT(ival);
1104 if (ival < 0) {
1105 /* avoid signed overflow when ival = SIZE_T_MIN */
1106 abs_ival = (size_t)(-1-ival)+1;
1107 negative = 1;
1108 }
1109 else {
1110 abs_ival = (size_t)ival;
1111 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 /* Count the number of Python digits. */
1114 t = abs_ival;
1115 while (t) {
1116 ++ndigits;
1117 t >>= PyLong_SHIFT;
1118 }
1119 v = _PyLong_New(ndigits);
1120 if (v != NULL) {
1121 digit *p = v->ob_digit;
1122 Py_SIZE(v) = negative ? -ndigits : ndigits;
1123 t = abs_ival;
1124 while (t) {
1125 *p++ = (digit)(t & PyLong_MASK);
1126 t >>= PyLong_SHIFT;
1127 }
1128 }
1129 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001130}
1131
1132/* Create a new long int object from a C size_t. */
1133
1134PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001135PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyLongObject *v;
1138 size_t t;
1139 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 if (ival < PyLong_BASE)
1142 return PyLong_FromLong((long)ival);
1143 /* Count the number of Python digits. */
1144 t = ival;
1145 while (t) {
1146 ++ndigits;
1147 t >>= PyLong_SHIFT;
1148 }
1149 v = _PyLong_New(ndigits);
1150 if (v != NULL) {
1151 digit *p = v->ob_digit;
1152 Py_SIZE(v) = ndigits;
1153 while (ival) {
1154 *p++ = (digit)(ival & PyLong_MASK);
1155 ival >>= PyLong_SHIFT;
1156 }
1157 }
1158 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159}
1160
Mark Dickinson8d48b432011-10-23 20:47:14 +01001161/* Get a C long long int from a long int object or any object that has an
1162 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001163
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001164PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001165PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyLongObject *v;
1168 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (vv == NULL) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175 if (!PyLong_Check(vv)) {
1176 PyNumberMethods *nb;
1177 PyObject *io;
1178 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1179 nb->nb_int == NULL) {
1180 PyErr_SetString(PyExc_TypeError, "an integer is required");
1181 return -1;
1182 }
1183 io = (*nb->nb_int) (vv);
1184 if (io == NULL)
1185 return -1;
1186 if (PyLong_Check(io)) {
1187 bytes = PyLong_AsLongLong(io);
1188 Py_DECREF(io);
1189 return bytes;
1190 }
1191 Py_DECREF(io);
1192 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1193 return -1;
1194 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 v = (PyLongObject*)vv;
1197 switch(Py_SIZE(v)) {
1198 case -1: return -(sdigit)v->ob_digit[0];
1199 case 0: return 0;
1200 case 1: return v->ob_digit[0];
1201 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001202 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001203 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1206 if (res < 0)
1207 return (PY_LONG_LONG)-1;
1208 else
1209 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210}
1211
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001212/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001213 Return -1 and set an error if overflow occurs. */
1214
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001215unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001216PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyLongObject *v;
1219 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001221
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001222 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyErr_BadInternalCall();
1224 return (unsigned PY_LONG_LONG)-1;
1225 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001226 if (!PyLong_Check(vv)) {
1227 PyErr_SetString(PyExc_TypeError, "an integer is required");
1228 return (unsigned PY_LONG_LONG)-1;
1229 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 v = (PyLongObject*)vv;
1232 switch(Py_SIZE(v)) {
1233 case 0: return 0;
1234 case 1: return v->ob_digit[0];
1235 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001236
Mark Dickinson22b20182010-05-10 21:27:53 +00001237 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001238 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1241 if (res < 0)
1242 return (unsigned PY_LONG_LONG)res;
1243 else
1244 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001245}
Tim Petersd1a7da62001-06-13 00:35:57 +00001246
Thomas Hellera4ea6032003-04-17 18:55:45 +00001247/* Get a C unsigned long int from a long int object, ignoring the high bits.
1248 Returns -1 and sets an error condition if an error occurs. */
1249
Guido van Rossumddefaf32007-01-14 03:31:43 +00001250static unsigned PY_LONG_LONG
1251_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 register PyLongObject *v;
1254 unsigned PY_LONG_LONG x;
1255 Py_ssize_t i;
1256 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (vv == NULL || !PyLong_Check(vv)) {
1259 PyErr_BadInternalCall();
1260 return (unsigned long) -1;
1261 }
1262 v = (PyLongObject *)vv;
1263 switch(Py_SIZE(v)) {
1264 case 0: return 0;
1265 case 1: return v->ob_digit[0];
1266 }
1267 i = Py_SIZE(v);
1268 sign = 1;
1269 x = 0;
1270 if (i < 0) {
1271 sign = -1;
1272 i = -i;
1273 }
1274 while (--i >= 0) {
1275 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1276 }
1277 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001278}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001279
1280unsigned PY_LONG_LONG
1281PyLong_AsUnsignedLongLongMask(register PyObject *op)
1282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 PyNumberMethods *nb;
1284 PyLongObject *lo;
1285 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (op && PyLong_Check(op))
1288 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1291 nb->nb_int == NULL) {
1292 PyErr_SetString(PyExc_TypeError, "an integer is required");
1293 return (unsigned PY_LONG_LONG)-1;
1294 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 lo = (PyLongObject*) (*nb->nb_int) (op);
1297 if (lo == NULL)
1298 return (unsigned PY_LONG_LONG)-1;
1299 if (PyLong_Check(lo)) {
1300 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1301 Py_DECREF(lo);
1302 if (PyErr_Occurred())
1303 return (unsigned PY_LONG_LONG)-1;
1304 return val;
1305 }
1306 else
1307 {
1308 Py_DECREF(lo);
1309 PyErr_SetString(PyExc_TypeError,
1310 "nb_int should return int object");
1311 return (unsigned PY_LONG_LONG)-1;
1312 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001313}
Tim Petersd1a7da62001-06-13 00:35:57 +00001314
Mark Dickinson8d48b432011-10-23 20:47:14 +01001315/* Get a C long long int from a long int object or any object that has an
1316 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001317
Mark Dickinson8d48b432011-10-23 20:47:14 +01001318 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1319 the result. Otherwise *overflow is 0.
1320
1321 For other errors (e.g., TypeError), return -1 and set an error condition.
1322 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001323*/
1324
1325PY_LONG_LONG
1326PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* This version by Tim Peters */
1329 register PyLongObject *v;
1330 unsigned PY_LONG_LONG x, prev;
1331 PY_LONG_LONG res;
1332 Py_ssize_t i;
1333 int sign;
1334 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 *overflow = 0;
1337 if (vv == NULL) {
1338 PyErr_BadInternalCall();
1339 return -1;
1340 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (!PyLong_Check(vv)) {
1343 PyNumberMethods *nb;
1344 nb = vv->ob_type->tp_as_number;
1345 if (nb == NULL || nb->nb_int == NULL) {
1346 PyErr_SetString(PyExc_TypeError,
1347 "an integer is required");
1348 return -1;
1349 }
1350 vv = (*nb->nb_int) (vv);
1351 if (vv == NULL)
1352 return -1;
1353 do_decref = 1;
1354 if (!PyLong_Check(vv)) {
1355 Py_DECREF(vv);
1356 PyErr_SetString(PyExc_TypeError,
1357 "nb_int should return int object");
1358 return -1;
1359 }
1360 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 res = -1;
1363 v = (PyLongObject *)vv;
1364 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 switch (i) {
1367 case -1:
1368 res = -(sdigit)v->ob_digit[0];
1369 break;
1370 case 0:
1371 res = 0;
1372 break;
1373 case 1:
1374 res = v->ob_digit[0];
1375 break;
1376 default:
1377 sign = 1;
1378 x = 0;
1379 if (i < 0) {
1380 sign = -1;
1381 i = -(i);
1382 }
1383 while (--i >= 0) {
1384 prev = x;
1385 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1386 if ((x >> PyLong_SHIFT) != prev) {
1387 *overflow = sign;
1388 goto exit;
1389 }
1390 }
1391 /* Haven't lost any bits, but casting to long requires extra
1392 * care (see comment above).
1393 */
1394 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1395 res = (PY_LONG_LONG)x * sign;
1396 }
1397 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1398 res = PY_LLONG_MIN;
1399 }
1400 else {
1401 *overflow = sign;
1402 /* res is already set to -1 */
1403 }
1404 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001405 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (do_decref) {
1407 Py_DECREF(vv);
1408 }
1409 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001410}
1411
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001412#endif /* HAVE_LONG_LONG */
1413
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001414#define CHECK_BINOP(v,w) \
1415 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001416 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1417 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001418 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001419
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001420/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1421 2**k if d is nonzero, else 0. */
1422
1423static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1425 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001426};
1427
1428static int
1429bits_in_digit(digit d)
1430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 int d_bits = 0;
1432 while (d >= 32) {
1433 d_bits += 6;
1434 d >>= 6;
1435 }
1436 d_bits += (int)BitLengthTable[d];
1437 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001438}
1439
Tim Peters877a2122002-08-12 05:09:36 +00001440/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1441 * is modified in place, by adding y to it. Carries are propagated as far as
1442 * x[m-1], and the remaining carry (0 or 1) is returned.
1443 */
1444static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001445v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 Py_ssize_t i;
1448 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 assert(m >= n);
1451 for (i = 0; i < n; ++i) {
1452 carry += x[i] + y[i];
1453 x[i] = carry & PyLong_MASK;
1454 carry >>= PyLong_SHIFT;
1455 assert((carry & 1) == carry);
1456 }
1457 for (; carry && i < m; ++i) {
1458 carry += x[i];
1459 x[i] = carry & PyLong_MASK;
1460 carry >>= PyLong_SHIFT;
1461 assert((carry & 1) == carry);
1462 }
1463 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001464}
1465
1466/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1467 * is modified in place, by subtracting y from it. Borrows are propagated as
1468 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1469 */
1470static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001471v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 Py_ssize_t i;
1474 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 assert(m >= n);
1477 for (i = 0; i < n; ++i) {
1478 borrow = x[i] - y[i] - borrow;
1479 x[i] = borrow & PyLong_MASK;
1480 borrow >>= PyLong_SHIFT;
1481 borrow &= 1; /* keep only 1 sign bit */
1482 }
1483 for (; borrow && i < m; ++i) {
1484 borrow = x[i] - borrow;
1485 x[i] = borrow & PyLong_MASK;
1486 borrow >>= PyLong_SHIFT;
1487 borrow &= 1;
1488 }
1489 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001490}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001491
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001492/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1493 * result in z[0:m], and return the d bits shifted out of the top.
1494 */
1495static digit
1496v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 Py_ssize_t i;
1499 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 assert(0 <= d && d < PyLong_SHIFT);
1502 for (i=0; i < m; i++) {
1503 twodigits acc = (twodigits)a[i] << d | carry;
1504 z[i] = (digit)acc & PyLong_MASK;
1505 carry = (digit)(acc >> PyLong_SHIFT);
1506 }
1507 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001508}
1509
1510/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1511 * result in z[0:m], and return the d bits shifted out of the bottom.
1512 */
1513static digit
1514v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 Py_ssize_t i;
1517 digit carry = 0;
1518 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 assert(0 <= d && d < PyLong_SHIFT);
1521 for (i=m; i-- > 0;) {
1522 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1523 carry = (digit)acc & mask;
1524 z[i] = (digit)(acc >> d);
1525 }
1526 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001527}
1528
Tim Peters212e6142001-07-14 12:23:19 +00001529/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1530 in pout, and returning the remainder. pin and pout point at the LSD.
1531 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001532 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001533 immutable. */
1534
1535static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001536inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 assert(n > 0 && n <= PyLong_MASK);
1541 pin += size;
1542 pout += size;
1543 while (--size >= 0) {
1544 digit hi;
1545 rem = (rem << PyLong_SHIFT) | *--pin;
1546 *--pout = hi = (digit)(rem / n);
1547 rem -= (twodigits)hi * n;
1548 }
1549 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001550}
1551
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001552/* Divide a long integer by a digit, returning both the quotient
1553 (as function result) and the remainder (through *prem).
1554 The sign of a is ignored; n should not be zero. */
1555
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001556static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001557divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 const Py_ssize_t size = ABS(Py_SIZE(a));
1560 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 assert(n > 0 && n <= PyLong_MASK);
1563 z = _PyLong_New(size);
1564 if (z == NULL)
1565 return NULL;
1566 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1567 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001568}
1569
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001570/* Convert a long integer to a base 10 string. Returns a new non-shared
1571 string. (Return value is non-shared so that callers can modify the
1572 returned value if necessary.) */
1573
Victor Stinnerd3f08822012-05-29 12:57:52 +02001574static int
1575long_to_decimal_string_internal(PyObject *aa,
1576 PyObject **p_output,
1577 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 PyLongObject *scratch, *a;
1580 PyObject *str;
1581 Py_ssize_t size, strlen, size_a, i, j;
1582 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001584 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 a = (PyLongObject *)aa;
1587 if (a == NULL || !PyLong_Check(a)) {
1588 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001589 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 }
1591 size_a = ABS(Py_SIZE(a));
1592 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 /* quick and dirty upper bound for the number of digits
1595 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 But log2(a) < size_a * PyLong_SHIFT, and
1600 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1601 > 3 * _PyLong_DECIMAL_SHIFT
1602 */
1603 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1604 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001605 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001606 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 }
1608 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1609 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1610 scratch = _PyLong_New(size);
1611 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001612 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* convert array of base _PyLong_BASE digits in pin to an array of
1615 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1616 Volume 2 (3rd edn), section 4.4, Method 1b). */
1617 pin = a->ob_digit;
1618 pout = scratch->ob_digit;
1619 size = 0;
1620 for (i = size_a; --i >= 0; ) {
1621 digit hi = pin[i];
1622 for (j = 0; j < size; j++) {
1623 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1624 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1625 pout[j] = (digit)(z - (twodigits)hi *
1626 _PyLong_DECIMAL_BASE);
1627 }
1628 while (hi) {
1629 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1630 hi /= _PyLong_DECIMAL_BASE;
1631 }
1632 /* check for keyboard interrupt */
1633 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001634 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001635 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001636 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 }
1638 /* pout should have at least one digit, so that the case when a = 0
1639 works correctly */
1640 if (size == 0)
1641 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* calculate exact length of output string, and allocate */
1644 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1645 tenpow = 10;
1646 rem = pout[size-1];
1647 while (rem >= tenpow) {
1648 tenpow *= 10;
1649 strlen++;
1650 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001651 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001652 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1653 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001654 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001655 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001656 kind = writer->kind;
1657 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001659 else {
1660 str = PyUnicode_New(strlen, '9');
1661 if (str == NULL) {
1662 Py_DECREF(scratch);
1663 return -1;
1664 }
1665 kind = PyUnicode_KIND(str);
1666 }
1667
1668#define WRITE_DIGITS(TYPE) \
1669 do { \
1670 if (writer) \
1671 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1672 else \
1673 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1674 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001675 /* pout[0] through pout[size-2] contribute exactly \
1676 _PyLong_DECIMAL_SHIFT digits each */ \
1677 for (i=0; i < size - 1; i++) { \
1678 rem = pout[i]; \
1679 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1680 *--p = '0' + rem % 10; \
1681 rem /= 10; \
1682 } \
1683 } \
1684 /* pout[size-1]: always produce at least one decimal digit */ \
1685 rem = pout[i]; \
1686 do { \
1687 *--p = '0' + rem % 10; \
1688 rem /= 10; \
1689 } while (rem != 0); \
1690 \
1691 /* and sign */ \
1692 if (negative) \
1693 *--p = '-'; \
1694 \
1695 /* check we've counted correctly */ \
1696 if (writer) \
1697 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1698 else \
1699 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1700 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001703 if (kind == PyUnicode_1BYTE_KIND) {
1704 Py_UCS1 *p;
1705 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001707 else if (kind == PyUnicode_2BYTE_KIND) {
1708 Py_UCS2 *p;
1709 WRITE_DIGITS(Py_UCS2);
1710 }
1711 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001712 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001713 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001714 WRITE_DIGITS(Py_UCS4);
1715 }
1716#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 if (writer) {
1720 writer->pos += strlen;
1721 }
1722 else {
1723 assert(_PyUnicode_CheckConsistency(str, 1));
1724 *p_output = (PyObject *)str;
1725 }
1726 return 0;
1727}
1728
1729static PyObject *
1730long_to_decimal_string(PyObject *aa)
1731{
1732 PyObject *v;
1733 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1734 return NULL;
1735 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001736}
1737
Mark Dickinsoncd068122009-09-18 14:53:08 +00001738/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001739 which should be one of 2, 8 or 16. Return a string object.
1740 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1741 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001742
Victor Stinnerd3f08822012-05-29 12:57:52 +02001743static int
1744long_format_binary(PyObject *aa, int base, int alternate,
1745 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001749 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001751 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001752 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001754
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (a == NULL || !PyLong_Check(a)) {
1757 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001758 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 }
1760 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001761 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 /* Compute a rough upper bound for the length of the string */
1764 switch (base) {
1765 case 16:
1766 bits = 4;
1767 break;
1768 case 8:
1769 bits = 3;
1770 break;
1771 case 2:
1772 bits = 1;
1773 break;
1774 default:
1775 assert(0); /* shouldn't ever get here */
1776 bits = 0; /* to silence gcc warning */
1777 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001778
Mark Dickinsone2846542012-04-20 21:21:24 +01001779 /* Compute exact length 'sz' of output string. */
1780 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001781 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001782 }
1783 else {
1784 Py_ssize_t size_a_in_bits;
1785 /* Ensure overflow doesn't occur during computation of sz. */
1786 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1787 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001788 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001790 }
1791 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1792 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001793 /* Allow 1 character for a '-' sign. */
1794 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1795 }
1796 if (alternate) {
1797 /* 2 characters for prefix */
1798 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001799 }
1800
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 if (writer) {
1802 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1803 return -1;
1804 kind = writer->kind;
1805 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
1807 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001808 v = PyUnicode_New(sz, 'x');
1809 if (v == NULL)
1810 return -1;
1811 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001813
Victor Stinnerd3f08822012-05-29 12:57:52 +02001814#define WRITE_DIGITS(TYPE) \
1815 do { \
1816 if (writer) \
1817 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1818 else \
1819 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1820 \
1821 if (size_a == 0) { \
1822 *--p = '0'; \
1823 } \
1824 else { \
1825 /* JRH: special case for power-of-2 bases */ \
1826 twodigits accum = 0; \
1827 int accumbits = 0; /* # of bits in accum */ \
1828 Py_ssize_t i; \
1829 for (i = 0; i < size_a; ++i) { \
1830 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1831 accumbits += PyLong_SHIFT; \
1832 assert(accumbits >= bits); \
1833 do { \
1834 char cdigit; \
1835 cdigit = (char)(accum & (base - 1)); \
1836 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1837 *--p = cdigit; \
1838 accumbits -= bits; \
1839 accum >>= bits; \
1840 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1841 } \
1842 } \
1843 \
1844 if (alternate) { \
1845 if (base == 16) \
1846 *--p = 'x'; \
1847 else if (base == 8) \
1848 *--p = 'o'; \
1849 else /* (base == 2) */ \
1850 *--p = 'b'; \
1851 *--p = '0'; \
1852 } \
1853 if (negative) \
1854 *--p = '-'; \
1855 if (writer) \
1856 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1857 else \
1858 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1859 } while (0)
1860
1861 if (kind == PyUnicode_1BYTE_KIND) {
1862 Py_UCS1 *p;
1863 WRITE_DIGITS(Py_UCS1);
1864 }
1865 else if (kind == PyUnicode_2BYTE_KIND) {
1866 Py_UCS2 *p;
1867 WRITE_DIGITS(Py_UCS2);
1868 }
1869 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001870 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001871 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001872 WRITE_DIGITS(Py_UCS4);
1873 }
1874#undef WRITE_DIGITS
1875
1876 if (writer) {
1877 writer->pos += sz;
1878 }
1879 else {
1880 assert(_PyUnicode_CheckConsistency(v, 1));
1881 *p_output = v;
1882 }
1883 return 0;
1884}
1885
1886PyObject *
1887_PyLong_Format(PyObject *obj, int base)
1888{
1889 PyObject *str;
1890 int err;
1891 if (base == 10)
1892 err = long_to_decimal_string_internal(obj, &str, NULL);
1893 else
1894 err = long_format_binary(obj, base, 1, &str, NULL);
1895 if (err == -1)
1896 return NULL;
1897 return str;
1898}
1899
1900int
1901_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1902 PyObject *obj,
1903 int base, int alternate)
1904{
1905 if (base == 10)
1906 return long_to_decimal_string_internal(obj, NULL, writer);
1907 else
1908 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001909}
1910
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911/* Table of digit values for 8-bit string -> integer conversion.
1912 * '0' maps to 0, ..., '9' maps to 9.
1913 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1914 * All other indices map to 37.
1915 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001916 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001917 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001918unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1920 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1921 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1922 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1923 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1924 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1925 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1926 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1927 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1928 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1929 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1930 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1931 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1932 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1933 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1934 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001935};
1936
1937/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001938 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1939 * non-digit (which may be *str!). A normalized long is returned.
1940 * The point to this routine is that it takes time linear in the number of
1941 * string characters.
1942 */
1943static PyLongObject *
1944long_from_binary_base(char **str, int base)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 char *p = *str;
1947 char *start = p;
1948 int bits_per_char;
1949 Py_ssize_t n;
1950 PyLongObject *z;
1951 twodigits accum;
1952 int bits_in_accum;
1953 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1956 n = base;
1957 for (bits_per_char = -1; n; ++bits_per_char)
1958 n >>= 1;
1959 /* n <- total # of bits needed, while setting p to end-of-string */
1960 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1961 ++p;
1962 *str = p;
1963 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1964 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1965 if (n / bits_per_char < p - start) {
1966 PyErr_SetString(PyExc_ValueError,
1967 "int string too large to convert");
1968 return NULL;
1969 }
1970 n = n / PyLong_SHIFT;
1971 z = _PyLong_New(n);
1972 if (z == NULL)
1973 return NULL;
1974 /* Read string from right, and fill in long from left; i.e.,
1975 * from least to most significant in both.
1976 */
1977 accum = 0;
1978 bits_in_accum = 0;
1979 pdigit = z->ob_digit;
1980 while (--p >= start) {
1981 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1982 assert(k >= 0 && k < base);
1983 accum |= (twodigits)k << bits_in_accum;
1984 bits_in_accum += bits_per_char;
1985 if (bits_in_accum >= PyLong_SHIFT) {
1986 *pdigit++ = (digit)(accum & PyLong_MASK);
1987 assert(pdigit - z->ob_digit <= n);
1988 accum >>= PyLong_SHIFT;
1989 bits_in_accum -= PyLong_SHIFT;
1990 assert(bits_in_accum < PyLong_SHIFT);
1991 }
1992 }
1993 if (bits_in_accum) {
1994 assert(bits_in_accum <= PyLong_SHIFT);
1995 *pdigit++ = (digit)accum;
1996 assert(pdigit - z->ob_digit <= n);
1997 }
1998 while (pdigit - z->ob_digit < n)
1999 *pdigit++ = 0;
2000 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002001}
2002
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002003PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002004PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 int sign = 1, error_if_nonzero = 0;
2007 char *start, *orig_str = str;
2008 PyLongObject *z = NULL;
2009 PyObject *strobj;
2010 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 if ((base != 0 && base < 2) || base > 36) {
2013 PyErr_SetString(PyExc_ValueError,
2014 "int() arg 2 must be >= 2 and <= 36");
2015 return NULL;
2016 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002017 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 str++;
2019 if (*str == '+')
2020 ++str;
2021 else if (*str == '-') {
2022 ++str;
2023 sign = -1;
2024 }
2025 if (base == 0) {
2026 if (str[0] != '0')
2027 base = 10;
2028 else if (str[1] == 'x' || str[1] == 'X')
2029 base = 16;
2030 else if (str[1] == 'o' || str[1] == 'O')
2031 base = 8;
2032 else if (str[1] == 'b' || str[1] == 'B')
2033 base = 2;
2034 else {
2035 /* "old" (C-style) octal literal, now invalid.
2036 it might still be zero though */
2037 error_if_nonzero = 1;
2038 base = 10;
2039 }
2040 }
2041 if (str[0] == '0' &&
2042 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2043 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2044 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2045 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 start = str;
2048 if ((base & (base - 1)) == 0)
2049 z = long_from_binary_base(&str, base);
2050 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051/***
2052Binary bases can be converted in time linear in the number of digits, because
2053Python's representation base is binary. Other bases (including decimal!) use
2054the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002055
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056First some math: the largest integer that can be expressed in N base-B digits
2057is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2058case number of Python digits needed to hold it is the smallest integer n s.t.
2059
2060 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2061 BASE**n >= B**N [taking logs to base BASE]
2062 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2063
2064The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2065this quickly. A Python long with that much space is reserved near the start,
2066and the result is computed into it.
2067
2068The input string is actually treated as being in base base**i (i.e., i digits
2069are processed at a time), where two more static arrays hold:
2070
2071 convwidth_base[base] = the largest integer i such that base**i <= BASE
2072 convmultmax_base[base] = base ** convwidth_base[base]
2073
2074The first of these is the largest i such that i consecutive input digits
2075must fit in a single Python digit. The second is effectively the input
2076base we're really using.
2077
2078Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2079convmultmax_base[base], the result is "simply"
2080
2081 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2082
2083where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002084
2085Error analysis: as above, the number of Python digits `n` needed is worst-
2086case
2087
2088 n >= N * log(B)/log(BASE)
2089
2090where `N` is the number of input digits in base `B`. This is computed via
2091
2092 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2093
2094below. Two numeric concerns are how much space this can waste, and whether
2095the computed result can be too small. To be concrete, assume BASE = 2**15,
2096which is the default (and it's unlikely anyone changes that).
2097
2098Waste isn't a problem: provided the first input digit isn't 0, the difference
2099between the worst-case input with N digits and the smallest input with N
2100digits is about a factor of B, but B is small compared to BASE so at most
2101one allocated Python digit can remain unused on that count. If
2102N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2103and adding 1 returns a result 1 larger than necessary. However, that can't
2104happen: whenever B is a power of 2, long_from_binary_base() is called
2105instead, and it's impossible for B**i to be an integer power of 2**15 when
2106B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2107an exact integer when B is not a power of 2, since B**i has a prime factor
2108other than 2 in that case, but (2**15)**j's only prime factor is 2).
2109
2110The computed result can be too small if the true value of N*log(B)/log(BASE)
2111is a little bit larger than an exact integer, but due to roundoff errors (in
2112computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2113yields a numeric result a little less than that integer. Unfortunately, "how
2114close can a transcendental function get to an integer over some range?"
2115questions are generally theoretically intractable. Computer analysis via
2116continued fractions is practical: expand log(B)/log(BASE) via continued
2117fractions, giving a sequence i/j of "the best" rational approximations. Then
2118j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2119we can get very close to being in trouble, but very rarely. For example,
212076573 is a denominator in one of the continued-fraction approximations to
2121log(10)/log(2**15), and indeed:
2122
2123 >>> log(10)/log(2**15)*76573
2124 16958.000000654003
2125
2126is very close to an integer. If we were working with IEEE single-precision,
2127rounding errors could kill us. Finding worst cases in IEEE double-precision
2128requires better-than-double-precision log() functions, and Tim didn't bother.
2129Instead the code checks to see whether the allocated space is enough as each
2130new Python digit is added, and copies the whole thing to a larger long if not.
2131This should happen extremely rarely, and in fact I don't have a test case
2132that triggers it(!). Instead the code was tested by artificially allocating
2133just 1 digit at the start, so that the copying code was exercised for every
2134digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002135***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 register twodigits c; /* current input character */
2137 Py_ssize_t size_z;
2138 int i;
2139 int convwidth;
2140 twodigits convmultmax, convmult;
2141 digit *pz, *pzstop;
2142 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 static double log_base_BASE[37] = {0.0e0,};
2145 static int convwidth_base[37] = {0,};
2146 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (log_base_BASE[base] == 0.0) {
2149 twodigits convmax = base;
2150 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002151
Mark Dickinson22b20182010-05-10 21:27:53 +00002152 log_base_BASE[base] = (log((double)base) /
2153 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 for (;;) {
2155 twodigits next = convmax * base;
2156 if (next > PyLong_BASE)
2157 break;
2158 convmax = next;
2159 ++i;
2160 }
2161 convmultmax_base[base] = convmax;
2162 assert(i > 0);
2163 convwidth_base[base] = i;
2164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 /* Find length of the string of numeric characters. */
2167 scan = str;
2168 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2169 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Create a long object that can contain the largest possible
2172 * integer with this base and length. Note that there's no
2173 * need to initialize z->ob_digit -- no slot is read up before
2174 * being stored into.
2175 */
2176 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2177 /* Uncomment next line to test exceedingly rare copy code */
2178 /* size_z = 1; */
2179 assert(size_z > 0);
2180 z = _PyLong_New(size_z);
2181 if (z == NULL)
2182 return NULL;
2183 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* `convwidth` consecutive input digits are treated as a single
2186 * digit in base `convmultmax`.
2187 */
2188 convwidth = convwidth_base[base];
2189 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* Work ;-) */
2192 while (str < scan) {
2193 /* grab up to convwidth digits from the input string */
2194 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2195 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2196 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002197 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 assert(c < PyLong_BASE);
2199 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 convmult = convmultmax;
2202 /* Calculate the shift only if we couldn't get
2203 * convwidth digits.
2204 */
2205 if (i != convwidth) {
2206 convmult = base;
2207 for ( ; i > 1; --i)
2208 convmult *= base;
2209 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* Multiply z by convmult, and add c. */
2212 pz = z->ob_digit;
2213 pzstop = pz + Py_SIZE(z);
2214 for (; pz < pzstop; ++pz) {
2215 c += (twodigits)*pz * convmult;
2216 *pz = (digit)(c & PyLong_MASK);
2217 c >>= PyLong_SHIFT;
2218 }
2219 /* carry off the current end? */
2220 if (c) {
2221 assert(c < PyLong_BASE);
2222 if (Py_SIZE(z) < size_z) {
2223 *pz = (digit)c;
2224 ++Py_SIZE(z);
2225 }
2226 else {
2227 PyLongObject *tmp;
2228 /* Extremely rare. Get more space. */
2229 assert(Py_SIZE(z) == size_z);
2230 tmp = _PyLong_New(size_z + 1);
2231 if (tmp == NULL) {
2232 Py_DECREF(z);
2233 return NULL;
2234 }
2235 memcpy(tmp->ob_digit,
2236 z->ob_digit,
2237 sizeof(digit) * size_z);
2238 Py_DECREF(z);
2239 z = tmp;
2240 z->ob_digit[size_z] = (digit)c;
2241 ++size_z;
2242 }
2243 }
2244 }
2245 }
2246 if (z == NULL)
2247 return NULL;
2248 if (error_if_nonzero) {
2249 /* reset the base to 0, else the exception message
2250 doesn't make too much sense */
2251 base = 0;
2252 if (Py_SIZE(z) != 0)
2253 goto onError;
2254 /* there might still be other problems, therefore base
2255 remains zero here for the same reason */
2256 }
2257 if (str == start)
2258 goto onError;
2259 if (sign < 0)
2260 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002261 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 str++;
2263 if (*str != '\0')
2264 goto onError;
2265 if (pend)
2266 *pend = str;
2267 long_normalize(z);
2268 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002269
Mark Dickinson22b20182010-05-10 21:27:53 +00002270 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 Py_XDECREF(z);
2272 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2273 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2274 if (strobj == NULL)
2275 return NULL;
2276 PyErr_Format(PyExc_ValueError,
2277 "invalid literal for int() with base %d: %R",
2278 base, strobj);
2279 Py_DECREF(strobj);
2280 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002281}
2282
2283PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002284PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002285{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002286 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2287 if (unicode == NULL)
2288 return NULL;
2289 v = PyLong_FromUnicodeObject(unicode, base);
2290 Py_DECREF(unicode);
2291 return v;
2292}
2293
2294PyObject *
2295PyLong_FromUnicodeObject(PyObject *u, int base)
2296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002298 PyObject *asciidig;
2299 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002302 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002303 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002305 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002306 if (buffer == NULL) {
2307 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 return NULL;
2309 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002310 result = PyLong_FromString(buffer, &end, base);
2311 if (result != NULL && end != buffer + buflen) {
2312 PyErr_SetString(PyExc_ValueError,
2313 "null byte in argument for int()");
2314 Py_DECREF(result);
2315 result = NULL;
2316 }
2317 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319}
2320
Tim Peters9f688bf2000-07-07 15:53:28 +00002321/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002322static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002324static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325
2326/* Long division with remainder, top-level routine */
2327
Guido van Rossume32e0141992-01-19 16:31:05 +00002328static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002329long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2333 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (size_b == 0) {
2336 PyErr_SetString(PyExc_ZeroDivisionError,
2337 "integer division or modulo by zero");
2338 return -1;
2339 }
2340 if (size_a < size_b ||
2341 (size_a == size_b &&
2342 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2343 /* |a| < |b|. */
2344 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2345 if (*pdiv == NULL)
2346 return -1;
2347 Py_INCREF(a);
2348 *prem = (PyLongObject *) a;
2349 return 0;
2350 }
2351 if (size_b == 1) {
2352 digit rem = 0;
2353 z = divrem1(a, b->ob_digit[0], &rem);
2354 if (z == NULL)
2355 return -1;
2356 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2357 if (*prem == NULL) {
2358 Py_DECREF(z);
2359 return -1;
2360 }
2361 }
2362 else {
2363 z = x_divrem(a, b, prem);
2364 if (z == NULL)
2365 return -1;
2366 }
2367 /* Set the signs.
2368 The quotient z has the sign of a*b;
2369 the remainder r has the sign of a,
2370 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002371 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2372 _PyLong_Negate(&z);
2373 if (z == NULL) {
2374 Py_CLEAR(*prem);
2375 return -1;
2376 }
2377 }
2378 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2379 _PyLong_Negate(prem);
2380 if (*prem == NULL) {
2381 Py_DECREF(z);
2382 Py_CLEAR(*prem);
2383 return -1;
2384 }
2385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 *pdiv = maybe_small_long(z);
2387 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002388}
2389
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002390/* Unsigned long division with remainder -- the algorithm. The arguments v1
2391 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002392
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002393static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002394x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 PyLongObject *v, *w, *a;
2397 Py_ssize_t i, k, size_v, size_w;
2398 int d;
2399 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2400 twodigits vv;
2401 sdigit zhi;
2402 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2405 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2406 handle the special case when the initial estimate q for a quotient
2407 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2408 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* allocate space; w will also be used to hold the final remainder */
2411 size_v = ABS(Py_SIZE(v1));
2412 size_w = ABS(Py_SIZE(w1));
2413 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2414 v = _PyLong_New(size_v+1);
2415 if (v == NULL) {
2416 *prem = NULL;
2417 return NULL;
2418 }
2419 w = _PyLong_New(size_w);
2420 if (w == NULL) {
2421 Py_DECREF(v);
2422 *prem = NULL;
2423 return NULL;
2424 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2427 shift v1 left by the same amount. Results go into w and v. */
2428 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2429 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2430 assert(carry == 0);
2431 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2432 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2433 v->ob_digit[size_v] = carry;
2434 size_v++;
2435 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2438 at most (and usually exactly) k = size_v - size_w digits. */
2439 k = size_v - size_w;
2440 assert(k >= 0);
2441 a = _PyLong_New(k);
2442 if (a == NULL) {
2443 Py_DECREF(w);
2444 Py_DECREF(v);
2445 *prem = NULL;
2446 return NULL;
2447 }
2448 v0 = v->ob_digit;
2449 w0 = w->ob_digit;
2450 wm1 = w0[size_w-1];
2451 wm2 = w0[size_w-2];
2452 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2453 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2454 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002457 Py_DECREF(a);
2458 Py_DECREF(w);
2459 Py_DECREF(v);
2460 *prem = NULL;
2461 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002462 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* estimate quotient digit q; may overestimate by 1 (rare) */
2465 vtop = vk[size_w];
2466 assert(vtop <= wm1);
2467 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2468 q = (digit)(vv / wm1);
2469 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2470 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2471 | vk[size_w-2])) {
2472 --q;
2473 r += wm1;
2474 if (r >= PyLong_BASE)
2475 break;
2476 }
2477 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2480 zhi = 0;
2481 for (i = 0; i < size_w; ++i) {
2482 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2483 -PyLong_BASE * q <= z < PyLong_BASE */
2484 z = (sdigit)vk[i] + zhi -
2485 (stwodigits)q * (stwodigits)w0[i];
2486 vk[i] = (digit)z & PyLong_MASK;
2487 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002488 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 /* add w back if q was too large (this branch taken rarely) */
2492 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2493 if ((sdigit)vtop + zhi < 0) {
2494 carry = 0;
2495 for (i = 0; i < size_w; ++i) {
2496 carry += vk[i] + w0[i];
2497 vk[i] = carry & PyLong_MASK;
2498 carry >>= PyLong_SHIFT;
2499 }
2500 --q;
2501 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 /* store quotient digit */
2504 assert(q < PyLong_BASE);
2505 *--ak = q;
2506 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* unshift remainder; we reuse w to store the result */
2509 carry = v_rshift(w0, v0, size_w, d);
2510 assert(carry==0);
2511 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 *prem = long_normalize(w);
2514 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002515}
2516
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002517/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2518 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2519 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2520 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2521 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2522 -1.0. */
2523
2524/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2525#if DBL_MANT_DIG == 53
2526#define EXP2_DBL_MANT_DIG 9007199254740992.0
2527#else
2528#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2529#endif
2530
2531double
2532_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2535 /* See below for why x_digits is always large enough. */
2536 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2537 double dx;
2538 /* Correction term for round-half-to-even rounding. For a digit x,
2539 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2540 multiple of 4, rounding ties to a multiple of 8. */
2541 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 a_size = ABS(Py_SIZE(a));
2544 if (a_size == 0) {
2545 /* Special case for 0: significand 0.0, exponent 0. */
2546 *e = 0;
2547 return 0.0;
2548 }
2549 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2550 /* The following is an overflow-free version of the check
2551 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2552 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2553 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2554 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002555 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2559 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 Number of digits needed for result: write // for floor division.
2562 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2571 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2574 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2575 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 in both cases.
2582 */
2583 if (a_bits <= DBL_MANT_DIG + 2) {
2584 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2585 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2586 x_size = 0;
2587 while (x_size < shift_digits)
2588 x_digits[x_size++] = 0;
2589 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2590 (int)shift_bits);
2591 x_size += a_size;
2592 x_digits[x_size++] = rem;
2593 }
2594 else {
2595 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2596 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2597 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2598 a_size - shift_digits, (int)shift_bits);
2599 x_size = a_size - shift_digits;
2600 /* For correct rounding below, we need the least significant
2601 bit of x to be 'sticky' for this shift: if any of the bits
2602 shifted out was nonzero, we set the least significant bit
2603 of x. */
2604 if (rem)
2605 x_digits[0] |= 1;
2606 else
2607 while (shift_digits > 0)
2608 if (a->ob_digit[--shift_digits]) {
2609 x_digits[0] |= 1;
2610 break;
2611 }
2612 }
Victor Stinner63941882011-09-29 00:42:28 +02002613 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 /* Round, and convert to double. */
2616 x_digits[0] += half_even_correction[x_digits[0] & 7];
2617 dx = x_digits[--x_size];
2618 while (x_size > 0)
2619 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 /* Rescale; make correction if result is 1.0. */
2622 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2623 if (dx == 1.0) {
2624 if (a_bits == PY_SSIZE_T_MAX)
2625 goto overflow;
2626 dx = 0.5;
2627 a_bits += 1;
2628 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 *e = a_bits;
2631 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002632
2633 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 /* exponent > PY_SSIZE_T_MAX */
2635 PyErr_SetString(PyExc_OverflowError,
2636 "huge integer: number of bits overflows a Py_ssize_t");
2637 *e = 0;
2638 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002639}
2640
2641/* Get a C double from a long int object. Rounds to the nearest double,
2642 using the round-half-to-even rule in the case of a tie. */
2643
2644double
2645PyLong_AsDouble(PyObject *v)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 Py_ssize_t exponent;
2648 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002649
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002650 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyErr_BadInternalCall();
2652 return -1.0;
2653 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002654 if (!PyLong_Check(v)) {
2655 PyErr_SetString(PyExc_TypeError, "an integer is required");
2656 return -1.0;
2657 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2659 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2660 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002661 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 return -1.0;
2663 }
2664 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002665}
2666
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002667/* Methods */
2668
2669static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002670long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002673}
2674
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002675static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002676long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 if (Py_SIZE(a) != Py_SIZE(b)) {
2681 sign = Py_SIZE(a) - Py_SIZE(b);
2682 }
2683 else {
2684 Py_ssize_t i = ABS(Py_SIZE(a));
2685 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2686 ;
2687 if (i < 0)
2688 sign = 0;
2689 else {
2690 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2691 if (Py_SIZE(a) < 0)
2692 sign = -sign;
2693 }
2694 }
2695 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002696}
2697
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002698#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002700
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002701static PyObject *
2702long_richcompare(PyObject *self, PyObject *other, int op)
2703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 int result;
2705 PyObject *v;
2706 CHECK_BINOP(self, other);
2707 if (self == other)
2708 result = 0;
2709 else
2710 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2711 /* Convert the return value to a Boolean */
2712 switch (op) {
2713 case Py_EQ:
2714 v = TEST_COND(result == 0);
2715 break;
2716 case Py_NE:
2717 v = TEST_COND(result != 0);
2718 break;
2719 case Py_LE:
2720 v = TEST_COND(result <= 0);
2721 break;
2722 case Py_GE:
2723 v = TEST_COND(result >= 0);
2724 break;
2725 case Py_LT:
2726 v = TEST_COND(result == -1);
2727 break;
2728 case Py_GT:
2729 v = TEST_COND(result == 1);
2730 break;
2731 default:
2732 PyErr_BadArgument();
2733 return NULL;
2734 }
2735 Py_INCREF(v);
2736 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002737}
2738
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002739static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002740long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002741{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002742 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 Py_ssize_t i;
2744 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 i = Py_SIZE(v);
2747 switch(i) {
2748 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2749 case 0: return 0;
2750 case 1: return v->ob_digit[0];
2751 }
2752 sign = 1;
2753 x = 0;
2754 if (i < 0) {
2755 sign = -1;
2756 i = -(i);
2757 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002759 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2760 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2761 _PyHASH_MODULUS.
2762
2763 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2764 amounts to a rotation of the bits of x. To see this, write
2765
2766 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2767
2768 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2769 PyLong_SHIFT bits of x (those that are shifted out of the
2770 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2771 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2772 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2773 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2774 congruent to y modulo _PyHASH_MODULUS. So
2775
2776 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2777
2778 The right-hand side is just the result of rotating the
2779 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2780 not all _PyHASH_BITS bits of x are 1s, the same is true
2781 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2782 the reduction of x*2**PyLong_SHIFT modulo
2783 _PyHASH_MODULUS. */
2784 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2785 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002787 if (x >= _PyHASH_MODULUS)
2788 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 }
2790 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002791 if (x == (Py_uhash_t)-1)
2792 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002793 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002794}
2795
2796
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002797/* Add the absolute values of two long integers. */
2798
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002799static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002800x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2803 PyLongObject *z;
2804 Py_ssize_t i;
2805 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 /* Ensure a is the larger of the two: */
2808 if (size_a < size_b) {
2809 { PyLongObject *temp = a; a = b; b = temp; }
2810 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002811 size_a = size_b;
2812 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 }
2814 z = _PyLong_New(size_a+1);
2815 if (z == NULL)
2816 return NULL;
2817 for (i = 0; i < size_b; ++i) {
2818 carry += a->ob_digit[i] + b->ob_digit[i];
2819 z->ob_digit[i] = carry & PyLong_MASK;
2820 carry >>= PyLong_SHIFT;
2821 }
2822 for (; i < size_a; ++i) {
2823 carry += a->ob_digit[i];
2824 z->ob_digit[i] = carry & PyLong_MASK;
2825 carry >>= PyLong_SHIFT;
2826 }
2827 z->ob_digit[i] = carry;
2828 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002829}
2830
2831/* Subtract the absolute values of two integers. */
2832
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002833static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002834x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2837 PyLongObject *z;
2838 Py_ssize_t i;
2839 int sign = 1;
2840 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 /* Ensure a is the larger of the two: */
2843 if (size_a < size_b) {
2844 sign = -1;
2845 { PyLongObject *temp = a; a = b; b = temp; }
2846 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002847 size_a = size_b;
2848 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 }
2850 else if (size_a == size_b) {
2851 /* Find highest digit where a and b differ: */
2852 i = size_a;
2853 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2854 ;
2855 if (i < 0)
2856 return (PyLongObject *)PyLong_FromLong(0);
2857 if (a->ob_digit[i] < b->ob_digit[i]) {
2858 sign = -1;
2859 { PyLongObject *temp = a; a = b; b = temp; }
2860 }
2861 size_a = size_b = i+1;
2862 }
2863 z = _PyLong_New(size_a);
2864 if (z == NULL)
2865 return NULL;
2866 for (i = 0; i < size_b; ++i) {
2867 /* The following assumes unsigned arithmetic
2868 works module 2**N for some N>PyLong_SHIFT. */
2869 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2870 z->ob_digit[i] = borrow & PyLong_MASK;
2871 borrow >>= PyLong_SHIFT;
2872 borrow &= 1; /* Keep only one sign bit */
2873 }
2874 for (; i < size_a; ++i) {
2875 borrow = a->ob_digit[i] - borrow;
2876 z->ob_digit[i] = borrow & PyLong_MASK;
2877 borrow >>= PyLong_SHIFT;
2878 borrow &= 1; /* Keep only one sign bit */
2879 }
2880 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002881 if (sign < 0) {
2882 _PyLong_Negate(&z);
2883 if (z == NULL)
2884 return NULL;
2885 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002887}
2888
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002889static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002890long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2897 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2898 MEDIUM_VALUE(b));
2899 return result;
2900 }
2901 if (Py_SIZE(a) < 0) {
2902 if (Py_SIZE(b) < 0) {
2903 z = x_add(a, b);
2904 if (z != NULL && Py_SIZE(z) != 0)
2905 Py_SIZE(z) = -(Py_SIZE(z));
2906 }
2907 else
2908 z = x_sub(b, a);
2909 }
2910 else {
2911 if (Py_SIZE(b) < 0)
2912 z = x_sub(a, b);
2913 else
2914 z = x_add(a, b);
2915 }
2916 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002917}
2918
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002919static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002920long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2927 PyObject* r;
2928 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2929 return r;
2930 }
2931 if (Py_SIZE(a) < 0) {
2932 if (Py_SIZE(b) < 0)
2933 z = x_sub(a, b);
2934 else
2935 z = x_add(a, b);
2936 if (z != NULL && Py_SIZE(z) != 0)
2937 Py_SIZE(z) = -(Py_SIZE(z));
2938 }
2939 else {
2940 if (Py_SIZE(b) < 0)
2941 z = x_add(a, b);
2942 else
2943 z = x_sub(a, b);
2944 }
2945 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002946}
2947
Tim Peters5af4e6c2002-08-12 02:31:19 +00002948/* Grade school multiplication, ignoring the signs.
2949 * Returns the absolute value of the product, or NULL if error.
2950 */
2951static PyLongObject *
2952x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 PyLongObject *z;
2955 Py_ssize_t size_a = ABS(Py_SIZE(a));
2956 Py_ssize_t size_b = ABS(Py_SIZE(b));
2957 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 z = _PyLong_New(size_a + size_b);
2960 if (z == NULL)
2961 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2964 if (a == b) {
2965 /* Efficient squaring per HAC, Algorithm 14.16:
2966 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2967 * Gives slightly less than a 2x speedup when a == b,
2968 * via exploiting that each entry in the multiplication
2969 * pyramid appears twice (except for the size_a squares).
2970 */
2971 for (i = 0; i < size_a; ++i) {
2972 twodigits carry;
2973 twodigits f = a->ob_digit[i];
2974 digit *pz = z->ob_digit + (i << 1);
2975 digit *pa = a->ob_digit + i + 1;
2976 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002979 Py_DECREF(z);
2980 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002981 });
Tim Peters0973b992004-08-29 22:16:50 +00002982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 carry = *pz + f * f;
2984 *pz++ = (digit)(carry & PyLong_MASK);
2985 carry >>= PyLong_SHIFT;
2986 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 /* Now f is added in twice in each column of the
2989 * pyramid it appears. Same as adding f<<1 once.
2990 */
2991 f <<= 1;
2992 while (pa < paend) {
2993 carry += *pz + *pa++ * f;
2994 *pz++ = (digit)(carry & PyLong_MASK);
2995 carry >>= PyLong_SHIFT;
2996 assert(carry <= (PyLong_MASK << 1));
2997 }
2998 if (carry) {
2999 carry += *pz;
3000 *pz++ = (digit)(carry & PyLong_MASK);
3001 carry >>= PyLong_SHIFT;
3002 }
3003 if (carry)
3004 *pz += (digit)(carry & PyLong_MASK);
3005 assert((carry >> PyLong_SHIFT) == 0);
3006 }
3007 }
3008 else { /* a is not the same as b -- gradeschool long mult */
3009 for (i = 0; i < size_a; ++i) {
3010 twodigits carry = 0;
3011 twodigits f = a->ob_digit[i];
3012 digit *pz = z->ob_digit + i;
3013 digit *pb = b->ob_digit;
3014 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003017 Py_DECREF(z);
3018 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003019 });
Tim Peters0973b992004-08-29 22:16:50 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 while (pb < pbend) {
3022 carry += *pz + *pb++ * f;
3023 *pz++ = (digit)(carry & PyLong_MASK);
3024 carry >>= PyLong_SHIFT;
3025 assert(carry <= PyLong_MASK);
3026 }
3027 if (carry)
3028 *pz += (digit)(carry & PyLong_MASK);
3029 assert((carry >> PyLong_SHIFT) == 0);
3030 }
3031 }
3032 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003033}
3034
3035/* A helper for Karatsuba multiplication (k_mul).
3036 Takes a long "n" and an integer "size" representing the place to
3037 split, and sets low and high such that abs(n) == (high << size) + low,
3038 viewing the shift as being by digits. The sign bit is ignored, and
3039 the return values are >= 0.
3040 Returns 0 on success, -1 on failure.
3041*/
3042static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003043kmul_split(PyLongObject *n,
3044 Py_ssize_t size,
3045 PyLongObject **high,
3046 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 PyLongObject *hi, *lo;
3049 Py_ssize_t size_lo, size_hi;
3050 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003051
Victor Stinner640c35c2013-06-04 23:14:37 +02003052 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 if ((hi = _PyLong_New(size_hi)) == NULL)
3056 return -1;
3057 if ((lo = _PyLong_New(size_lo)) == NULL) {
3058 Py_DECREF(hi);
3059 return -1;
3060 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3063 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 *high = long_normalize(hi);
3066 *low = long_normalize(lo);
3067 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003068}
3069
Tim Peters60004642002-08-12 22:01:34 +00003070static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3071
Tim Peters5af4e6c2002-08-12 02:31:19 +00003072/* Karatsuba multiplication. Ignores the input signs, and returns the
3073 * absolute value of the product (or NULL if error).
3074 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3075 */
3076static PyLongObject *
3077k_mul(PyLongObject *a, PyLongObject *b)
3078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 Py_ssize_t asize = ABS(Py_SIZE(a));
3080 Py_ssize_t bsize = ABS(Py_SIZE(b));
3081 PyLongObject *ah = NULL;
3082 PyLongObject *al = NULL;
3083 PyLongObject *bh = NULL;
3084 PyLongObject *bl = NULL;
3085 PyLongObject *ret = NULL;
3086 PyLongObject *t1, *t2, *t3;
3087 Py_ssize_t shift; /* the number of digits we split off */
3088 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3091 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3092 * Then the original product is
3093 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3094 * By picking X to be a power of 2, "*X" is just shifting, and it's
3095 * been reduced to 3 multiplies on numbers half the size.
3096 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 /* We want to split based on the larger number; fiddle so that b
3099 * is largest.
3100 */
3101 if (asize > bsize) {
3102 t1 = a;
3103 a = b;
3104 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 i = asize;
3107 asize = bsize;
3108 bsize = i;
3109 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 /* Use gradeschool math when either number is too small. */
3112 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3113 if (asize <= i) {
3114 if (asize == 0)
3115 return (PyLongObject *)PyLong_FromLong(0);
3116 else
3117 return x_mul(a, b);
3118 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* If a is small compared to b, splitting on b gives a degenerate
3121 * case with ah==0, and Karatsuba may be (even much) less efficient
3122 * than "grade school" then. However, we can still win, by viewing
3123 * b as a string of "big digits", each of width a->ob_size. That
3124 * leads to a sequence of balanced calls to k_mul.
3125 */
3126 if (2 * asize <= bsize)
3127 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 /* Split a & b into hi & lo pieces. */
3130 shift = bsize >> 1;
3131 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3132 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 if (a == b) {
3135 bh = ah;
3136 bl = al;
3137 Py_INCREF(bh);
3138 Py_INCREF(bl);
3139 }
3140 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 /* The plan:
3143 * 1. Allocate result space (asize + bsize digits: that's always
3144 * enough).
3145 * 2. Compute ah*bh, and copy into result at 2*shift.
3146 * 3. Compute al*bl, and copy into result at 0. Note that this
3147 * can't overlap with #2.
3148 * 4. Subtract al*bl from the result, starting at shift. This may
3149 * underflow (borrow out of the high digit), but we don't care:
3150 * we're effectively doing unsigned arithmetic mod
3151 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3152 * borrows and carries out of the high digit can be ignored.
3153 * 5. Subtract ah*bh from the result, starting at shift.
3154 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3155 * at shift.
3156 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 /* 1. Allocate result space. */
3159 ret = _PyLong_New(asize + bsize);
3160 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003161#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* Fill with trash, to catch reference to uninitialized digits. */
3163 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003164#endif
Tim Peters44121a62002-08-12 06:17:58 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3167 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3168 assert(Py_SIZE(t1) >= 0);
3169 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3170 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3171 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 /* Zero-out the digits higher than the ah*bh copy. */
3174 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3175 if (i)
3176 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3177 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 /* 3. t2 <- al*bl, and copy into the low digits. */
3180 if ((t2 = k_mul(al, bl)) == NULL) {
3181 Py_DECREF(t1);
3182 goto fail;
3183 }
3184 assert(Py_SIZE(t2) >= 0);
3185 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3186 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 /* Zero out remaining digits. */
3189 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3190 if (i)
3191 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3194 * because it's fresher in cache.
3195 */
3196 i = Py_SIZE(ret) - shift; /* # digits after shift */
3197 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3198 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3201 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3204 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3205 Py_DECREF(ah);
3206 Py_DECREF(al);
3207 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 if (a == b) {
3210 t2 = t1;
3211 Py_INCREF(t2);
3212 }
3213 else if ((t2 = x_add(bh, bl)) == NULL) {
3214 Py_DECREF(t1);
3215 goto fail;
3216 }
3217 Py_DECREF(bh);
3218 Py_DECREF(bl);
3219 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 t3 = k_mul(t1, t2);
3222 Py_DECREF(t1);
3223 Py_DECREF(t2);
3224 if (t3 == NULL) goto fail;
3225 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 /* Add t3. It's not obvious why we can't run out of room here.
3228 * See the (*) comment after this function.
3229 */
3230 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3231 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003234
Mark Dickinson22b20182010-05-10 21:27:53 +00003235 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 Py_XDECREF(ret);
3237 Py_XDECREF(ah);
3238 Py_XDECREF(al);
3239 Py_XDECREF(bh);
3240 Py_XDECREF(bl);
3241 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003242}
3243
Tim Petersd6974a52002-08-13 20:37:51 +00003244/* (*) Why adding t3 can't "run out of room" above.
3245
Tim Petersab86c2b2002-08-15 20:06:00 +00003246Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3247to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003248
Tim Petersab86c2b2002-08-15 20:06:00 +000032491. For any integer i, i = c(i/2) + f(i/2). In particular,
3250 bsize = c(bsize/2) + f(bsize/2).
32512. shift = f(bsize/2)
32523. asize <= bsize
32534. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3254 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003255
Tim Petersab86c2b2002-08-15 20:06:00 +00003256We allocated asize + bsize result digits, and add t3 into them at an offset
3257of shift. This leaves asize+bsize-shift allocated digit positions for t3
3258to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3259asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003260
Tim Petersab86c2b2002-08-15 20:06:00 +00003261bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3262at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003263
Tim Petersab86c2b2002-08-15 20:06:00 +00003264If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3265digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3266most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003267
Tim Petersab86c2b2002-08-15 20:06:00 +00003268The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003269
Tim Petersab86c2b2002-08-15 20:06:00 +00003270 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003271
Tim Petersab86c2b2002-08-15 20:06:00 +00003272and we have asize + c(bsize/2) available digit positions. We need to show
3273this is always enough. An instance of c(bsize/2) cancels out in both, so
3274the question reduces to whether asize digits is enough to hold
3275(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3276then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3277asize 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 +00003278digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003279asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003280c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3281is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3282bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003283
Tim Peters48d52c02002-08-14 17:07:32 +00003284Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3285clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3286ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003287*/
3288
Tim Peters60004642002-08-12 22:01:34 +00003289/* b has at least twice the digits of a, and a is big enough that Karatsuba
3290 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3291 * of slices, each with a->ob_size digits, and multiply the slices by a,
3292 * one at a time. This gives k_mul balanced inputs to work with, and is
3293 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003294 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003295 * single-width slice overlap between successive partial sums).
3296 */
3297static PyLongObject *
3298k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 const Py_ssize_t asize = ABS(Py_SIZE(a));
3301 Py_ssize_t bsize = ABS(Py_SIZE(b));
3302 Py_ssize_t nbdone; /* # of b digits already multiplied */
3303 PyLongObject *ret;
3304 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 assert(asize > KARATSUBA_CUTOFF);
3307 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 /* Allocate result space, and zero it out. */
3310 ret = _PyLong_New(asize + bsize);
3311 if (ret == NULL)
3312 return NULL;
3313 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 /* Successive slices of b are copied into bslice. */
3316 bslice = _PyLong_New(asize);
3317 if (bslice == NULL)
3318 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 nbdone = 0;
3321 while (bsize > 0) {
3322 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003323 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 /* Multiply the next slice of b by a. */
3326 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3327 nbtouse * sizeof(digit));
3328 Py_SIZE(bslice) = nbtouse;
3329 product = k_mul(a, bslice);
3330 if (product == NULL)
3331 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 /* Add into result. */
3334 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3335 product->ob_digit, Py_SIZE(product));
3336 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 bsize -= nbtouse;
3339 nbdone += nbtouse;
3340 }
Tim Peters60004642002-08-12 22:01:34 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 Py_DECREF(bslice);
3343 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003344
Mark Dickinson22b20182010-05-10 21:27:53 +00003345 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 Py_DECREF(ret);
3347 Py_XDECREF(bslice);
3348 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003349}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003350
3351static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003352long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 /* fast path for single-digit multiplication */
3359 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3360 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003361#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003363#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* if we don't have long long then we're almost certainly
3365 using 15-bit digits, so v will fit in a long. In the
3366 unlikely event that we're using 30-bit digits on a platform
3367 without long long, a large v will just cause us to fall
3368 through to the general multiplication code below. */
3369 if (v >= LONG_MIN && v <= LONG_MAX)
3370 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003371#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 z = k_mul(a, b);
3375 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003376 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3377 _PyLong_Negate(&z);
3378 if (z == NULL)
3379 return NULL;
3380 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003382}
3383
Guido van Rossume32e0141992-01-19 16:31:05 +00003384/* The / and % operators are now defined in terms of divmod().
3385 The expression a mod b has the value a - b*floor(a/b).
3386 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003387 |a| by |b|, with the sign of a. This is also expressed
3388 as a - b*trunc(a/b), if trunc truncates towards zero.
3389 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 a b a rem b a mod b
3391 13 10 3 3
3392 -13 10 -3 7
3393 13 -10 3 -7
3394 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003395 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003396 have different signs. We then subtract one from the 'div'
3397 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003398
Tim Peters47e52ee2004-08-30 02:44:38 +00003399/* Compute
3400 * *pdiv, *pmod = divmod(v, w)
3401 * NULL can be passed for pdiv or pmod, in which case that part of
3402 * the result is simply thrown away. The caller owns a reference to
3403 * each of these it requests (does not pass NULL for).
3404 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003405static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 if (long_divrem(v, w, &div, &mod) < 0)
3412 return -1;
3413 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3414 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3415 PyLongObject *temp;
3416 PyLongObject *one;
3417 temp = (PyLongObject *) long_add(mod, w);
3418 Py_DECREF(mod);
3419 mod = temp;
3420 if (mod == NULL) {
3421 Py_DECREF(div);
3422 return -1;
3423 }
3424 one = (PyLongObject *) PyLong_FromLong(1L);
3425 if (one == NULL ||
3426 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3427 Py_DECREF(mod);
3428 Py_DECREF(div);
3429 Py_XDECREF(one);
3430 return -1;
3431 }
3432 Py_DECREF(one);
3433 Py_DECREF(div);
3434 div = temp;
3435 }
3436 if (pdiv != NULL)
3437 *pdiv = div;
3438 else
3439 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 if (pmod != NULL)
3442 *pmod = mod;
3443 else
3444 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003447}
3448
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003449static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003450long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 CHECK_BINOP(a, b);
3455 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3456 div = NULL;
3457 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003458}
3459
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003460/* PyLong/PyLong -> float, with correctly rounded result. */
3461
3462#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3463#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3464
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003465static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003466long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 PyLongObject *a, *b, *x;
3469 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3470 digit mask, low;
3471 int inexact, negate, a_is_small, b_is_small;
3472 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 CHECK_BINOP(v, w);
3475 a = (PyLongObject *)v;
3476 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 /*
3479 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3482 1. choose a suitable integer 'shift'
3483 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3484 3. adjust x for correct rounding
3485 4. convert x to a double dx with the same value
3486 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3491 returns either 0.0 or -0.0, depending on the sign of b. For a and
3492 b both nonzero, ignore signs of a and b, and add the sign back in
3493 at the end. Now write a_bits and b_bits for the bit lengths of a
3494 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3495 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3500 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3501 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3502 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 1. The integer 'shift' is chosen so that x has the right number of
3507 bits for a double, plus two or three extra bits that will be used
3508 in the rounding decisions. Writing a_bits and b_bits for the
3509 number of significant bits in a and b respectively, a
3510 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 This is fine in the usual case, but if a/b is smaller than the
3515 smallest normal float then it can lead to double rounding on an
3516 IEEE 754 platform, giving incorrectly rounded results. So we
3517 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 2. The quantity x is computed by first shifting a (left -shift bits
3522 if shift <= 0, right shift bits if shift > 0) and then dividing by
3523 b. For both the shift and the division, we keep track of whether
3524 the result is inexact, in a flag 'inexact'; this information is
3525 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 With the choice of shift above, together with our assumption that
3528 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3529 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3532 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 For float representability, we need x/2**extra_bits <
3537 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3538 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 To round, we just modify the bottom digit of x in-place; this can
3543 end up giving a digit with value > PyLONG_MASK, but that's not a
3544 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 With the original choices for shift above, extra_bits will always
3547 be 2 or 3. Then rounding under the round-half-to-even rule, we
3548 round up iff the most significant of the extra bits is 1, and
3549 either: (a) the computation of x in step 2 had an inexact result,
3550 or (b) at least one other of the extra bits is 1, or (c) the least
3551 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 4. Conversion to a double is straightforward; all floating-point
3554 operations involved in the conversion are exact, so there's no
3555 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3558 The result will always be exactly representable as a double, except
3559 in the case that it overflows. To avoid dependence on the exact
3560 behaviour of ldexp on overflow, we check for overflow before
3561 applying ldexp. The result of ldexp is adjusted for sign before
3562 returning.
3563 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 /* Reduce to case where a and b are both positive. */
3566 a_size = ABS(Py_SIZE(a));
3567 b_size = ABS(Py_SIZE(b));
3568 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3569 if (b_size == 0) {
3570 PyErr_SetString(PyExc_ZeroDivisionError,
3571 "division by zero");
3572 goto error;
3573 }
3574 if (a_size == 0)
3575 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 /* Fast path for a and b small (exactly representable in a double).
3578 Relies on floating-point division being correctly rounded; results
3579 may be subject to double rounding on x86 machines that operate with
3580 the x87 FPU set to 64-bit precision. */
3581 a_is_small = a_size <= MANT_DIG_DIGITS ||
3582 (a_size == MANT_DIG_DIGITS+1 &&
3583 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3584 b_is_small = b_size <= MANT_DIG_DIGITS ||
3585 (b_size == MANT_DIG_DIGITS+1 &&
3586 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3587 if (a_is_small && b_is_small) {
3588 double da, db;
3589 da = a->ob_digit[--a_size];
3590 while (a_size > 0)
3591 da = da * PyLong_BASE + a->ob_digit[--a_size];
3592 db = b->ob_digit[--b_size];
3593 while (b_size > 0)
3594 db = db * PyLong_BASE + b->ob_digit[--b_size];
3595 result = da / db;
3596 goto success;
3597 }
Tim Peterse2a60002001-09-04 06:17:36 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 /* Catch obvious cases of underflow and overflow */
3600 diff = a_size - b_size;
3601 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3602 /* Extreme overflow */
3603 goto overflow;
3604 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3605 /* Extreme underflow */
3606 goto underflow_or_zero;
3607 /* Next line is now safe from overflowing a Py_ssize_t */
3608 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3609 bits_in_digit(b->ob_digit[b_size - 1]);
3610 /* Now diff = a_bits - b_bits. */
3611 if (diff > DBL_MAX_EXP)
3612 goto overflow;
3613 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3614 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003617 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 /* x = abs(a * 2**-shift) */
3622 if (shift <= 0) {
3623 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3624 digit rem;
3625 /* x = a << -shift */
3626 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3627 /* In practice, it's probably impossible to end up
3628 here. Both a and b would have to be enormous,
3629 using close to SIZE_T_MAX bytes of memory each. */
3630 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003631 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 goto error;
3633 }
3634 x = _PyLong_New(a_size + shift_digits + 1);
3635 if (x == NULL)
3636 goto error;
3637 for (i = 0; i < shift_digits; i++)
3638 x->ob_digit[i] = 0;
3639 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3640 a_size, -shift % PyLong_SHIFT);
3641 x->ob_digit[a_size + shift_digits] = rem;
3642 }
3643 else {
3644 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3645 digit rem;
3646 /* x = a >> shift */
3647 assert(a_size >= shift_digits);
3648 x = _PyLong_New(a_size - shift_digits);
3649 if (x == NULL)
3650 goto error;
3651 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3652 a_size - shift_digits, shift % PyLong_SHIFT);
3653 /* set inexact if any of the bits shifted out is nonzero */
3654 if (rem)
3655 inexact = 1;
3656 while (!inexact && shift_digits > 0)
3657 if (a->ob_digit[--shift_digits])
3658 inexact = 1;
3659 }
3660 long_normalize(x);
3661 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3664 reference to x, so it's safe to modify it in-place. */
3665 if (b_size == 1) {
3666 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3667 b->ob_digit[0]);
3668 long_normalize(x);
3669 if (rem)
3670 inexact = 1;
3671 }
3672 else {
3673 PyLongObject *div, *rem;
3674 div = x_divrem(x, b, &rem);
3675 Py_DECREF(x);
3676 x = div;
3677 if (x == NULL)
3678 goto error;
3679 if (Py_SIZE(rem))
3680 inexact = 1;
3681 Py_DECREF(rem);
3682 }
3683 x_size = ABS(Py_SIZE(x));
3684 assert(x_size > 0); /* result of division is never zero */
3685 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003687 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003688 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 /* Round by directly modifying the low digit of x. */
3692 mask = (digit)1 << (extra_bits - 1);
3693 low = x->ob_digit[0] | inexact;
3694 if (low & mask && low & (3*mask-1))
3695 low += mask;
3696 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 /* Convert x to a double dx; the conversion is exact. */
3699 dx = x->ob_digit[--x_size];
3700 while (x_size > 0)
3701 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3702 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 /* Check whether ldexp result will overflow a double. */
3705 if (shift + x_bits >= DBL_MAX_EXP &&
3706 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3707 goto overflow;
3708 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003709
3710 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003712
3713 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003715
3716 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003717 PyErr_SetString(PyExc_OverflowError,
3718 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003719 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003721}
3722
3723static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003724long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 CHECK_BINOP(a, b);
3729
3730 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3731 mod = NULL;
3732 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003733}
3734
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003735static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003736long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 PyLongObject *div, *mod;
3739 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3744 return NULL;
3745 }
3746 z = PyTuple_New(2);
3747 if (z != NULL) {
3748 PyTuple_SetItem(z, 0, (PyObject *) div);
3749 PyTuple_SetItem(z, 1, (PyObject *) mod);
3750 }
3751 else {
3752 Py_DECREF(div);
3753 Py_DECREF(mod);
3754 }
3755 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003756}
3757
Tim Peters47e52ee2004-08-30 02:44:38 +00003758/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003759static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003760long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3763 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 PyLongObject *z = NULL; /* accumulated result */
3766 Py_ssize_t i, j, k; /* counters */
3767 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 /* 5-ary values. If the exponent is large enough, table is
3770 * precomputed so that table[i] == a**i % c for i in range(32).
3771 */
3772 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3773 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 /* a, b, c = v, w, x */
3776 CHECK_BINOP(v, w);
3777 a = (PyLongObject*)v; Py_INCREF(a);
3778 b = (PyLongObject*)w; Py_INCREF(b);
3779 if (PyLong_Check(x)) {
3780 c = (PyLongObject *)x;
3781 Py_INCREF(x);
3782 }
3783 else if (x == Py_None)
3784 c = NULL;
3785 else {
3786 Py_DECREF(a);
3787 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003788 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 }
Tim Peters4c483c42001-09-05 06:24:58 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3792 if (c) {
3793 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003794 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 goto Error;
3796 }
3797 else {
3798 /* else return a float. This works because we know
3799 that this calls float_pow() which converts its
3800 arguments to double. */
3801 Py_DECREF(a);
3802 Py_DECREF(b);
3803 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3804 }
3805 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 if (c) {
3808 /* if modulus == 0:
3809 raise ValueError() */
3810 if (Py_SIZE(c) == 0) {
3811 PyErr_SetString(PyExc_ValueError,
3812 "pow() 3rd argument cannot be 0");
3813 goto Error;
3814 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 /* if modulus < 0:
3817 negativeOutput = True
3818 modulus = -modulus */
3819 if (Py_SIZE(c) < 0) {
3820 negativeOutput = 1;
3821 temp = (PyLongObject *)_PyLong_Copy(c);
3822 if (temp == NULL)
3823 goto Error;
3824 Py_DECREF(c);
3825 c = temp;
3826 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02003827 _PyLong_Negate(&c);
3828 if (c == NULL)
3829 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 /* if modulus == 1:
3833 return 0 */
3834 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3835 z = (PyLongObject *)PyLong_FromLong(0L);
3836 goto Done;
3837 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 /* if base < 0:
3840 base = base % modulus
3841 Having the base positive just makes things easier. */
3842 if (Py_SIZE(a) < 0) {
3843 if (l_divmod(a, c, NULL, &temp) < 0)
3844 goto Error;
3845 Py_DECREF(a);
3846 a = temp;
3847 temp = NULL;
3848 }
3849 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 /* At this point a, b, and c are guaranteed non-negative UNLESS
3852 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 z = (PyLongObject *)PyLong_FromLong(1L);
3855 if (z == NULL)
3856 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 /* Perform a modular reduction, X = X % c, but leave X alone if c
3859 * is NULL.
3860 */
3861#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003862 do { \
3863 if (c != NULL) { \
3864 if (l_divmod(X, c, NULL, &temp) < 0) \
3865 goto Error; \
3866 Py_XDECREF(X); \
3867 X = temp; \
3868 temp = NULL; \
3869 } \
3870 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003872 /* Multiply two values, then reduce the result:
3873 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003874#define MULT(X, Y, result) \
3875 do { \
3876 temp = (PyLongObject *)long_mul(X, Y); \
3877 if (temp == NULL) \
3878 goto Error; \
3879 Py_XDECREF(result); \
3880 result = temp; \
3881 temp = NULL; \
3882 REDUCE(result); \
3883 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003885 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3886 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3887 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3888 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3889 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003892 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003894 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 }
3896 }
3897 }
3898 else {
3899 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3900 Py_INCREF(z); /* still holds 1L */
3901 table[0] = z;
3902 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003903 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003905 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3906 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3909 const int index = (bi >> j) & 0x1f;
3910 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003911 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003913 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 }
3915 }
3916 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 if (negativeOutput && (Py_SIZE(z) != 0)) {
3919 temp = (PyLongObject *)long_sub(z, c);
3920 if (temp == NULL)
3921 goto Error;
3922 Py_DECREF(z);
3923 z = temp;
3924 temp = NULL;
3925 }
3926 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003927
Mark Dickinson22b20182010-05-10 21:27:53 +00003928 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02003929 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003931 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3933 for (i = 0; i < 32; ++i)
3934 Py_XDECREF(table[i]);
3935 }
3936 Py_DECREF(a);
3937 Py_DECREF(b);
3938 Py_XDECREF(c);
3939 Py_XDECREF(temp);
3940 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003941}
3942
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003943static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003944long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 /* Implement ~x as -(x+1) */
3947 PyLongObject *x;
3948 PyLongObject *w;
3949 if (ABS(Py_SIZE(v)) <=1)
3950 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3951 w = (PyLongObject *)PyLong_FromLong(1L);
3952 if (w == NULL)
3953 return NULL;
3954 x = (PyLongObject *) long_add(v, w);
3955 Py_DECREF(w);
3956 if (x == NULL)
3957 return NULL;
3958 Py_SIZE(x) = -(Py_SIZE(x));
3959 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003960}
3961
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003962static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003963long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 PyLongObject *z;
3966 if (ABS(Py_SIZE(v)) <= 1)
3967 return PyLong_FromLong(-MEDIUM_VALUE(v));
3968 z = (PyLongObject *)_PyLong_Copy(v);
3969 if (z != NULL)
3970 Py_SIZE(z) = -(Py_SIZE(v));
3971 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003972}
3973
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003974static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003975long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003977 if (Py_SIZE(v) < 0)
3978 return long_neg(v);
3979 else
3980 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003981}
3982
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003983static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003984long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003987}
3988
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003989static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003990long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003992 PyLongObject *z = NULL;
3993 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3994 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 if (Py_SIZE(a) < 0) {
3999 /* Right shifting negative numbers is harder */
4000 PyLongObject *a1, *a2;
4001 a1 = (PyLongObject *) long_invert(a);
4002 if (a1 == NULL)
4003 goto rshift_error;
4004 a2 = (PyLongObject *) long_rshift(a1, b);
4005 Py_DECREF(a1);
4006 if (a2 == NULL)
4007 goto rshift_error;
4008 z = (PyLongObject *) long_invert(a2);
4009 Py_DECREF(a2);
4010 }
4011 else {
4012 shiftby = PyLong_AsSsize_t((PyObject *)b);
4013 if (shiftby == -1L && PyErr_Occurred())
4014 goto rshift_error;
4015 if (shiftby < 0) {
4016 PyErr_SetString(PyExc_ValueError,
4017 "negative shift count");
4018 goto rshift_error;
4019 }
4020 wordshift = shiftby / PyLong_SHIFT;
4021 newsize = ABS(Py_SIZE(a)) - wordshift;
4022 if (newsize <= 0)
4023 return PyLong_FromLong(0);
4024 loshift = shiftby % PyLong_SHIFT;
4025 hishift = PyLong_SHIFT - loshift;
4026 lomask = ((digit)1 << hishift) - 1;
4027 himask = PyLong_MASK ^ lomask;
4028 z = _PyLong_New(newsize);
4029 if (z == NULL)
4030 goto rshift_error;
4031 if (Py_SIZE(a) < 0)
4032 Py_SIZE(z) = -(Py_SIZE(z));
4033 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4034 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4035 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004036 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 }
4038 z = long_normalize(z);
4039 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004040 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004042
Guido van Rossumc6913e71991-11-19 20:26:46 +00004043}
4044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004045static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004046long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 /* This version due to Tim Peters */
4049 PyLongObject *a = (PyLongObject*)v;
4050 PyLongObject *b = (PyLongObject*)w;
4051 PyLongObject *z = NULL;
4052 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4053 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 shiftby = PyLong_AsSsize_t((PyObject *)b);
4058 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004059 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004060 if (shiftby < 0) {
4061 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004062 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004063 }
4064 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4065 wordshift = shiftby / PyLong_SHIFT;
4066 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 oldsize = ABS(Py_SIZE(a));
4069 newsize = oldsize + wordshift;
4070 if (remshift)
4071 ++newsize;
4072 z = _PyLong_New(newsize);
4073 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004074 return NULL;
4075 if (Py_SIZE(a) < 0) {
4076 assert(Py_REFCNT(z) == 1);
4077 Py_SIZE(z) = -Py_SIZE(z);
4078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 for (i = 0; i < wordshift; i++)
4080 z->ob_digit[i] = 0;
4081 accum = 0;
4082 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4083 accum |= (twodigits)a->ob_digit[j] << remshift;
4084 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4085 accum >>= PyLong_SHIFT;
4086 }
4087 if (remshift)
4088 z->ob_digit[newsize-1] = (digit)accum;
4089 else
4090 assert(!accum);
4091 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004093}
4094
Mark Dickinson27a87a22009-10-25 20:43:34 +00004095/* Compute two's complement of digit vector a[0:m], writing result to
4096 z[0:m]. The digit vector a need not be normalized, but should not
4097 be entirely zero. a and z may point to the same digit vector. */
4098
4099static void
4100v_complement(digit *z, digit *a, Py_ssize_t m)
4101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 Py_ssize_t i;
4103 digit carry = 1;
4104 for (i = 0; i < m; ++i) {
4105 carry += a[i] ^ PyLong_MASK;
4106 z[i] = carry & PyLong_MASK;
4107 carry >>= PyLong_SHIFT;
4108 }
4109 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004110}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004111
4112/* Bitwise and/xor/or operations */
4113
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004114static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004115long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004116 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004117 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 int nega, negb, negz;
4120 Py_ssize_t size_a, size_b, size_z, i;
4121 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 /* Bitwise operations for negative numbers operate as though
4124 on a two's complement representation. So convert arguments
4125 from sign-magnitude to two's complement, and convert the
4126 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 /* If a is negative, replace it by its two's complement. */
4129 size_a = ABS(Py_SIZE(a));
4130 nega = Py_SIZE(a) < 0;
4131 if (nega) {
4132 z = _PyLong_New(size_a);
4133 if (z == NULL)
4134 return NULL;
4135 v_complement(z->ob_digit, a->ob_digit, size_a);
4136 a = z;
4137 }
4138 else
4139 /* Keep reference count consistent. */
4140 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 /* Same for b. */
4143 size_b = ABS(Py_SIZE(b));
4144 negb = Py_SIZE(b) < 0;
4145 if (negb) {
4146 z = _PyLong_New(size_b);
4147 if (z == NULL) {
4148 Py_DECREF(a);
4149 return NULL;
4150 }
4151 v_complement(z->ob_digit, b->ob_digit, size_b);
4152 b = z;
4153 }
4154 else
4155 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 /* Swap a and b if necessary to ensure size_a >= size_b. */
4158 if (size_a < size_b) {
4159 z = a; a = b; b = z;
4160 size_z = size_a; size_a = size_b; size_b = size_z;
4161 negz = nega; nega = negb; negb = negz;
4162 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004164 /* JRH: The original logic here was to allocate the result value (z)
4165 as the longer of the two operands. However, there are some cases
4166 where the result is guaranteed to be shorter than that: AND of two
4167 positives, OR of two negatives: use the shorter number. AND with
4168 mixed signs: use the positive number. OR with mixed signs: use the
4169 negative number.
4170 */
4171 switch (op) {
4172 case '^':
4173 negz = nega ^ negb;
4174 size_z = size_a;
4175 break;
4176 case '&':
4177 negz = nega & negb;
4178 size_z = negb ? size_a : size_b;
4179 break;
4180 case '|':
4181 negz = nega | negb;
4182 size_z = negb ? size_b : size_a;
4183 break;
4184 default:
4185 PyErr_BadArgument();
4186 return NULL;
4187 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 /* We allow an extra digit if z is negative, to make sure that
4190 the final two's complement of z doesn't overflow. */
4191 z = _PyLong_New(size_z + negz);
4192 if (z == NULL) {
4193 Py_DECREF(a);
4194 Py_DECREF(b);
4195 return NULL;
4196 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 /* Compute digits for overlap of a and b. */
4199 switch(op) {
4200 case '&':
4201 for (i = 0; i < size_b; ++i)
4202 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4203 break;
4204 case '|':
4205 for (i = 0; i < size_b; ++i)
4206 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4207 break;
4208 case '^':
4209 for (i = 0; i < size_b; ++i)
4210 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4211 break;
4212 default:
4213 PyErr_BadArgument();
4214 return NULL;
4215 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 /* Copy any remaining digits of a, inverting if necessary. */
4218 if (op == '^' && negb)
4219 for (; i < size_z; ++i)
4220 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4221 else if (i < size_z)
4222 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4223 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 /* Complement result if negative. */
4226 if (negz) {
4227 Py_SIZE(z) = -(Py_SIZE(z));
4228 z->ob_digit[size_z] = PyLong_MASK;
4229 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4230 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 Py_DECREF(a);
4233 Py_DECREF(b);
4234 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004235}
4236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004237static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004238long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 PyObject *c;
4241 CHECK_BINOP(a, b);
4242 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4243 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004244}
4245
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004246static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004247long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004249 PyObject *c;
4250 CHECK_BINOP(a, b);
4251 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4252 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004253}
4254
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004255static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004256long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 PyObject *c;
4259 CHECK_BINOP(a, b);
4260 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4261 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004262}
4263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004264static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004265long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 if (PyLong_CheckExact(v))
4268 Py_INCREF(v);
4269 else
4270 v = _PyLong_Copy((PyLongObject *)v);
4271 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004272}
4273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004274static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004275long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004277 double result;
4278 result = PyLong_AsDouble(v);
4279 if (result == -1.0 && PyErr_Occurred())
4280 return NULL;
4281 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004282}
4283
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004284static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004285long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004286
Tim Peters6d6c1a32001-08-02 04:15:00 +00004287static PyObject *
4288long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4289{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004290 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004291 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004292 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 if (type != &PyLong_Type)
4295 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004296 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4297 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004299 if (x == NULL) {
4300 if (obase != NULL) {
4301 PyErr_SetString(PyExc_TypeError,
4302 "int() missing string argument");
4303 return NULL;
4304 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004306 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004307 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004309
Gregory P. Smitha689e522012-12-25 22:38:32 -08004310 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004311 if (base == -1 && PyErr_Occurred())
4312 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004313 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004314 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004315 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004316 return NULL;
4317 }
4318
4319 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004320 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4322 /* Since PyLong_FromString doesn't have a length parameter,
4323 * check here for possible NULs in the string. */
4324 char *string;
4325 Py_ssize_t size = Py_SIZE(x);
4326 if (PyByteArray_Check(x))
4327 string = PyByteArray_AS_STRING(x);
4328 else
4329 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004330 if (strlen(string) != (size_t)size || !size) {
4331 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 x is a bytes or buffer, *and* a base is given. */
4333 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004334 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004335 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 return NULL;
4337 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004338 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 }
4340 else {
4341 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004342 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004343 return NULL;
4344 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004345}
4346
Guido van Rossumbef14172001-08-29 15:47:46 +00004347/* Wimpy, slow approach to tp_new calls for subtypes of long:
4348 first create a regular long from whatever arguments we got,
4349 then allocate a subtype instance and initialize it from
4350 the regular long. The regular long is then thrown away.
4351*/
4352static PyObject *
4353long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 PyLongObject *tmp, *newobj;
4356 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 assert(PyType_IsSubtype(type, &PyLong_Type));
4359 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4360 if (tmp == NULL)
4361 return NULL;
4362 assert(PyLong_CheckExact(tmp));
4363 n = Py_SIZE(tmp);
4364 if (n < 0)
4365 n = -n;
4366 newobj = (PyLongObject *)type->tp_alloc(type, n);
4367 if (newobj == NULL) {
4368 Py_DECREF(tmp);
4369 return NULL;
4370 }
4371 assert(PyLong_Check(newobj));
4372 Py_SIZE(newobj) = Py_SIZE(tmp);
4373 for (i = 0; i < n; i++)
4374 newobj->ob_digit[i] = tmp->ob_digit[i];
4375 Py_DECREF(tmp);
4376 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004377}
4378
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004379static PyObject *
4380long_getnewargs(PyLongObject *v)
4381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004383}
4384
Guido van Rossumb43daf72007-08-01 18:08:08 +00004385static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004386long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004388}
4389
4390static PyObject *
4391long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004393}
4394
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004395static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004396long__format__(PyObject *self, PyObject *args)
4397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004398 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004399 _PyUnicodeWriter writer;
4400 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4403 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004404
Victor Stinner8f674cc2013-04-17 23:02:17 +02004405 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004406 ret = _PyLong_FormatAdvancedWriter(
4407 &writer,
4408 self,
4409 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4410 if (ret == -1) {
4411 _PyUnicodeWriter_Dealloc(&writer);
4412 return NULL;
4413 }
4414 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004415}
4416
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004417/* Return a pair (q, r) such that a = b * q + r, and
4418 abs(r) <= abs(b)/2, with equality possible only if q is even.
4419 In other words, q == a / b, rounded to the nearest integer using
4420 round-half-to-even. */
4421
4422PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004423_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004424{
4425 PyLongObject *quo = NULL, *rem = NULL;
4426 PyObject *one = NULL, *twice_rem, *result, *temp;
4427 int cmp, quo_is_odd, quo_is_neg;
4428
4429 /* Equivalent Python code:
4430
4431 def divmod_near(a, b):
4432 q, r = divmod(a, b)
4433 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4434 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4435 # positive, 2 * r < b if b negative.
4436 greater_than_half = 2*r > b if b > 0 else 2*r < b
4437 exactly_half = 2*r == b
4438 if greater_than_half or exactly_half and q % 2 == 1:
4439 q += 1
4440 r -= b
4441 return q, r
4442
4443 */
4444 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4445 PyErr_SetString(PyExc_TypeError,
4446 "non-integer arguments in division");
4447 return NULL;
4448 }
4449
4450 /* Do a and b have different signs? If so, quotient is negative. */
4451 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4452
4453 one = PyLong_FromLong(1L);
4454 if (one == NULL)
4455 return NULL;
4456
4457 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4458 goto error;
4459
4460 /* compare twice the remainder with the divisor, to see
4461 if we need to adjust the quotient and remainder */
4462 twice_rem = long_lshift((PyObject *)rem, one);
4463 if (twice_rem == NULL)
4464 goto error;
4465 if (quo_is_neg) {
4466 temp = long_neg((PyLongObject*)twice_rem);
4467 Py_DECREF(twice_rem);
4468 twice_rem = temp;
4469 if (twice_rem == NULL)
4470 goto error;
4471 }
4472 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4473 Py_DECREF(twice_rem);
4474
4475 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4476 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4477 /* fix up quotient */
4478 if (quo_is_neg)
4479 temp = long_sub(quo, (PyLongObject *)one);
4480 else
4481 temp = long_add(quo, (PyLongObject *)one);
4482 Py_DECREF(quo);
4483 quo = (PyLongObject *)temp;
4484 if (quo == NULL)
4485 goto error;
4486 /* and remainder */
4487 if (quo_is_neg)
4488 temp = long_add(rem, (PyLongObject *)b);
4489 else
4490 temp = long_sub(rem, (PyLongObject *)b);
4491 Py_DECREF(rem);
4492 rem = (PyLongObject *)temp;
4493 if (rem == NULL)
4494 goto error;
4495 }
4496
4497 result = PyTuple_New(2);
4498 if (result == NULL)
4499 goto error;
4500
4501 /* PyTuple_SET_ITEM steals references */
4502 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4503 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4504 Py_DECREF(one);
4505 return result;
4506
4507 error:
4508 Py_XDECREF(quo);
4509 Py_XDECREF(rem);
4510 Py_XDECREF(one);
4511 return NULL;
4512}
4513
Eric Smith8c663262007-08-25 02:26:07 +00004514static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004515long_round(PyObject *self, PyObject *args)
4516{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004517 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004518
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004519 /* To round an integer m to the nearest 10**n (n positive), we make use of
4520 * the divmod_near operation, defined by:
4521 *
4522 * divmod_near(a, b) = (q, r)
4523 *
4524 * where q is the nearest integer to the quotient a / b (the
4525 * nearest even integer in the case of a tie) and r == a - q * b.
4526 * Hence q * b = a - r is the nearest multiple of b to a,
4527 * preferring even multiples in the case of a tie.
4528 *
4529 * So the nearest multiple of 10**n to m is:
4530 *
4531 * m - divmod_near(m, 10**n)[1].
4532 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4534 return NULL;
4535 if (o_ndigits == NULL)
4536 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004537
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004538 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 if (ndigits == NULL)
4540 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004541
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004542 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 if (Py_SIZE(ndigits) >= 0) {
4544 Py_DECREF(ndigits);
4545 return long_long(self);
4546 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004547
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004548 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4549 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004551 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004553 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004554
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004555 result = PyLong_FromLong(10L);
4556 if (result == NULL) {
4557 Py_DECREF(ndigits);
4558 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004560
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004561 temp = long_pow(result, ndigits, Py_None);
4562 Py_DECREF(ndigits);
4563 Py_DECREF(result);
4564 result = temp;
4565 if (result == NULL)
4566 return NULL;
4567
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004568 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004569 Py_DECREF(result);
4570 result = temp;
4571 if (result == NULL)
4572 return NULL;
4573
4574 temp = long_sub((PyLongObject *)self,
4575 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4576 Py_DECREF(result);
4577 result = temp;
4578
4579 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004580}
4581
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004582static PyObject *
4583long_sizeof(PyLongObject *v)
4584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4588 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004589}
4590
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004591static PyObject *
4592long_bit_length(PyLongObject *v)
4593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 PyLongObject *result, *x, *y;
4595 Py_ssize_t ndigits, msd_bits = 0;
4596 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 assert(v != NULL);
4599 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 ndigits = ABS(Py_SIZE(v));
4602 if (ndigits == 0)
4603 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 msd = v->ob_digit[ndigits-1];
4606 while (msd >= 32) {
4607 msd_bits += 6;
4608 msd >>= 6;
4609 }
4610 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4613 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 /* expression above may overflow; use Python integers instead */
4616 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4617 if (result == NULL)
4618 return NULL;
4619 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4620 if (x == NULL)
4621 goto error;
4622 y = (PyLongObject *)long_mul(result, x);
4623 Py_DECREF(x);
4624 if (y == NULL)
4625 goto error;
4626 Py_DECREF(result);
4627 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4630 if (x == NULL)
4631 goto error;
4632 y = (PyLongObject *)long_add(result, x);
4633 Py_DECREF(x);
4634 if (y == NULL)
4635 goto error;
4636 Py_DECREF(result);
4637 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004640
Mark Dickinson22b20182010-05-10 21:27:53 +00004641 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 Py_DECREF(result);
4643 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004644}
4645
4646PyDoc_STRVAR(long_bit_length_doc,
4647"int.bit_length() -> int\n\
4648\n\
4649Number of bits necessary to represent self in binary.\n\
4650>>> bin(37)\n\
4651'0b100101'\n\
4652>>> (37).bit_length()\n\
46536");
4654
Christian Heimes53876d92008-04-19 00:31:39 +00004655#if 0
4656static PyObject *
4657long_is_finite(PyObject *v)
4658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004660}
4661#endif
4662
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004663
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004664static PyObject *
4665long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 PyObject *byteorder_str;
4668 PyObject *is_signed_obj = NULL;
4669 Py_ssize_t length;
4670 int little_endian;
4671 int is_signed;
4672 PyObject *bytes;
4673 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4676 &length, &byteorder_str,
4677 &is_signed_obj))
4678 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 if (args != NULL && Py_SIZE(args) > 2) {
4681 PyErr_SetString(PyExc_TypeError,
4682 "'signed' is a keyword-only argument");
4683 return NULL;
4684 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4687 little_endian = 1;
4688 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4689 little_endian = 0;
4690 else {
4691 PyErr_SetString(PyExc_ValueError,
4692 "byteorder must be either 'little' or 'big'");
4693 return NULL;
4694 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 if (is_signed_obj != NULL) {
4697 int cmp = PyObject_IsTrue(is_signed_obj);
4698 if (cmp < 0)
4699 return NULL;
4700 is_signed = cmp ? 1 : 0;
4701 }
4702 else {
4703 /* If the signed argument was omitted, use False as the
4704 default. */
4705 is_signed = 0;
4706 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 if (length < 0) {
4709 PyErr_SetString(PyExc_ValueError,
4710 "length argument must be non-negative");
4711 return NULL;
4712 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 bytes = PyBytes_FromStringAndSize(NULL, length);
4715 if (bytes == NULL)
4716 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4719 length, little_endian, is_signed) < 0) {
4720 Py_DECREF(bytes);
4721 return NULL;
4722 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004725}
4726
Mark Dickinson078c2532010-01-30 18:06:17 +00004727PyDoc_STRVAR(long_to_bytes_doc,
4728"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004729\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004730Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004731\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004733raised if the integer is not representable with the given number of\n\
4734bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004735\n\
4736The byteorder argument determines the byte order used to represent the\n\
4737integer. If byteorder is 'big', the most significant byte is at the\n\
4738beginning of the byte array. If byteorder is 'little', the most\n\
4739significant byte is at the end of the byte array. To request the native\n\
4740byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4741\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004742The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004744is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004745
4746static PyObject *
4747long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 PyObject *byteorder_str;
4750 PyObject *is_signed_obj = NULL;
4751 int little_endian;
4752 int is_signed;
4753 PyObject *obj;
4754 PyObject *bytes;
4755 PyObject *long_obj;
4756 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4759 &obj, &byteorder_str,
4760 &is_signed_obj))
4761 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 if (args != NULL && Py_SIZE(args) > 2) {
4764 PyErr_SetString(PyExc_TypeError,
4765 "'signed' is a keyword-only argument");
4766 return NULL;
4767 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4770 little_endian = 1;
4771 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4772 little_endian = 0;
4773 else {
4774 PyErr_SetString(PyExc_ValueError,
4775 "byteorder must be either 'little' or 'big'");
4776 return NULL;
4777 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 if (is_signed_obj != NULL) {
4780 int cmp = PyObject_IsTrue(is_signed_obj);
4781 if (cmp < 0)
4782 return NULL;
4783 is_signed = cmp ? 1 : 0;
4784 }
4785 else {
4786 /* If the signed argument was omitted, use False as the
4787 default. */
4788 is_signed = 0;
4789 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 bytes = PyObject_Bytes(obj);
4792 if (bytes == NULL)
4793 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 long_obj = _PyLong_FromByteArray(
4796 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4797 little_endian, is_signed);
4798 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 /* If from_bytes() was used on subclass, allocate new subclass
4801 * instance, initialize it with decoded long value and return it.
4802 */
4803 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4804 PyLongObject *newobj;
4805 int i;
4806 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 newobj = (PyLongObject *)type->tp_alloc(type, n);
4809 if (newobj == NULL) {
4810 Py_DECREF(long_obj);
4811 return NULL;
4812 }
4813 assert(PyLong_Check(newobj));
4814 Py_SIZE(newobj) = Py_SIZE(long_obj);
4815 for (i = 0; i < n; i++) {
4816 newobj->ob_digit[i] =
4817 ((PyLongObject *)long_obj)->ob_digit[i];
4818 }
4819 Py_DECREF(long_obj);
4820 return (PyObject *)newobj;
4821 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004824}
4825
Mark Dickinson078c2532010-01-30 18:06:17 +00004826PyDoc_STRVAR(long_from_bytes_doc,
4827"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4828\n\
4829Return the integer represented by the given array of bytes.\n\
4830\n\
4831The bytes argument must either support the buffer protocol or be an\n\
4832iterable object producing bytes. Bytes and bytearray are examples of\n\
4833built-in objects that support the buffer protocol.\n\
4834\n\
4835The byteorder argument determines the byte order used to represent the\n\
4836integer. If byteorder is 'big', the most significant byte is at the\n\
4837beginning of the byte array. If byteorder is 'little', the most\n\
4838significant byte is at the end of the byte array. To request the native\n\
4839byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4840\n\
4841The signed keyword-only argument indicates whether two's complement is\n\
4842used to represent the integer.");
4843
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004844static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4846 "Returns self, the complex conjugate of any int."},
4847 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4848 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004849#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4851 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004852#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 {"to_bytes", (PyCFunction)long_to_bytes,
4854 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4855 {"from_bytes", (PyCFunction)long_from_bytes,
4856 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4857 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4858 "Truncating an Integral returns itself."},
4859 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4860 "Flooring an Integral returns itself."},
4861 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4862 "Ceiling of an Integral returns itself."},
4863 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4864 "Rounding an Integral returns itself.\n"
4865 "Rounding with an ndigits argument also returns an integer."},
4866 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4867 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4868 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4869 "Returns size in memory, in bytes"},
4870 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004871};
4872
Guido van Rossumb43daf72007-08-01 18:08:08 +00004873static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004874 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004875 (getter)long_long, (setter)NULL,
4876 "the real part of a complex number",
4877 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004878 {"imag",
4879 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004880 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004881 NULL},
4882 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004883 (getter)long_long, (setter)NULL,
4884 "the numerator of a rational number in lowest terms",
4885 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004886 {"denominator",
4887 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004888 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004889 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004890 {NULL} /* Sentinel */
4891};
4892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004893PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004894"int(x=0) -> integer\n\
4895int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004896\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004897Convert a number or string to an integer, or return 0 if no arguments\n\
4898are given. If x is a number, return x.__int__(). For floating point\n\
4899numbers, this truncates towards zero.\n\
4900\n\
4901If x is not a number or if base is given, then x must be a string,\n\
4902bytes, or bytearray instance representing an integer literal in the\n\
4903given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4904by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4905Base 0 means to interpret the base from the string as an integer literal.\n\
4906>>> int('0b100', base=0)\n\
49074");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004908
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004909static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004910 (binaryfunc)long_add, /*nb_add*/
4911 (binaryfunc)long_sub, /*nb_subtract*/
4912 (binaryfunc)long_mul, /*nb_multiply*/
4913 long_mod, /*nb_remainder*/
4914 long_divmod, /*nb_divmod*/
4915 long_pow, /*nb_power*/
4916 (unaryfunc)long_neg, /*nb_negative*/
4917 (unaryfunc)long_long, /*tp_positive*/
4918 (unaryfunc)long_abs, /*tp_absolute*/
4919 (inquiry)long_bool, /*tp_bool*/
4920 (unaryfunc)long_invert, /*nb_invert*/
4921 long_lshift, /*nb_lshift*/
4922 (binaryfunc)long_rshift, /*nb_rshift*/
4923 long_and, /*nb_and*/
4924 long_xor, /*nb_xor*/
4925 long_or, /*nb_or*/
4926 long_long, /*nb_int*/
4927 0, /*nb_reserved*/
4928 long_float, /*nb_float*/
4929 0, /* nb_inplace_add */
4930 0, /* nb_inplace_subtract */
4931 0, /* nb_inplace_multiply */
4932 0, /* nb_inplace_remainder */
4933 0, /* nb_inplace_power */
4934 0, /* nb_inplace_lshift */
4935 0, /* nb_inplace_rshift */
4936 0, /* nb_inplace_and */
4937 0, /* nb_inplace_xor */
4938 0, /* nb_inplace_or */
4939 long_div, /* nb_floor_divide */
4940 long_true_divide, /* nb_true_divide */
4941 0, /* nb_inplace_floor_divide */
4942 0, /* nb_inplace_true_divide */
4943 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004944};
4945
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004946PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4948 "int", /* tp_name */
4949 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4950 sizeof(digit), /* tp_itemsize */
4951 long_dealloc, /* tp_dealloc */
4952 0, /* tp_print */
4953 0, /* tp_getattr */
4954 0, /* tp_setattr */
4955 0, /* tp_reserved */
4956 long_to_decimal_string, /* tp_repr */
4957 &long_as_number, /* tp_as_number */
4958 0, /* tp_as_sequence */
4959 0, /* tp_as_mapping */
4960 (hashfunc)long_hash, /* tp_hash */
4961 0, /* tp_call */
4962 long_to_decimal_string, /* tp_str */
4963 PyObject_GenericGetAttr, /* tp_getattro */
4964 0, /* tp_setattro */
4965 0, /* tp_as_buffer */
4966 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4967 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4968 long_doc, /* tp_doc */
4969 0, /* tp_traverse */
4970 0, /* tp_clear */
4971 long_richcompare, /* tp_richcompare */
4972 0, /* tp_weaklistoffset */
4973 0, /* tp_iter */
4974 0, /* tp_iternext */
4975 long_methods, /* tp_methods */
4976 0, /* tp_members */
4977 long_getset, /* tp_getset */
4978 0, /* tp_base */
4979 0, /* tp_dict */
4980 0, /* tp_descr_get */
4981 0, /* tp_descr_set */
4982 0, /* tp_dictoffset */
4983 0, /* tp_init */
4984 0, /* tp_alloc */
4985 long_new, /* tp_new */
4986 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004987};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004988
Mark Dickinsonbd792642009-03-18 20:06:12 +00004989static PyTypeObject Int_InfoType;
4990
4991PyDoc_STRVAR(int_info__doc__,
4992"sys.int_info\n\
4993\n\
4994A struct sequence that holds information about Python's\n\
4995internal representation of integers. The attributes are read only.");
4996
4997static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004999 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005001};
5002
5003static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 "sys.int_info", /* name */
5005 int_info__doc__, /* doc */
5006 int_info_fields, /* fields */
5007 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005008};
5009
5010PyObject *
5011PyLong_GetInfo(void)
5012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 PyObject* int_info;
5014 int field = 0;
5015 int_info = PyStructSequence_New(&Int_InfoType);
5016 if (int_info == NULL)
5017 return NULL;
5018 PyStructSequence_SET_ITEM(int_info, field++,
5019 PyLong_FromLong(PyLong_SHIFT));
5020 PyStructSequence_SET_ITEM(int_info, field++,
5021 PyLong_FromLong(sizeof(digit)));
5022 if (PyErr_Occurred()) {
5023 Py_CLEAR(int_info);
5024 return NULL;
5025 }
5026 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005027}
5028
Guido van Rossumddefaf32007-01-14 03:31:43 +00005029int
5030_PyLong_Init(void)
5031{
5032#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005033 int ival, size;
5034 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5037 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5038 if (Py_TYPE(v) == &PyLong_Type) {
5039 /* The element is already initialized, most likely
5040 * the Python interpreter was initialized before.
5041 */
5042 Py_ssize_t refcnt;
5043 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5046 _Py_NewReference(op);
5047 /* _Py_NewReference sets the ref count to 1 but
5048 * the ref count might be larger. Set the refcnt
5049 * to the original refcnt + 1 */
5050 Py_REFCNT(op) = refcnt + 1;
5051 assert(Py_SIZE(op) == size);
5052 assert(v->ob_digit[0] == abs(ival));
5053 }
5054 else {
5055 PyObject_INIT(v, &PyLong_Type);
5056 }
5057 Py_SIZE(v) = size;
5058 v->ob_digit[0] = abs(ival);
5059 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005060#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005062 if (Int_InfoType.tp_name == NULL) {
5063 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5064 return 0;
5065 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005068}
5069
5070void
5071PyLong_Fini(void)
5072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 /* Integers are currently statically allocated. Py_DECREF is not
5074 needed, but Python must forget about the reference or multiple
5075 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005076#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 int i;
5078 PyLongObject *v = small_ints;
5079 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5080 _Py_DEC_REFTOTAL;
5081 _Py_ForgetReference((PyObject*)v);
5082 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005083#endif
5084}