blob: 0a5b9aa52c942bd3009d53fc0f6a0ca726d6aba8 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
33int quick_int_allocs, quick_neg_int_allocs;
34#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
159 sdigit ival = src->ob_digit[0];
160 if (Py_SIZE(src) < 0)
161 ival = -ival;
162 CHECK_SMALL_INT(ival);
163 }
164 result = _PyLong_New(i);
165 if (result != NULL) {
166 Py_SIZE(result) = Py_SIZE(src);
167 while (--i >= 0)
168 result->ob_digit[i] = src->ob_digit[i];
169 }
170 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000171}
172
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000173/* Create a new long int object from a C long int */
174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000176PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyLongObject *v;
179 unsigned long abs_ival;
180 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
181 int ndigits = 0;
182 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (ival < 0) {
187 /* negate: can't write this as abs_ival = -ival since that
188 invokes undefined behaviour when ival is LONG_MIN */
189 abs_ival = 0U-(unsigned long)ival;
190 sign = -1;
191 }
192 else {
193 abs_ival = (unsigned long)ival;
194 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Fast path for single-digit ints */
197 if (!(abs_ival >> PyLong_SHIFT)) {
198 v = _PyLong_New(1);
199 if (v) {
200 Py_SIZE(v) = sign;
201 v->ob_digit[0] = Py_SAFE_DOWNCAST(
202 abs_ival, unsigned long, digit);
203 }
204 return (PyObject*)v;
205 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206
Mark Dickinson249b8982009-04-27 19:41:00 +0000207#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* 2 digits */
209 if (!(abs_ival >> 2*PyLong_SHIFT)) {
210 v = _PyLong_New(2);
211 if (v) {
212 Py_SIZE(v) = 2*sign;
213 v->ob_digit[0] = Py_SAFE_DOWNCAST(
214 abs_ival & PyLong_MASK, unsigned long, digit);
215 v->ob_digit[1] = Py_SAFE_DOWNCAST(
216 abs_ival >> PyLong_SHIFT, unsigned long, digit);
217 }
218 return (PyObject*)v;
219 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000220#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 /* Larger numbers: loop to determine number of digits */
223 t = abs_ival;
224 while (t) {
225 ++ndigits;
226 t >>= PyLong_SHIFT;
227 }
228 v = _PyLong_New(ndigits);
229 if (v != NULL) {
230 digit *p = v->ob_digit;
231 Py_SIZE(v) = ndigits*sign;
232 t = abs_ival;
233 while (t) {
234 *p++ = Py_SAFE_DOWNCAST(
235 t & PyLong_MASK, unsigned long, digit);
236 t >>= PyLong_SHIFT;
237 }
238 }
239 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000240}
241
Guido van Rossum53756b11997-01-03 17:14:46 +0000242/* Create a new long int object from a C unsigned long int */
243
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000245PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyLongObject *v;
248 unsigned long t;
249 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (ival < PyLong_BASE)
252 return PyLong_FromLong(ival);
253 /* Count the number of Python digits. */
254 t = (unsigned long)ival;
255 while (t) {
256 ++ndigits;
257 t >>= PyLong_SHIFT;
258 }
259 v = _PyLong_New(ndigits);
260 if (v != NULL) {
261 digit *p = v->ob_digit;
262 Py_SIZE(v) = ndigits;
263 while (ival) {
264 *p++ = (digit)(ival & PyLong_MASK);
265 ival >>= PyLong_SHIFT;
266 }
267 }
268 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000269}
270
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000271/* Create a new long int object from a C double */
272
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000273PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 PyLongObject *v;
277 double frac;
278 int i, ndig, expo, neg;
279 neg = 0;
280 if (Py_IS_INFINITY(dval)) {
281 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000282 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
284 }
285 if (Py_IS_NAN(dval)) {
286 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000287 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 return NULL;
289 }
290 if (dval < 0.0) {
291 neg = 1;
292 dval = -dval;
293 }
294 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
295 if (expo <= 0)
296 return PyLong_FromLong(0L);
297 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
298 v = _PyLong_New(ndig);
299 if (v == NULL)
300 return NULL;
301 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
302 for (i = ndig; --i >= 0; ) {
303 digit bits = (digit)frac;
304 v->ob_digit[i] = bits;
305 frac = frac - (double)bits;
306 frac = ldexp(frac, PyLong_SHIFT);
307 }
308 if (neg)
309 Py_SIZE(v) = -(Py_SIZE(v));
310 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000311}
312
Thomas Wouters89f507f2006-12-13 04:49:30 +0000313/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
314 * anything about what happens when a signed integer operation overflows,
315 * and some compilers think they're doing you a favor by being "clever"
316 * then. The bit pattern for the largest postive signed long is
317 * (unsigned long)LONG_MAX, and for the smallest negative signed long
318 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
319 * However, some other compilers warn about applying unary minus to an
320 * unsigned operand. Hence the weird "0-".
321 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
323#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324
Mark Dickinson8d48b432011-10-23 20:47:14 +0100325/* Get a C long int from a long int object or any object that has an __int__
326 method.
327
328 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
329 the result. Otherwise *overflow is 0.
330
331 For other errors (e.g., TypeError), return -1 and set an error condition.
332 In this case *overflow will be 0.
333*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000334
335long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000336PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 /* This version by Tim Peters */
339 register PyLongObject *v;
340 unsigned long x, prev;
341 long res;
342 Py_ssize_t i;
343 int sign;
344 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 *overflow = 0;
347 if (vv == NULL) {
348 PyErr_BadInternalCall();
349 return -1;
350 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (!PyLong_Check(vv)) {
353 PyNumberMethods *nb;
354 nb = vv->ob_type->tp_as_number;
355 if (nb == NULL || nb->nb_int == NULL) {
356 PyErr_SetString(PyExc_TypeError,
357 "an integer is required");
358 return -1;
359 }
360 vv = (*nb->nb_int) (vv);
361 if (vv == NULL)
362 return -1;
363 do_decref = 1;
364 if (!PyLong_Check(vv)) {
365 Py_DECREF(vv);
366 PyErr_SetString(PyExc_TypeError,
367 "nb_int should return int object");
368 return -1;
369 }
370 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 res = -1;
373 v = (PyLongObject *)vv;
374 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 switch (i) {
377 case -1:
378 res = -(sdigit)v->ob_digit[0];
379 break;
380 case 0:
381 res = 0;
382 break;
383 case 1:
384 res = v->ob_digit[0];
385 break;
386 default:
387 sign = 1;
388 x = 0;
389 if (i < 0) {
390 sign = -1;
391 i = -(i);
392 }
393 while (--i >= 0) {
394 prev = x;
395 x = (x << PyLong_SHIFT) | v->ob_digit[i];
396 if ((x >> PyLong_SHIFT) != prev) {
397 *overflow = sign;
398 goto exit;
399 }
400 }
401 /* Haven't lost any bits, but casting to long requires extra
402 * care (see comment above).
403 */
404 if (x <= (unsigned long)LONG_MAX) {
405 res = (long)x * sign;
406 }
407 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
408 res = LONG_MIN;
409 }
410 else {
411 *overflow = sign;
412 /* res is already set to -1 */
413 }
414 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000415 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (do_decref) {
417 Py_DECREF(vv);
418 }
419 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000420}
421
Mark Dickinson8d48b432011-10-23 20:47:14 +0100422/* Get a C long int from a long int object or any object that has an __int__
423 method. Return -1 and set an error if overflow occurs. */
424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000426PyLong_AsLong(PyObject *obj)
427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 int overflow;
429 long result = PyLong_AsLongAndOverflow(obj, &overflow);
430 if (overflow) {
431 /* XXX: could be cute and give a different
432 message for overflow == -1 */
433 PyErr_SetString(PyExc_OverflowError,
434 "Python int too large to convert to C long");
435 }
436 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000437}
438
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000439/* Get a Py_ssize_t from a long int object.
440 Returns -1 and sets an error condition if overflow occurs. */
441
442Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000443PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 register PyLongObject *v;
445 size_t x, prev;
446 Py_ssize_t i;
447 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (vv == NULL) {
450 PyErr_BadInternalCall();
451 return -1;
452 }
453 if (!PyLong_Check(vv)) {
454 PyErr_SetString(PyExc_TypeError, "an integer is required");
455 return -1;
456 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 v = (PyLongObject *)vv;
459 i = Py_SIZE(v);
460 switch (i) {
461 case -1: return -(sdigit)v->ob_digit[0];
462 case 0: return 0;
463 case 1: return v->ob_digit[0];
464 }
465 sign = 1;
466 x = 0;
467 if (i < 0) {
468 sign = -1;
469 i = -(i);
470 }
471 while (--i >= 0) {
472 prev = x;
473 x = (x << PyLong_SHIFT) | v->ob_digit[i];
474 if ((x >> PyLong_SHIFT) != prev)
475 goto overflow;
476 }
477 /* Haven't lost any bits, but casting to a signed type requires
478 * extra care (see comment above).
479 */
480 if (x <= (size_t)PY_SSIZE_T_MAX) {
481 return (Py_ssize_t)x * sign;
482 }
483 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
484 return PY_SSIZE_T_MIN;
485 }
486 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487
Mark Dickinson22b20182010-05-10 21:27:53 +0000488 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyErr_SetString(PyExc_OverflowError,
490 "Python int too large to convert to C ssize_t");
491 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000492}
493
Guido van Rossumd8c80482002-08-13 00:24:58 +0000494/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000495 Returns -1 and sets an error condition if overflow occurs. */
496
497unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000498PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 register PyLongObject *v;
501 unsigned long x, prev;
502 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (vv == NULL) {
505 PyErr_BadInternalCall();
506 return (unsigned long)-1;
507 }
508 if (!PyLong_Check(vv)) {
509 PyErr_SetString(PyExc_TypeError, "an integer is required");
510 return (unsigned long)-1;
511 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 v = (PyLongObject *)vv;
514 i = Py_SIZE(v);
515 x = 0;
516 if (i < 0) {
517 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000518 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return (unsigned long) -1;
520 }
521 switch (i) {
522 case 0: return 0;
523 case 1: return v->ob_digit[0];
524 }
525 while (--i >= 0) {
526 prev = x;
527 x = (x << PyLong_SHIFT) | v->ob_digit[i];
528 if ((x >> PyLong_SHIFT) != prev) {
529 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000530 "python int too large to convert "
531 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return (unsigned long) -1;
533 }
534 }
535 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000536}
537
Stefan Krahb77c6c62011-09-12 16:22:47 +0200538/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
539 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000540
541size_t
542PyLong_AsSize_t(PyObject *vv)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 register PyLongObject *v;
545 size_t x, prev;
546 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (vv == NULL) {
549 PyErr_BadInternalCall();
550 return (size_t) -1;
551 }
552 if (!PyLong_Check(vv)) {
553 PyErr_SetString(PyExc_TypeError, "an integer is required");
554 return (size_t)-1;
555 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 v = (PyLongObject *)vv;
558 i = Py_SIZE(v);
559 x = 0;
560 if (i < 0) {
561 PyErr_SetString(PyExc_OverflowError,
562 "can't convert negative value to size_t");
563 return (size_t) -1;
564 }
565 switch (i) {
566 case 0: return 0;
567 case 1: return v->ob_digit[0];
568 }
569 while (--i >= 0) {
570 prev = x;
571 x = (x << PyLong_SHIFT) | v->ob_digit[i];
572 if ((x >> PyLong_SHIFT) != prev) {
573 PyErr_SetString(PyExc_OverflowError,
574 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200575 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 }
577 }
578 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000579}
580
Thomas Hellera4ea6032003-04-17 18:55:45 +0000581/* Get a C unsigned long int from a long int object, ignoring the high bits.
582 Returns -1 and sets an error condition if an error occurs. */
583
Guido van Rossumddefaf32007-01-14 03:31:43 +0000584static unsigned long
585_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 register PyLongObject *v;
588 unsigned long x;
589 Py_ssize_t i;
590 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (vv == NULL || !PyLong_Check(vv)) {
593 PyErr_BadInternalCall();
594 return (unsigned long) -1;
595 }
596 v = (PyLongObject *)vv;
597 i = Py_SIZE(v);
598 switch (i) {
599 case 0: return 0;
600 case 1: return v->ob_digit[0];
601 }
602 sign = 1;
603 x = 0;
604 if (i < 0) {
605 sign = -1;
606 i = -i;
607 }
608 while (--i >= 0) {
609 x = (x << PyLong_SHIFT) | v->ob_digit[i];
610 }
611 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000612}
613
Guido van Rossumddefaf32007-01-14 03:31:43 +0000614unsigned long
615PyLong_AsUnsignedLongMask(register PyObject *op)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyNumberMethods *nb;
618 PyLongObject *lo;
619 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (op && PyLong_Check(op))
622 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
625 nb->nb_int == NULL) {
626 PyErr_SetString(PyExc_TypeError, "an integer is required");
627 return (unsigned long)-1;
628 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 lo = (PyLongObject*) (*nb->nb_int) (op);
631 if (lo == NULL)
632 return (unsigned long)-1;
633 if (PyLong_Check(lo)) {
634 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
635 Py_DECREF(lo);
636 if (PyErr_Occurred())
637 return (unsigned long)-1;
638 return val;
639 }
640 else
641 {
642 Py_DECREF(lo);
643 PyErr_SetString(PyExc_TypeError,
644 "nb_int should return int object");
645 return (unsigned long)-1;
646 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000647}
648
Tim Peters5b8132f2003-01-31 15:52:05 +0000649int
650_PyLong_Sign(PyObject *vv)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 assert(v != NULL);
655 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000658}
659
Tim Petersbaefd9e2003-01-28 20:37:45 +0000660size_t
661_PyLong_NumBits(PyObject *vv)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyLongObject *v = (PyLongObject *)vv;
664 size_t result = 0;
665 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 assert(v != NULL);
668 assert(PyLong_Check(v));
669 ndigits = ABS(Py_SIZE(v));
670 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
671 if (ndigits > 0) {
672 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 result = (ndigits - 1) * PyLong_SHIFT;
675 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
676 goto Overflow;
677 do {
678 ++result;
679 if (result == 0)
680 goto Overflow;
681 msd >>= 1;
682 } while (msd);
683 }
684 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000685
Mark Dickinson22b20182010-05-10 21:27:53 +0000686 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
688 "to express in a platform size_t");
689 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000690}
691
Tim Peters2a9b3672001-06-11 21:23:58 +0000692PyObject *
693_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000695{
Mark Dickinson22b20182010-05-10 21:27:53 +0000696 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 int incr; /* direction to move pstartbyte */
698 const unsigned char* pendbyte; /* MSB of bytes */
699 size_t numsignificantbytes; /* number of bytes that matter */
700 Py_ssize_t ndigits; /* number of Python long digits */
701 PyLongObject* v; /* result */
702 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (n == 0)
705 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (little_endian) {
708 pstartbyte = bytes;
709 pendbyte = bytes + n - 1;
710 incr = 1;
711 }
712 else {
713 pstartbyte = bytes + n - 1;
714 pendbyte = bytes;
715 incr = -1;
716 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (is_signed)
719 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200722 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 is positive, and leading 0xff bytes if negative. */
724 {
725 size_t i;
726 const unsigned char* p = pendbyte;
727 const int pincr = -incr; /* search MSB to LSB */
728 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 for (i = 0; i < n; ++i, p += pincr) {
731 if (*p != insignficant)
732 break;
733 }
734 numsignificantbytes = n - i;
735 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
736 actually has 2 significant bytes. OTOH, 0xff0001 ==
737 -0x00ffff, so we wouldn't *need* to bump it there; but we
738 do for 0xffff = -0x0001. To be safe without bothering to
739 check every case, bump it regardless. */
740 if (is_signed && numsignificantbytes < n)
741 ++numsignificantbytes;
742 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 /* How many Python long digits do we need? We have
745 8*numsignificantbytes bits, and each Python long digit has
746 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
747 /* catch overflow before it happens */
748 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
749 PyErr_SetString(PyExc_OverflowError,
750 "byte array too long to convert to int");
751 return NULL;
752 }
753 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
754 v = _PyLong_New(ndigits);
755 if (v == NULL)
756 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* Copy the bits over. The tricky parts are computing 2's-comp on
759 the fly for signed numbers, and dealing with the mismatch between
760 8-bit bytes and (probably) 15-bit Python digits.*/
761 {
762 size_t i;
763 twodigits carry = 1; /* for 2's-comp calculation */
764 twodigits accum = 0; /* sliding register */
765 unsigned int accumbits = 0; /* number of bits in accum */
766 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
769 twodigits thisbyte = *p;
770 /* Compute correction for 2's comp, if needed. */
771 if (is_signed) {
772 thisbyte = (0xff ^ thisbyte) + carry;
773 carry = thisbyte >> 8;
774 thisbyte &= 0xff;
775 }
776 /* Because we're going LSB to MSB, thisbyte is
777 more significant than what's already in accum,
778 so needs to be prepended to accum. */
779 accum |= (twodigits)thisbyte << accumbits;
780 accumbits += 8;
781 if (accumbits >= PyLong_SHIFT) {
782 /* There's enough to fill a Python digit. */
783 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000784 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 ++idigit;
786 accum >>= PyLong_SHIFT;
787 accumbits -= PyLong_SHIFT;
788 assert(accumbits < PyLong_SHIFT);
789 }
790 }
791 assert(accumbits < PyLong_SHIFT);
792 if (accumbits) {
793 assert(idigit < ndigits);
794 v->ob_digit[idigit] = (digit)accum;
795 ++idigit;
796 }
797 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 Py_SIZE(v) = is_signed ? -idigit : idigit;
800 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000801}
802
803int
804_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 unsigned char* bytes, size_t n,
806 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000809 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000811 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
813 digit carry; /* for computing 2's-comp */
814 size_t j; /* # bytes filled */
815 unsigned char* p; /* pointer to next byte in bytes */
816 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (Py_SIZE(v) < 0) {
821 ndigits = -(Py_SIZE(v));
822 if (!is_signed) {
823 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000824 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return -1;
826 }
827 do_twos_comp = 1;
828 }
829 else {
830 ndigits = Py_SIZE(v);
831 do_twos_comp = 0;
832 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (little_endian) {
835 p = bytes;
836 pincr = 1;
837 }
838 else {
839 p = bytes + n - 1;
840 pincr = -1;
841 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Copy over all the Python digits.
844 It's crucial that every Python digit except for the MSD contribute
845 exactly PyLong_SHIFT bits to the total, so first assert that the long is
846 normalized. */
847 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
848 j = 0;
849 accum = 0;
850 accumbits = 0;
851 carry = do_twos_comp ? 1 : 0;
852 for (i = 0; i < ndigits; ++i) {
853 digit thisdigit = v->ob_digit[i];
854 if (do_twos_comp) {
855 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
856 carry = thisdigit >> PyLong_SHIFT;
857 thisdigit &= PyLong_MASK;
858 }
859 /* Because we're going LSB to MSB, thisdigit is more
860 significant than what's already in accum, so needs to be
861 prepended to accum. */
862 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 /* The most-significant digit may be (probably is) at least
865 partly empty. */
866 if (i == ndigits - 1) {
867 /* Count # of sign bits -- they needn't be stored,
868 * although for signed conversion we need later to
869 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000870 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 while (s != 0) {
872 s >>= 1;
873 accumbits++;
874 }
875 }
876 else
877 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Store as many bytes as possible. */
880 while (accumbits >= 8) {
881 if (j >= n)
882 goto Overflow;
883 ++j;
884 *p = (unsigned char)(accum & 0xff);
885 p += pincr;
886 accumbits -= 8;
887 accum >>= 8;
888 }
889 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Store the straggler (if any). */
892 assert(accumbits < 8);
893 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
894 if (accumbits > 0) {
895 if (j >= n)
896 goto Overflow;
897 ++j;
898 if (do_twos_comp) {
899 /* Fill leading bits of the byte with sign bits
900 (appropriately pretending that the long had an
901 infinite supply of sign bits). */
902 accum |= (~(twodigits)0) << accumbits;
903 }
904 *p = (unsigned char)(accum & 0xff);
905 p += pincr;
906 }
907 else if (j == n && n > 0 && is_signed) {
908 /* The main loop filled the byte array exactly, so the code
909 just above didn't get to ensure there's a sign bit, and the
910 loop below wouldn't add one either. Make sure a sign bit
911 exists. */
912 unsigned char msb = *(p - pincr);
913 int sign_bit_set = msb >= 0x80;
914 assert(accumbits == 0);
915 if (sign_bit_set == do_twos_comp)
916 return 0;
917 else
918 goto Overflow;
919 }
Tim Peters05607ad2001-06-13 21:01:27 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 /* Fill remaining bytes with copies of the sign bit. */
922 {
923 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
924 for ( ; j < n; ++j, p += pincr)
925 *p = signbyte;
926 }
Tim Peters05607ad2001-06-13 21:01:27 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000929
Mark Dickinson22b20182010-05-10 21:27:53 +0000930 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
932 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000933
Tim Peters2a9b3672001-06-11 21:23:58 +0000934}
935
Mark Dickinson8d48b432011-10-23 20:47:14 +0100936/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000937
938PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000939PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000940{
Tim Peters70128a12001-06-16 08:48:40 +0000941#ifndef HAVE_LONG_LONG
942# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
943#endif
944#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000945# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000946#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* special-case null pointer */
948 if (!p)
949 return PyLong_FromLong(0);
950 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000951
Guido van Rossum78694d91998-09-18 14:14:13 +0000952}
953
Mark Dickinson8d48b432011-10-23 20:47:14 +0100954/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000955
956void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000957PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000958{
Tim Peters70128a12001-06-16 08:48:40 +0000959#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
963 x = PyLong_AsLong(vv);
964 else
965 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000966#else
Tim Peters70128a12001-06-16 08:48:40 +0000967
968#ifndef HAVE_LONG_LONG
969# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
970#endif
971#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000972# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
977 x = PyLong_AsLongLong(vv);
978 else
979 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000980
981#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (x == -1 && PyErr_Occurred())
984 return NULL;
985 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000986}
987
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000988#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000989
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000991 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000992 */
993
Tim Peterscf37dfc2001-06-14 18:42:50 +0000994#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000995#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000996
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000997/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000998
999PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001000PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyLongObject *v;
1003 unsigned PY_LONG_LONG abs_ival;
1004 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1005 int ndigits = 0;
1006 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 CHECK_SMALL_INT(ival);
1009 if (ival < 0) {
1010 /* avoid signed overflow on negation; see comments
1011 in PyLong_FromLong above. */
1012 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1013 negative = 1;
1014 }
1015 else {
1016 abs_ival = (unsigned PY_LONG_LONG)ival;
1017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* Count the number of Python digits.
1020 We used to pick 5 ("big enough for anything"), but that's a
1021 waste of time and space given that 5*15 = 75 bits are rarely
1022 needed. */
1023 t = abs_ival;
1024 while (t) {
1025 ++ndigits;
1026 t >>= PyLong_SHIFT;
1027 }
1028 v = _PyLong_New(ndigits);
1029 if (v != NULL) {
1030 digit *p = v->ob_digit;
1031 Py_SIZE(v) = negative ? -ndigits : ndigits;
1032 t = abs_ival;
1033 while (t) {
1034 *p++ = (digit)(t & PyLong_MASK);
1035 t >>= PyLong_SHIFT;
1036 }
1037 }
1038 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039}
1040
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001042
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001044PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyLongObject *v;
1047 unsigned PY_LONG_LONG t;
1048 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (ival < PyLong_BASE)
1051 return PyLong_FromLong((long)ival);
1052 /* Count the number of Python digits. */
1053 t = (unsigned PY_LONG_LONG)ival;
1054 while (t) {
1055 ++ndigits;
1056 t >>= PyLong_SHIFT;
1057 }
1058 v = _PyLong_New(ndigits);
1059 if (v != NULL) {
1060 digit *p = v->ob_digit;
1061 Py_SIZE(v) = ndigits;
1062 while (ival) {
1063 *p++ = (digit)(ival & PyLong_MASK);
1064 ival >>= PyLong_SHIFT;
1065 }
1066 }
1067 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001068}
1069
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070/* Create a new long int object from a C Py_ssize_t. */
1071
1072PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001073PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyLongObject *v;
1076 size_t abs_ival;
1077 size_t t; /* unsigned so >> doesn't propagate sign bit */
1078 int ndigits = 0;
1079 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 CHECK_SMALL_INT(ival);
1082 if (ival < 0) {
1083 /* avoid signed overflow when ival = SIZE_T_MIN */
1084 abs_ival = (size_t)(-1-ival)+1;
1085 negative = 1;
1086 }
1087 else {
1088 abs_ival = (size_t)ival;
1089 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 /* Count the number of Python digits. */
1092 t = abs_ival;
1093 while (t) {
1094 ++ndigits;
1095 t >>= PyLong_SHIFT;
1096 }
1097 v = _PyLong_New(ndigits);
1098 if (v != NULL) {
1099 digit *p = v->ob_digit;
1100 Py_SIZE(v) = negative ? -ndigits : ndigits;
1101 t = abs_ival;
1102 while (t) {
1103 *p++ = (digit)(t & PyLong_MASK);
1104 t >>= PyLong_SHIFT;
1105 }
1106 }
1107 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108}
1109
1110/* Create a new long int object from a C size_t. */
1111
1112PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001113PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyLongObject *v;
1116 size_t t;
1117 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (ival < PyLong_BASE)
1120 return PyLong_FromLong((long)ival);
1121 /* Count the number of Python digits. */
1122 t = ival;
1123 while (t) {
1124 ++ndigits;
1125 t >>= PyLong_SHIFT;
1126 }
1127 v = _PyLong_New(ndigits);
1128 if (v != NULL) {
1129 digit *p = v->ob_digit;
1130 Py_SIZE(v) = ndigits;
1131 while (ival) {
1132 *p++ = (digit)(ival & PyLong_MASK);
1133 ival >>= PyLong_SHIFT;
1134 }
1135 }
1136 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137}
1138
Mark Dickinson8d48b432011-10-23 20:47:14 +01001139/* Get a C long long int from a long int object or any object that has an
1140 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001142PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001143PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyLongObject *v;
1146 PY_LONG_LONG bytes;
1147 int one = 1;
1148 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (vv == NULL) {
1151 PyErr_BadInternalCall();
1152 return -1;
1153 }
1154 if (!PyLong_Check(vv)) {
1155 PyNumberMethods *nb;
1156 PyObject *io;
1157 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1158 nb->nb_int == NULL) {
1159 PyErr_SetString(PyExc_TypeError, "an integer is required");
1160 return -1;
1161 }
1162 io = (*nb->nb_int) (vv);
1163 if (io == NULL)
1164 return -1;
1165 if (PyLong_Check(io)) {
1166 bytes = PyLong_AsLongLong(io);
1167 Py_DECREF(io);
1168 return bytes;
1169 }
1170 Py_DECREF(io);
1171 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1172 return -1;
1173 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 v = (PyLongObject*)vv;
1176 switch(Py_SIZE(v)) {
1177 case -1: return -(sdigit)v->ob_digit[0];
1178 case 0: return 0;
1179 case 1: return v->ob_digit[0];
1180 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001181 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1182 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1185 if (res < 0)
1186 return (PY_LONG_LONG)-1;
1187 else
1188 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001189}
1190
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001191/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001192 Return -1 and set an error if overflow occurs. */
1193
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001194unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001195PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyLongObject *v;
1198 unsigned PY_LONG_LONG bytes;
1199 int one = 1;
1200 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001201
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001202 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyErr_BadInternalCall();
1204 return (unsigned PY_LONG_LONG)-1;
1205 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001206 if (!PyLong_Check(vv)) {
1207 PyErr_SetString(PyExc_TypeError, "an integer is required");
1208 return (unsigned PY_LONG_LONG)-1;
1209 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 v = (PyLongObject*)vv;
1212 switch(Py_SIZE(v)) {
1213 case 0: return 0;
1214 case 1: return v->ob_digit[0];
1215 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001216
Mark Dickinson22b20182010-05-10 21:27:53 +00001217 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1218 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1221 if (res < 0)
1222 return (unsigned PY_LONG_LONG)res;
1223 else
1224 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001225}
Tim Petersd1a7da62001-06-13 00:35:57 +00001226
Thomas Hellera4ea6032003-04-17 18:55:45 +00001227/* Get a C unsigned long int from a long int object, ignoring the high bits.
1228 Returns -1 and sets an error condition if an error occurs. */
1229
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230static unsigned PY_LONG_LONG
1231_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 register PyLongObject *v;
1234 unsigned PY_LONG_LONG x;
1235 Py_ssize_t i;
1236 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (vv == NULL || !PyLong_Check(vv)) {
1239 PyErr_BadInternalCall();
1240 return (unsigned long) -1;
1241 }
1242 v = (PyLongObject *)vv;
1243 switch(Py_SIZE(v)) {
1244 case 0: return 0;
1245 case 1: return v->ob_digit[0];
1246 }
1247 i = Py_SIZE(v);
1248 sign = 1;
1249 x = 0;
1250 if (i < 0) {
1251 sign = -1;
1252 i = -i;
1253 }
1254 while (--i >= 0) {
1255 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1256 }
1257 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001258}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001259
1260unsigned PY_LONG_LONG
1261PyLong_AsUnsignedLongLongMask(register PyObject *op)
1262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyNumberMethods *nb;
1264 PyLongObject *lo;
1265 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (op && PyLong_Check(op))
1268 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1271 nb->nb_int == NULL) {
1272 PyErr_SetString(PyExc_TypeError, "an integer is required");
1273 return (unsigned PY_LONG_LONG)-1;
1274 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 lo = (PyLongObject*) (*nb->nb_int) (op);
1277 if (lo == NULL)
1278 return (unsigned PY_LONG_LONG)-1;
1279 if (PyLong_Check(lo)) {
1280 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1281 Py_DECREF(lo);
1282 if (PyErr_Occurred())
1283 return (unsigned PY_LONG_LONG)-1;
1284 return val;
1285 }
1286 else
1287 {
1288 Py_DECREF(lo);
1289 PyErr_SetString(PyExc_TypeError,
1290 "nb_int should return int object");
1291 return (unsigned PY_LONG_LONG)-1;
1292 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001293}
Tim Petersd1a7da62001-06-13 00:35:57 +00001294#undef IS_LITTLE_ENDIAN
1295
Mark Dickinson8d48b432011-10-23 20:47:14 +01001296/* Get a C long long int from a long int object or any object that has an
1297 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001298
Mark Dickinson8d48b432011-10-23 20:47:14 +01001299 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1300 the result. Otherwise *overflow is 0.
1301
1302 For other errors (e.g., TypeError), return -1 and set an error condition.
1303 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001304*/
1305
1306PY_LONG_LONG
1307PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /* This version by Tim Peters */
1310 register PyLongObject *v;
1311 unsigned PY_LONG_LONG x, prev;
1312 PY_LONG_LONG res;
1313 Py_ssize_t i;
1314 int sign;
1315 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 *overflow = 0;
1318 if (vv == NULL) {
1319 PyErr_BadInternalCall();
1320 return -1;
1321 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (!PyLong_Check(vv)) {
1324 PyNumberMethods *nb;
1325 nb = vv->ob_type->tp_as_number;
1326 if (nb == NULL || nb->nb_int == NULL) {
1327 PyErr_SetString(PyExc_TypeError,
1328 "an integer is required");
1329 return -1;
1330 }
1331 vv = (*nb->nb_int) (vv);
1332 if (vv == NULL)
1333 return -1;
1334 do_decref = 1;
1335 if (!PyLong_Check(vv)) {
1336 Py_DECREF(vv);
1337 PyErr_SetString(PyExc_TypeError,
1338 "nb_int should return int object");
1339 return -1;
1340 }
1341 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 res = -1;
1344 v = (PyLongObject *)vv;
1345 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 switch (i) {
1348 case -1:
1349 res = -(sdigit)v->ob_digit[0];
1350 break;
1351 case 0:
1352 res = 0;
1353 break;
1354 case 1:
1355 res = v->ob_digit[0];
1356 break;
1357 default:
1358 sign = 1;
1359 x = 0;
1360 if (i < 0) {
1361 sign = -1;
1362 i = -(i);
1363 }
1364 while (--i >= 0) {
1365 prev = x;
1366 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1367 if ((x >> PyLong_SHIFT) != prev) {
1368 *overflow = sign;
1369 goto exit;
1370 }
1371 }
1372 /* Haven't lost any bits, but casting to long requires extra
1373 * care (see comment above).
1374 */
1375 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1376 res = (PY_LONG_LONG)x * sign;
1377 }
1378 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1379 res = PY_LLONG_MIN;
1380 }
1381 else {
1382 *overflow = sign;
1383 /* res is already set to -1 */
1384 }
1385 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001386 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 if (do_decref) {
1388 Py_DECREF(vv);
1389 }
1390 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001391}
1392
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001393#endif /* HAVE_LONG_LONG */
1394
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001395#define CHECK_BINOP(v,w) \
1396 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001397 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1398 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001399 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001400
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001401/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1402 2**k if d is nonzero, else 0. */
1403
1404static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1406 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001407};
1408
1409static int
1410bits_in_digit(digit d)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 int d_bits = 0;
1413 while (d >= 32) {
1414 d_bits += 6;
1415 d >>= 6;
1416 }
1417 d_bits += (int)BitLengthTable[d];
1418 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001419}
1420
Tim Peters877a2122002-08-12 05:09:36 +00001421/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1422 * is modified in place, by adding y to it. Carries are propagated as far as
1423 * x[m-1], and the remaining carry (0 or 1) is returned.
1424 */
1425static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001426v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 Py_ssize_t i;
1429 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 assert(m >= n);
1432 for (i = 0; i < n; ++i) {
1433 carry += x[i] + y[i];
1434 x[i] = carry & PyLong_MASK;
1435 carry >>= PyLong_SHIFT;
1436 assert((carry & 1) == carry);
1437 }
1438 for (; carry && i < m; ++i) {
1439 carry += x[i];
1440 x[i] = carry & PyLong_MASK;
1441 carry >>= PyLong_SHIFT;
1442 assert((carry & 1) == carry);
1443 }
1444 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001445}
1446
1447/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1448 * is modified in place, by subtracting y from it. Borrows are propagated as
1449 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1450 */
1451static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i;
1455 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 assert(m >= n);
1458 for (i = 0; i < n; ++i) {
1459 borrow = x[i] - y[i] - borrow;
1460 x[i] = borrow & PyLong_MASK;
1461 borrow >>= PyLong_SHIFT;
1462 borrow &= 1; /* keep only 1 sign bit */
1463 }
1464 for (; borrow && i < m; ++i) {
1465 borrow = x[i] - borrow;
1466 x[i] = borrow & PyLong_MASK;
1467 borrow >>= PyLong_SHIFT;
1468 borrow &= 1;
1469 }
1470 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001471}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001472
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001473/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1474 * result in z[0:m], and return the d bits shifted out of the top.
1475 */
1476static digit
1477v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 Py_ssize_t i;
1480 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 assert(0 <= d && d < PyLong_SHIFT);
1483 for (i=0; i < m; i++) {
1484 twodigits acc = (twodigits)a[i] << d | carry;
1485 z[i] = (digit)acc & PyLong_MASK;
1486 carry = (digit)(acc >> PyLong_SHIFT);
1487 }
1488 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001489}
1490
1491/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1492 * result in z[0:m], and return the d bits shifted out of the bottom.
1493 */
1494static digit
1495v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_ssize_t i;
1498 digit carry = 0;
1499 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 assert(0 <= d && d < PyLong_SHIFT);
1502 for (i=m; i-- > 0;) {
1503 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1504 carry = (digit)acc & mask;
1505 z[i] = (digit)(acc >> d);
1506 }
1507 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001508}
1509
Tim Peters212e6142001-07-14 12:23:19 +00001510/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1511 in pout, and returning the remainder. pin and pout point at the LSD.
1512 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001513 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001514 immutable. */
1515
1516static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001517inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 assert(n > 0 && n <= PyLong_MASK);
1522 pin += size;
1523 pout += size;
1524 while (--size >= 0) {
1525 digit hi;
1526 rem = (rem << PyLong_SHIFT) | *--pin;
1527 *--pout = hi = (digit)(rem / n);
1528 rem -= (twodigits)hi * n;
1529 }
1530 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001531}
1532
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001533/* Divide a long integer by a digit, returning both the quotient
1534 (as function result) and the remainder (through *prem).
1535 The sign of a is ignored; n should not be zero. */
1536
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001537static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001538divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 const Py_ssize_t size = ABS(Py_SIZE(a));
1541 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 assert(n > 0 && n <= PyLong_MASK);
1544 z = _PyLong_New(size);
1545 if (z == NULL)
1546 return NULL;
1547 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1548 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001549}
1550
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001551/* Convert a long integer to a base 10 string. Returns a new non-shared
1552 string. (Return value is non-shared so that callers can modify the
1553 returned value if necessary.) */
1554
1555static PyObject *
1556long_to_decimal_string(PyObject *aa)
1557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyLongObject *scratch, *a;
1559 PyObject *str;
1560 Py_ssize_t size, strlen, size_a, i, j;
1561 digit *pout, *pin, rem, tenpow;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001562 unsigned char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 a = (PyLongObject *)aa;
1566 if (a == NULL || !PyLong_Check(a)) {
1567 PyErr_BadInternalCall();
1568 return NULL;
1569 }
1570 size_a = ABS(Py_SIZE(a));
1571 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* quick and dirty upper bound for the number of digits
1574 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 But log2(a) < size_a * PyLong_SHIFT, and
1579 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1580 > 3 * _PyLong_DECIMAL_SHIFT
1581 */
1582 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1583 PyErr_SetString(PyExc_OverflowError,
1584 "long is too large to format");
1585 return NULL;
1586 }
1587 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1588 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1589 scratch = _PyLong_New(size);
1590 if (scratch == NULL)
1591 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* convert array of base _PyLong_BASE digits in pin to an array of
1594 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1595 Volume 2 (3rd edn), section 4.4, Method 1b). */
1596 pin = a->ob_digit;
1597 pout = scratch->ob_digit;
1598 size = 0;
1599 for (i = size_a; --i >= 0; ) {
1600 digit hi = pin[i];
1601 for (j = 0; j < size; j++) {
1602 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1603 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1604 pout[j] = (digit)(z - (twodigits)hi *
1605 _PyLong_DECIMAL_BASE);
1606 }
1607 while (hi) {
1608 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1609 hi /= _PyLong_DECIMAL_BASE;
1610 }
1611 /* check for keyboard interrupt */
1612 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001613 Py_DECREF(scratch);
1614 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001615 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
1617 /* pout should have at least one digit, so that the case when a = 0
1618 works correctly */
1619 if (size == 0)
1620 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* calculate exact length of output string, and allocate */
1623 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1624 tenpow = 10;
1625 rem = pout[size-1];
1626 while (rem >= tenpow) {
1627 tenpow *= 10;
1628 strlen++;
1629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001630 str = PyUnicode_New(strlen, '9');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (str == NULL) {
1632 Py_DECREF(scratch);
1633 return NULL;
1634 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 /* fill the string right-to-left */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001637 assert(PyUnicode_KIND(str) == PyUnicode_1BYTE_KIND);
1638 p = PyUnicode_1BYTE_DATA(str) + strlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 *p = '\0';
1640 /* pout[0] through pout[size-2] contribute exactly
1641 _PyLong_DECIMAL_SHIFT digits each */
1642 for (i=0; i < size - 1; i++) {
1643 rem = pout[i];
1644 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1645 *--p = '0' + rem % 10;
1646 rem /= 10;
1647 }
1648 }
1649 /* pout[size-1]: always produce at least one decimal digit */
1650 rem = pout[i];
1651 do {
1652 *--p = '0' + rem % 10;
1653 rem /= 10;
1654 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 /* and sign */
1657 if (negative)
1658 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 /* check we've counted correctly */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661 assert(p == PyUnicode_1BYTE_DATA(str));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 Py_DECREF(scratch);
1663 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001664}
1665
Mark Dickinsoncd068122009-09-18 14:53:08 +00001666/* Convert a long int object to a string, using a given conversion base,
1667 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001668 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001669
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001670PyObject *
1671_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001675 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 Py_ssize_t size_a;
Mark Dickinsone2846542012-04-20 21:21:24 +01001677 Py_UCS1 *p;
1678 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 assert(base == 2 || base == 8 || base == 10 || base == 16);
1682 if (base == 10)
1683 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (a == NULL || !PyLong_Check(a)) {
1686 PyErr_BadInternalCall();
1687 return NULL;
1688 }
1689 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001690 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* Compute a rough upper bound for the length of the string */
1693 switch (base) {
1694 case 16:
1695 bits = 4;
1696 break;
1697 case 8:
1698 bits = 3;
1699 break;
1700 case 2:
1701 bits = 1;
1702 break;
1703 default:
1704 assert(0); /* shouldn't ever get here */
1705 bits = 0; /* to silence gcc warning */
1706 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001707
Mark Dickinsone2846542012-04-20 21:21:24 +01001708 /* Compute exact length 'sz' of output string. */
1709 if (size_a == 0) {
1710 sz = 3;
1711 }
1712 else {
1713 Py_ssize_t size_a_in_bits;
1714 /* Ensure overflow doesn't occur during computation of sz. */
1715 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1716 PyErr_SetString(PyExc_OverflowError,
1717 "int is too large to format");
1718 return NULL;
1719 }
1720 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1721 bits_in_digit(a->ob_digit[size_a - 1]);
1722 /* Allow 2 characters for prefix and 1 for a '-' sign. */
1723 sz = 2 + negative + (size_a_in_bits + (bits - 1)) / bits;
1724 }
1725
1726 v = PyUnicode_New(sz, 'x');
1727 if (v == NULL) {
1728 return NULL;
1729 }
1730 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
1731
1732 p = PyUnicode_1BYTE_DATA(v) + sz;
1733 if (size_a == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 *--p = '0';
1735 }
1736 else {
1737 /* JRH: special case for power-of-2 bases */
1738 twodigits accum = 0;
1739 int accumbits = 0; /* # of bits in accum */
Mark Dickinsone2846542012-04-20 21:21:24 +01001740 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 for (i = 0; i < size_a; ++i) {
1742 accum |= (twodigits)a->ob_digit[i] << accumbits;
1743 accumbits += PyLong_SHIFT;
1744 assert(accumbits >= bits);
1745 do {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 char cdigit;
1747 cdigit = (char)(accum & (base - 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 *--p = cdigit;
1750 accumbits -= bits;
1751 accum >>= bits;
1752 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1753 }
1754 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 if (base == 16)
1757 *--p = 'x';
1758 else if (base == 8)
1759 *--p = 'o';
1760 else /* (base == 2) */
1761 *--p = 'b';
1762 *--p = '0';
Mark Dickinsone2846542012-04-20 21:21:24 +01001763 if (negative)
1764 *--p = '-';
1765 assert(p == PyUnicode_1BYTE_DATA(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001767}
1768
Thomas Wouters477c8d52006-05-27 19:21:47 +00001769/* Table of digit values for 8-bit string -> integer conversion.
1770 * '0' maps to 0, ..., '9' maps to 9.
1771 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1772 * All other indices map to 37.
1773 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001774 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001775 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001776unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1778 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1779 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1780 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1781 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1782 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1783 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1784 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1785 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1786 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1787 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1788 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1789 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1790 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1791 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1792 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001793};
1794
1795/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001796 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1797 * non-digit (which may be *str!). A normalized long is returned.
1798 * The point to this routine is that it takes time linear in the number of
1799 * string characters.
1800 */
1801static PyLongObject *
1802long_from_binary_base(char **str, int base)
1803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 char *p = *str;
1805 char *start = p;
1806 int bits_per_char;
1807 Py_ssize_t n;
1808 PyLongObject *z;
1809 twodigits accum;
1810 int bits_in_accum;
1811 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1814 n = base;
1815 for (bits_per_char = -1; n; ++bits_per_char)
1816 n >>= 1;
1817 /* n <- total # of bits needed, while setting p to end-of-string */
1818 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1819 ++p;
1820 *str = p;
1821 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1822 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1823 if (n / bits_per_char < p - start) {
1824 PyErr_SetString(PyExc_ValueError,
1825 "int string too large to convert");
1826 return NULL;
1827 }
1828 n = n / PyLong_SHIFT;
1829 z = _PyLong_New(n);
1830 if (z == NULL)
1831 return NULL;
1832 /* Read string from right, and fill in long from left; i.e.,
1833 * from least to most significant in both.
1834 */
1835 accum = 0;
1836 bits_in_accum = 0;
1837 pdigit = z->ob_digit;
1838 while (--p >= start) {
1839 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1840 assert(k >= 0 && k < base);
1841 accum |= (twodigits)k << bits_in_accum;
1842 bits_in_accum += bits_per_char;
1843 if (bits_in_accum >= PyLong_SHIFT) {
1844 *pdigit++ = (digit)(accum & PyLong_MASK);
1845 assert(pdigit - z->ob_digit <= n);
1846 accum >>= PyLong_SHIFT;
1847 bits_in_accum -= PyLong_SHIFT;
1848 assert(bits_in_accum < PyLong_SHIFT);
1849 }
1850 }
1851 if (bits_in_accum) {
1852 assert(bits_in_accum <= PyLong_SHIFT);
1853 *pdigit++ = (digit)accum;
1854 assert(pdigit - z->ob_digit <= n);
1855 }
1856 while (pdigit - z->ob_digit < n)
1857 *pdigit++ = 0;
1858 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001859}
1860
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001861PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001862PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 int sign = 1, error_if_nonzero = 0;
1865 char *start, *orig_str = str;
1866 PyLongObject *z = NULL;
1867 PyObject *strobj;
1868 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 if ((base != 0 && base < 2) || base > 36) {
1871 PyErr_SetString(PyExc_ValueError,
1872 "int() arg 2 must be >= 2 and <= 36");
1873 return NULL;
1874 }
1875 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1876 str++;
1877 if (*str == '+')
1878 ++str;
1879 else if (*str == '-') {
1880 ++str;
1881 sign = -1;
1882 }
1883 if (base == 0) {
1884 if (str[0] != '0')
1885 base = 10;
1886 else if (str[1] == 'x' || str[1] == 'X')
1887 base = 16;
1888 else if (str[1] == 'o' || str[1] == 'O')
1889 base = 8;
1890 else if (str[1] == 'b' || str[1] == 'B')
1891 base = 2;
1892 else {
1893 /* "old" (C-style) octal literal, now invalid.
1894 it might still be zero though */
1895 error_if_nonzero = 1;
1896 base = 10;
1897 }
1898 }
1899 if (str[0] == '0' &&
1900 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1901 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1902 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1903 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 start = str;
1906 if ((base & (base - 1)) == 0)
1907 z = long_from_binary_base(&str, base);
1908 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001909/***
1910Binary bases can be converted in time linear in the number of digits, because
1911Python's representation base is binary. Other bases (including decimal!) use
1912the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001913
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914First some math: the largest integer that can be expressed in N base-B digits
1915is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1916case number of Python digits needed to hold it is the smallest integer n s.t.
1917
1918 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1919 BASE**n >= B**N [taking logs to base BASE]
1920 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1921
1922The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1923this quickly. A Python long with that much space is reserved near the start,
1924and the result is computed into it.
1925
1926The input string is actually treated as being in base base**i (i.e., i digits
1927are processed at a time), where two more static arrays hold:
1928
1929 convwidth_base[base] = the largest integer i such that base**i <= BASE
1930 convmultmax_base[base] = base ** convwidth_base[base]
1931
1932The first of these is the largest i such that i consecutive input digits
1933must fit in a single Python digit. The second is effectively the input
1934base we're really using.
1935
1936Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1937convmultmax_base[base], the result is "simply"
1938
1939 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1940
1941where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001942
1943Error analysis: as above, the number of Python digits `n` needed is worst-
1944case
1945
1946 n >= N * log(B)/log(BASE)
1947
1948where `N` is the number of input digits in base `B`. This is computed via
1949
1950 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1951
1952below. Two numeric concerns are how much space this can waste, and whether
1953the computed result can be too small. To be concrete, assume BASE = 2**15,
1954which is the default (and it's unlikely anyone changes that).
1955
1956Waste isn't a problem: provided the first input digit isn't 0, the difference
1957between the worst-case input with N digits and the smallest input with N
1958digits is about a factor of B, but B is small compared to BASE so at most
1959one allocated Python digit can remain unused on that count. If
1960N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1961and adding 1 returns a result 1 larger than necessary. However, that can't
1962happen: whenever B is a power of 2, long_from_binary_base() is called
1963instead, and it's impossible for B**i to be an integer power of 2**15 when
1964B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1965an exact integer when B is not a power of 2, since B**i has a prime factor
1966other than 2 in that case, but (2**15)**j's only prime factor is 2).
1967
1968The computed result can be too small if the true value of N*log(B)/log(BASE)
1969is a little bit larger than an exact integer, but due to roundoff errors (in
1970computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1971yields a numeric result a little less than that integer. Unfortunately, "how
1972close can a transcendental function get to an integer over some range?"
1973questions are generally theoretically intractable. Computer analysis via
1974continued fractions is practical: expand log(B)/log(BASE) via continued
1975fractions, giving a sequence i/j of "the best" rational approximations. Then
1976j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1977we can get very close to being in trouble, but very rarely. For example,
197876573 is a denominator in one of the continued-fraction approximations to
1979log(10)/log(2**15), and indeed:
1980
1981 >>> log(10)/log(2**15)*76573
1982 16958.000000654003
1983
1984is very close to an integer. If we were working with IEEE single-precision,
1985rounding errors could kill us. Finding worst cases in IEEE double-precision
1986requires better-than-double-precision log() functions, and Tim didn't bother.
1987Instead the code checks to see whether the allocated space is enough as each
1988new Python digit is added, and copies the whole thing to a larger long if not.
1989This should happen extremely rarely, and in fact I don't have a test case
1990that triggers it(!). Instead the code was tested by artificially allocating
1991just 1 digit at the start, so that the copying code was exercised for every
1992digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001993***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 register twodigits c; /* current input character */
1995 Py_ssize_t size_z;
1996 int i;
1997 int convwidth;
1998 twodigits convmultmax, convmult;
1999 digit *pz, *pzstop;
2000 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 static double log_base_BASE[37] = {0.0e0,};
2003 static int convwidth_base[37] = {0,};
2004 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (log_base_BASE[base] == 0.0) {
2007 twodigits convmax = base;
2008 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002009
Mark Dickinson22b20182010-05-10 21:27:53 +00002010 log_base_BASE[base] = (log((double)base) /
2011 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 for (;;) {
2013 twodigits next = convmax * base;
2014 if (next > PyLong_BASE)
2015 break;
2016 convmax = next;
2017 ++i;
2018 }
2019 convmultmax_base[base] = convmax;
2020 assert(i > 0);
2021 convwidth_base[base] = i;
2022 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 /* Find length of the string of numeric characters. */
2025 scan = str;
2026 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2027 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* Create a long object that can contain the largest possible
2030 * integer with this base and length. Note that there's no
2031 * need to initialize z->ob_digit -- no slot is read up before
2032 * being stored into.
2033 */
2034 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2035 /* Uncomment next line to test exceedingly rare copy code */
2036 /* size_z = 1; */
2037 assert(size_z > 0);
2038 z = _PyLong_New(size_z);
2039 if (z == NULL)
2040 return NULL;
2041 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 /* `convwidth` consecutive input digits are treated as a single
2044 * digit in base `convmultmax`.
2045 */
2046 convwidth = convwidth_base[base];
2047 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* Work ;-) */
2050 while (str < scan) {
2051 /* grab up to convwidth digits from the input string */
2052 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2053 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2054 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002055 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 assert(c < PyLong_BASE);
2057 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 convmult = convmultmax;
2060 /* Calculate the shift only if we couldn't get
2061 * convwidth digits.
2062 */
2063 if (i != convwidth) {
2064 convmult = base;
2065 for ( ; i > 1; --i)
2066 convmult *= base;
2067 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 /* Multiply z by convmult, and add c. */
2070 pz = z->ob_digit;
2071 pzstop = pz + Py_SIZE(z);
2072 for (; pz < pzstop; ++pz) {
2073 c += (twodigits)*pz * convmult;
2074 *pz = (digit)(c & PyLong_MASK);
2075 c >>= PyLong_SHIFT;
2076 }
2077 /* carry off the current end? */
2078 if (c) {
2079 assert(c < PyLong_BASE);
2080 if (Py_SIZE(z) < size_z) {
2081 *pz = (digit)c;
2082 ++Py_SIZE(z);
2083 }
2084 else {
2085 PyLongObject *tmp;
2086 /* Extremely rare. Get more space. */
2087 assert(Py_SIZE(z) == size_z);
2088 tmp = _PyLong_New(size_z + 1);
2089 if (tmp == NULL) {
2090 Py_DECREF(z);
2091 return NULL;
2092 }
2093 memcpy(tmp->ob_digit,
2094 z->ob_digit,
2095 sizeof(digit) * size_z);
2096 Py_DECREF(z);
2097 z = tmp;
2098 z->ob_digit[size_z] = (digit)c;
2099 ++size_z;
2100 }
2101 }
2102 }
2103 }
2104 if (z == NULL)
2105 return NULL;
2106 if (error_if_nonzero) {
2107 /* reset the base to 0, else the exception message
2108 doesn't make too much sense */
2109 base = 0;
2110 if (Py_SIZE(z) != 0)
2111 goto onError;
2112 /* there might still be other problems, therefore base
2113 remains zero here for the same reason */
2114 }
2115 if (str == start)
2116 goto onError;
2117 if (sign < 0)
2118 Py_SIZE(z) = -(Py_SIZE(z));
2119 while (*str && isspace(Py_CHARMASK(*str)))
2120 str++;
2121 if (*str != '\0')
2122 goto onError;
2123 if (pend)
2124 *pend = str;
2125 long_normalize(z);
2126 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002127
Mark Dickinson22b20182010-05-10 21:27:53 +00002128 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 Py_XDECREF(z);
2130 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2131 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2132 if (strobj == NULL)
2133 return NULL;
2134 PyErr_Format(PyExc_ValueError,
2135 "invalid literal for int() with base %d: %R",
2136 base, strobj);
2137 Py_DECREF(strobj);
2138 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002139}
2140
2141PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002142PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002143{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002144 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2145 if (unicode == NULL)
2146 return NULL;
2147 v = PyLong_FromUnicodeObject(unicode, base);
2148 Py_DECREF(unicode);
2149 return v;
2150}
2151
2152PyObject *
2153PyLong_FromUnicodeObject(PyObject *u, int base)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002156 PyObject *asciidig;
2157 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002160 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002161 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002163 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002164 if (buffer == NULL) {
2165 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 return NULL;
2167 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002168 result = PyLong_FromString(buffer, &end, base);
2169 if (result != NULL && end != buffer + buflen) {
2170 PyErr_SetString(PyExc_ValueError,
2171 "null byte in argument for int()");
2172 Py_DECREF(result);
2173 result = NULL;
2174 }
2175 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002177}
2178
Tim Peters9f688bf2000-07-07 15:53:28 +00002179/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002180static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002182static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183
2184/* Long division with remainder, top-level routine */
2185
Guido van Rossume32e0141992-01-19 16:31:05 +00002186static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002187long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2191 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (size_b == 0) {
2194 PyErr_SetString(PyExc_ZeroDivisionError,
2195 "integer division or modulo by zero");
2196 return -1;
2197 }
2198 if (size_a < size_b ||
2199 (size_a == size_b &&
2200 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2201 /* |a| < |b|. */
2202 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2203 if (*pdiv == NULL)
2204 return -1;
2205 Py_INCREF(a);
2206 *prem = (PyLongObject *) a;
2207 return 0;
2208 }
2209 if (size_b == 1) {
2210 digit rem = 0;
2211 z = divrem1(a, b->ob_digit[0], &rem);
2212 if (z == NULL)
2213 return -1;
2214 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2215 if (*prem == NULL) {
2216 Py_DECREF(z);
2217 return -1;
2218 }
2219 }
2220 else {
2221 z = x_divrem(a, b, prem);
2222 if (z == NULL)
2223 return -1;
2224 }
2225 /* Set the signs.
2226 The quotient z has the sign of a*b;
2227 the remainder r has the sign of a,
2228 so a = b*z + r. */
2229 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2230 NEGATE(z);
2231 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2232 NEGATE(*prem);
2233 *pdiv = maybe_small_long(z);
2234 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002235}
2236
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002237/* Unsigned long division with remainder -- the algorithm. The arguments v1
2238 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002239
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002240static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002241x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 PyLongObject *v, *w, *a;
2244 Py_ssize_t i, k, size_v, size_w;
2245 int d;
2246 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2247 twodigits vv;
2248 sdigit zhi;
2249 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2252 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2253 handle the special case when the initial estimate q for a quotient
2254 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2255 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 /* allocate space; w will also be used to hold the final remainder */
2258 size_v = ABS(Py_SIZE(v1));
2259 size_w = ABS(Py_SIZE(w1));
2260 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2261 v = _PyLong_New(size_v+1);
2262 if (v == NULL) {
2263 *prem = NULL;
2264 return NULL;
2265 }
2266 w = _PyLong_New(size_w);
2267 if (w == NULL) {
2268 Py_DECREF(v);
2269 *prem = NULL;
2270 return NULL;
2271 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2274 shift v1 left by the same amount. Results go into w and v. */
2275 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2276 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2277 assert(carry == 0);
2278 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2279 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2280 v->ob_digit[size_v] = carry;
2281 size_v++;
2282 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2285 at most (and usually exactly) k = size_v - size_w digits. */
2286 k = size_v - size_w;
2287 assert(k >= 0);
2288 a = _PyLong_New(k);
2289 if (a == NULL) {
2290 Py_DECREF(w);
2291 Py_DECREF(v);
2292 *prem = NULL;
2293 return NULL;
2294 }
2295 v0 = v->ob_digit;
2296 w0 = w->ob_digit;
2297 wm1 = w0[size_w-1];
2298 wm2 = w0[size_w-2];
2299 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2300 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2301 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002304 Py_DECREF(a);
2305 Py_DECREF(w);
2306 Py_DECREF(v);
2307 *prem = NULL;
2308 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002309 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* estimate quotient digit q; may overestimate by 1 (rare) */
2312 vtop = vk[size_w];
2313 assert(vtop <= wm1);
2314 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2315 q = (digit)(vv / wm1);
2316 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2317 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2318 | vk[size_w-2])) {
2319 --q;
2320 r += wm1;
2321 if (r >= PyLong_BASE)
2322 break;
2323 }
2324 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2327 zhi = 0;
2328 for (i = 0; i < size_w; ++i) {
2329 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2330 -PyLong_BASE * q <= z < PyLong_BASE */
2331 z = (sdigit)vk[i] + zhi -
2332 (stwodigits)q * (stwodigits)w0[i];
2333 vk[i] = (digit)z & PyLong_MASK;
2334 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002335 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* add w back if q was too large (this branch taken rarely) */
2339 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2340 if ((sdigit)vtop + zhi < 0) {
2341 carry = 0;
2342 for (i = 0; i < size_w; ++i) {
2343 carry += vk[i] + w0[i];
2344 vk[i] = carry & PyLong_MASK;
2345 carry >>= PyLong_SHIFT;
2346 }
2347 --q;
2348 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* store quotient digit */
2351 assert(q < PyLong_BASE);
2352 *--ak = q;
2353 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* unshift remainder; we reuse w to store the result */
2356 carry = v_rshift(w0, v0, size_w, d);
2357 assert(carry==0);
2358 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 *prem = long_normalize(w);
2361 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002362}
2363
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002364/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2365 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2366 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2367 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2368 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2369 -1.0. */
2370
2371/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2372#if DBL_MANT_DIG == 53
2373#define EXP2_DBL_MANT_DIG 9007199254740992.0
2374#else
2375#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2376#endif
2377
2378double
2379_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2382 /* See below for why x_digits is always large enough. */
2383 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2384 double dx;
2385 /* Correction term for round-half-to-even rounding. For a digit x,
2386 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2387 multiple of 4, rounding ties to a multiple of 8. */
2388 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 a_size = ABS(Py_SIZE(a));
2391 if (a_size == 0) {
2392 /* Special case for 0: significand 0.0, exponent 0. */
2393 *e = 0;
2394 return 0.0;
2395 }
2396 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2397 /* The following is an overflow-free version of the check
2398 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2399 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2400 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2401 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002402 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2406 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 Number of digits needed for result: write // for floor division.
2409 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2418 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2421 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2422 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 in both cases.
2429 */
2430 if (a_bits <= DBL_MANT_DIG + 2) {
2431 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2432 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2433 x_size = 0;
2434 while (x_size < shift_digits)
2435 x_digits[x_size++] = 0;
2436 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2437 (int)shift_bits);
2438 x_size += a_size;
2439 x_digits[x_size++] = rem;
2440 }
2441 else {
2442 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2443 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2444 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2445 a_size - shift_digits, (int)shift_bits);
2446 x_size = a_size - shift_digits;
2447 /* For correct rounding below, we need the least significant
2448 bit of x to be 'sticky' for this shift: if any of the bits
2449 shifted out was nonzero, we set the least significant bit
2450 of x. */
2451 if (rem)
2452 x_digits[0] |= 1;
2453 else
2454 while (shift_digits > 0)
2455 if (a->ob_digit[--shift_digits]) {
2456 x_digits[0] |= 1;
2457 break;
2458 }
2459 }
Victor Stinner63941882011-09-29 00:42:28 +02002460 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* Round, and convert to double. */
2463 x_digits[0] += half_even_correction[x_digits[0] & 7];
2464 dx = x_digits[--x_size];
2465 while (x_size > 0)
2466 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* Rescale; make correction if result is 1.0. */
2469 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2470 if (dx == 1.0) {
2471 if (a_bits == PY_SSIZE_T_MAX)
2472 goto overflow;
2473 dx = 0.5;
2474 a_bits += 1;
2475 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 *e = a_bits;
2478 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002479
2480 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* exponent > PY_SSIZE_T_MAX */
2482 PyErr_SetString(PyExc_OverflowError,
2483 "huge integer: number of bits overflows a Py_ssize_t");
2484 *e = 0;
2485 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002486}
2487
2488/* Get a C double from a long int object. Rounds to the nearest double,
2489 using the round-half-to-even rule in the case of a tie. */
2490
2491double
2492PyLong_AsDouble(PyObject *v)
2493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 Py_ssize_t exponent;
2495 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002496
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002497 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 PyErr_BadInternalCall();
2499 return -1.0;
2500 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002501 if (!PyLong_Check(v)) {
2502 PyErr_SetString(PyExc_TypeError, "an integer is required");
2503 return -1.0;
2504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2506 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2507 PyErr_SetString(PyExc_OverflowError,
2508 "long int too large to convert to float");
2509 return -1.0;
2510 }
2511 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002512}
2513
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002514/* Methods */
2515
2516static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002517long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002520}
2521
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002522static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002523long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 if (Py_SIZE(a) != Py_SIZE(b)) {
2528 sign = Py_SIZE(a) - Py_SIZE(b);
2529 }
2530 else {
2531 Py_ssize_t i = ABS(Py_SIZE(a));
2532 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2533 ;
2534 if (i < 0)
2535 sign = 0;
2536 else {
2537 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2538 if (Py_SIZE(a) < 0)
2539 sign = -sign;
2540 }
2541 }
2542 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002543}
2544
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002545#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002547
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002548static PyObject *
2549long_richcompare(PyObject *self, PyObject *other, int op)
2550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 int result;
2552 PyObject *v;
2553 CHECK_BINOP(self, other);
2554 if (self == other)
2555 result = 0;
2556 else
2557 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2558 /* Convert the return value to a Boolean */
2559 switch (op) {
2560 case Py_EQ:
2561 v = TEST_COND(result == 0);
2562 break;
2563 case Py_NE:
2564 v = TEST_COND(result != 0);
2565 break;
2566 case Py_LE:
2567 v = TEST_COND(result <= 0);
2568 break;
2569 case Py_GE:
2570 v = TEST_COND(result >= 0);
2571 break;
2572 case Py_LT:
2573 v = TEST_COND(result == -1);
2574 break;
2575 case Py_GT:
2576 v = TEST_COND(result == 1);
2577 break;
2578 default:
2579 PyErr_BadArgument();
2580 return NULL;
2581 }
2582 Py_INCREF(v);
2583 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002584}
2585
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002586static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002587long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002588{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002589 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 Py_ssize_t i;
2591 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 i = Py_SIZE(v);
2594 switch(i) {
2595 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2596 case 0: return 0;
2597 case 1: return v->ob_digit[0];
2598 }
2599 sign = 1;
2600 x = 0;
2601 if (i < 0) {
2602 sign = -1;
2603 i = -(i);
2604 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002606 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2607 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2608 _PyHASH_MODULUS.
2609
2610 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2611 amounts to a rotation of the bits of x. To see this, write
2612
2613 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2614
2615 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2616 PyLong_SHIFT bits of x (those that are shifted out of the
2617 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2618 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2619 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2620 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2621 congruent to y modulo _PyHASH_MODULUS. So
2622
2623 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2624
2625 The right-hand side is just the result of rotating the
2626 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2627 not all _PyHASH_BITS bits of x are 1s, the same is true
2628 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2629 the reduction of x*2**PyLong_SHIFT modulo
2630 _PyHASH_MODULUS. */
2631 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2632 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002634 if (x >= _PyHASH_MODULUS)
2635 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 }
2637 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002638 if (x == (Py_uhash_t)-1)
2639 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002640 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002641}
2642
2643
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002644/* Add the absolute values of two long integers. */
2645
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002646static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002647x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2650 PyLongObject *z;
2651 Py_ssize_t i;
2652 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 /* Ensure a is the larger of the two: */
2655 if (size_a < size_b) {
2656 { PyLongObject *temp = a; a = b; b = temp; }
2657 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002658 size_a = size_b;
2659 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 }
2661 z = _PyLong_New(size_a+1);
2662 if (z == NULL)
2663 return NULL;
2664 for (i = 0; i < size_b; ++i) {
2665 carry += a->ob_digit[i] + b->ob_digit[i];
2666 z->ob_digit[i] = carry & PyLong_MASK;
2667 carry >>= PyLong_SHIFT;
2668 }
2669 for (; i < size_a; ++i) {
2670 carry += a->ob_digit[i];
2671 z->ob_digit[i] = carry & PyLong_MASK;
2672 carry >>= PyLong_SHIFT;
2673 }
2674 z->ob_digit[i] = carry;
2675 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002676}
2677
2678/* Subtract the absolute values of two integers. */
2679
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002680static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002681x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2684 PyLongObject *z;
2685 Py_ssize_t i;
2686 int sign = 1;
2687 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 /* Ensure a is the larger of the two: */
2690 if (size_a < size_b) {
2691 sign = -1;
2692 { PyLongObject *temp = a; a = b; b = temp; }
2693 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002694 size_a = size_b;
2695 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 }
2697 else if (size_a == size_b) {
2698 /* Find highest digit where a and b differ: */
2699 i = size_a;
2700 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2701 ;
2702 if (i < 0)
2703 return (PyLongObject *)PyLong_FromLong(0);
2704 if (a->ob_digit[i] < b->ob_digit[i]) {
2705 sign = -1;
2706 { PyLongObject *temp = a; a = b; b = temp; }
2707 }
2708 size_a = size_b = i+1;
2709 }
2710 z = _PyLong_New(size_a);
2711 if (z == NULL)
2712 return NULL;
2713 for (i = 0; i < size_b; ++i) {
2714 /* The following assumes unsigned arithmetic
2715 works module 2**N for some N>PyLong_SHIFT. */
2716 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2717 z->ob_digit[i] = borrow & PyLong_MASK;
2718 borrow >>= PyLong_SHIFT;
2719 borrow &= 1; /* Keep only one sign bit */
2720 }
2721 for (; i < size_a; ++i) {
2722 borrow = a->ob_digit[i] - borrow;
2723 z->ob_digit[i] = borrow & PyLong_MASK;
2724 borrow >>= PyLong_SHIFT;
2725 borrow &= 1; /* Keep only one sign bit */
2726 }
2727 assert(borrow == 0);
2728 if (sign < 0)
2729 NEGATE(z);
2730 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002731}
2732
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002733static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002734long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2741 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2742 MEDIUM_VALUE(b));
2743 return result;
2744 }
2745 if (Py_SIZE(a) < 0) {
2746 if (Py_SIZE(b) < 0) {
2747 z = x_add(a, b);
2748 if (z != NULL && Py_SIZE(z) != 0)
2749 Py_SIZE(z) = -(Py_SIZE(z));
2750 }
2751 else
2752 z = x_sub(b, a);
2753 }
2754 else {
2755 if (Py_SIZE(b) < 0)
2756 z = x_sub(a, b);
2757 else
2758 z = x_add(a, b);
2759 }
2760 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002761}
2762
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002763static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002764long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2771 PyObject* r;
2772 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2773 return r;
2774 }
2775 if (Py_SIZE(a) < 0) {
2776 if (Py_SIZE(b) < 0)
2777 z = x_sub(a, b);
2778 else
2779 z = x_add(a, b);
2780 if (z != NULL && Py_SIZE(z) != 0)
2781 Py_SIZE(z) = -(Py_SIZE(z));
2782 }
2783 else {
2784 if (Py_SIZE(b) < 0)
2785 z = x_add(a, b);
2786 else
2787 z = x_sub(a, b);
2788 }
2789 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002790}
2791
Tim Peters5af4e6c2002-08-12 02:31:19 +00002792/* Grade school multiplication, ignoring the signs.
2793 * Returns the absolute value of the product, or NULL if error.
2794 */
2795static PyLongObject *
2796x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 PyLongObject *z;
2799 Py_ssize_t size_a = ABS(Py_SIZE(a));
2800 Py_ssize_t size_b = ABS(Py_SIZE(b));
2801 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 z = _PyLong_New(size_a + size_b);
2804 if (z == NULL)
2805 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2808 if (a == b) {
2809 /* Efficient squaring per HAC, Algorithm 14.16:
2810 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2811 * Gives slightly less than a 2x speedup when a == b,
2812 * via exploiting that each entry in the multiplication
2813 * pyramid appears twice (except for the size_a squares).
2814 */
2815 for (i = 0; i < size_a; ++i) {
2816 twodigits carry;
2817 twodigits f = a->ob_digit[i];
2818 digit *pz = z->ob_digit + (i << 1);
2819 digit *pa = a->ob_digit + i + 1;
2820 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002823 Py_DECREF(z);
2824 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002825 });
Tim Peters0973b992004-08-29 22:16:50 +00002826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 carry = *pz + f * f;
2828 *pz++ = (digit)(carry & PyLong_MASK);
2829 carry >>= PyLong_SHIFT;
2830 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 /* Now f is added in twice in each column of the
2833 * pyramid it appears. Same as adding f<<1 once.
2834 */
2835 f <<= 1;
2836 while (pa < paend) {
2837 carry += *pz + *pa++ * f;
2838 *pz++ = (digit)(carry & PyLong_MASK);
2839 carry >>= PyLong_SHIFT;
2840 assert(carry <= (PyLong_MASK << 1));
2841 }
2842 if (carry) {
2843 carry += *pz;
2844 *pz++ = (digit)(carry & PyLong_MASK);
2845 carry >>= PyLong_SHIFT;
2846 }
2847 if (carry)
2848 *pz += (digit)(carry & PyLong_MASK);
2849 assert((carry >> PyLong_SHIFT) == 0);
2850 }
2851 }
2852 else { /* a is not the same as b -- gradeschool long mult */
2853 for (i = 0; i < size_a; ++i) {
2854 twodigits carry = 0;
2855 twodigits f = a->ob_digit[i];
2856 digit *pz = z->ob_digit + i;
2857 digit *pb = b->ob_digit;
2858 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002861 Py_DECREF(z);
2862 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002863 });
Tim Peters0973b992004-08-29 22:16:50 +00002864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 while (pb < pbend) {
2866 carry += *pz + *pb++ * f;
2867 *pz++ = (digit)(carry & PyLong_MASK);
2868 carry >>= PyLong_SHIFT;
2869 assert(carry <= PyLong_MASK);
2870 }
2871 if (carry)
2872 *pz += (digit)(carry & PyLong_MASK);
2873 assert((carry >> PyLong_SHIFT) == 0);
2874 }
2875 }
2876 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002877}
2878
2879/* A helper for Karatsuba multiplication (k_mul).
2880 Takes a long "n" and an integer "size" representing the place to
2881 split, and sets low and high such that abs(n) == (high << size) + low,
2882 viewing the shift as being by digits. The sign bit is ignored, and
2883 the return values are >= 0.
2884 Returns 0 on success, -1 on failure.
2885*/
2886static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002887kmul_split(PyLongObject *n,
2888 Py_ssize_t size,
2889 PyLongObject **high,
2890 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyLongObject *hi, *lo;
2893 Py_ssize_t size_lo, size_hi;
2894 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 size_lo = MIN(size_n, size);
2897 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 if ((hi = _PyLong_New(size_hi)) == NULL)
2900 return -1;
2901 if ((lo = _PyLong_New(size_lo)) == NULL) {
2902 Py_DECREF(hi);
2903 return -1;
2904 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2907 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 *high = long_normalize(hi);
2910 *low = long_normalize(lo);
2911 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002912}
2913
Tim Peters60004642002-08-12 22:01:34 +00002914static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2915
Tim Peters5af4e6c2002-08-12 02:31:19 +00002916/* Karatsuba multiplication. Ignores the input signs, and returns the
2917 * absolute value of the product (or NULL if error).
2918 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2919 */
2920static PyLongObject *
2921k_mul(PyLongObject *a, PyLongObject *b)
2922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 Py_ssize_t asize = ABS(Py_SIZE(a));
2924 Py_ssize_t bsize = ABS(Py_SIZE(b));
2925 PyLongObject *ah = NULL;
2926 PyLongObject *al = NULL;
2927 PyLongObject *bh = NULL;
2928 PyLongObject *bl = NULL;
2929 PyLongObject *ret = NULL;
2930 PyLongObject *t1, *t2, *t3;
2931 Py_ssize_t shift; /* the number of digits we split off */
2932 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2935 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2936 * Then the original product is
2937 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2938 * By picking X to be a power of 2, "*X" is just shifting, and it's
2939 * been reduced to 3 multiplies on numbers half the size.
2940 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 /* We want to split based on the larger number; fiddle so that b
2943 * is largest.
2944 */
2945 if (asize > bsize) {
2946 t1 = a;
2947 a = b;
2948 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 i = asize;
2951 asize = bsize;
2952 bsize = i;
2953 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 /* Use gradeschool math when either number is too small. */
2956 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2957 if (asize <= i) {
2958 if (asize == 0)
2959 return (PyLongObject *)PyLong_FromLong(0);
2960 else
2961 return x_mul(a, b);
2962 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 /* If a is small compared to b, splitting on b gives a degenerate
2965 * case with ah==0, and Karatsuba may be (even much) less efficient
2966 * than "grade school" then. However, we can still win, by viewing
2967 * b as a string of "big digits", each of width a->ob_size. That
2968 * leads to a sequence of balanced calls to k_mul.
2969 */
2970 if (2 * asize <= bsize)
2971 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 /* Split a & b into hi & lo pieces. */
2974 shift = bsize >> 1;
2975 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2976 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 if (a == b) {
2979 bh = ah;
2980 bl = al;
2981 Py_INCREF(bh);
2982 Py_INCREF(bl);
2983 }
2984 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 /* The plan:
2987 * 1. Allocate result space (asize + bsize digits: that's always
2988 * enough).
2989 * 2. Compute ah*bh, and copy into result at 2*shift.
2990 * 3. Compute al*bl, and copy into result at 0. Note that this
2991 * can't overlap with #2.
2992 * 4. Subtract al*bl from the result, starting at shift. This may
2993 * underflow (borrow out of the high digit), but we don't care:
2994 * we're effectively doing unsigned arithmetic mod
2995 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2996 * borrows and carries out of the high digit can be ignored.
2997 * 5. Subtract ah*bh from the result, starting at shift.
2998 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2999 * at shift.
3000 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 /* 1. Allocate result space. */
3003 ret = _PyLong_New(asize + bsize);
3004 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003005#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* Fill with trash, to catch reference to uninitialized digits. */
3007 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003008#endif
Tim Peters44121a62002-08-12 06:17:58 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3011 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3012 assert(Py_SIZE(t1) >= 0);
3013 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3014 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3015 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003017 /* Zero-out the digits higher than the ah*bh copy. */
3018 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3019 if (i)
3020 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3021 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 /* 3. t2 <- al*bl, and copy into the low digits. */
3024 if ((t2 = k_mul(al, bl)) == NULL) {
3025 Py_DECREF(t1);
3026 goto fail;
3027 }
3028 assert(Py_SIZE(t2) >= 0);
3029 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3030 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 /* Zero out remaining digits. */
3033 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3034 if (i)
3035 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3038 * because it's fresher in cache.
3039 */
3040 i = Py_SIZE(ret) - shift; /* # digits after shift */
3041 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3042 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3045 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3048 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3049 Py_DECREF(ah);
3050 Py_DECREF(al);
3051 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 if (a == b) {
3054 t2 = t1;
3055 Py_INCREF(t2);
3056 }
3057 else if ((t2 = x_add(bh, bl)) == NULL) {
3058 Py_DECREF(t1);
3059 goto fail;
3060 }
3061 Py_DECREF(bh);
3062 Py_DECREF(bl);
3063 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 t3 = k_mul(t1, t2);
3066 Py_DECREF(t1);
3067 Py_DECREF(t2);
3068 if (t3 == NULL) goto fail;
3069 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 /* Add t3. It's not obvious why we can't run out of room here.
3072 * See the (*) comment after this function.
3073 */
3074 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3075 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003078
Mark Dickinson22b20182010-05-10 21:27:53 +00003079 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 Py_XDECREF(ret);
3081 Py_XDECREF(ah);
3082 Py_XDECREF(al);
3083 Py_XDECREF(bh);
3084 Py_XDECREF(bl);
3085 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003086}
3087
Tim Petersd6974a52002-08-13 20:37:51 +00003088/* (*) Why adding t3 can't "run out of room" above.
3089
Tim Petersab86c2b2002-08-15 20:06:00 +00003090Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3091to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003092
Tim Petersab86c2b2002-08-15 20:06:00 +000030931. For any integer i, i = c(i/2) + f(i/2). In particular,
3094 bsize = c(bsize/2) + f(bsize/2).
30952. shift = f(bsize/2)
30963. asize <= bsize
30974. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3098 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003099
Tim Petersab86c2b2002-08-15 20:06:00 +00003100We allocated asize + bsize result digits, and add t3 into them at an offset
3101of shift. This leaves asize+bsize-shift allocated digit positions for t3
3102to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3103asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003104
Tim Petersab86c2b2002-08-15 20:06:00 +00003105bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3106at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003107
Tim Petersab86c2b2002-08-15 20:06:00 +00003108If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3109digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3110most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003111
Tim Petersab86c2b2002-08-15 20:06:00 +00003112The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003113
Tim Petersab86c2b2002-08-15 20:06:00 +00003114 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003115
Tim Petersab86c2b2002-08-15 20:06:00 +00003116and we have asize + c(bsize/2) available digit positions. We need to show
3117this is always enough. An instance of c(bsize/2) cancels out in both, so
3118the question reduces to whether asize digits is enough to hold
3119(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3120then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3121asize 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 +00003122digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003123asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003124c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3125is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3126bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003127
Tim Peters48d52c02002-08-14 17:07:32 +00003128Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3129clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3130ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003131*/
3132
Tim Peters60004642002-08-12 22:01:34 +00003133/* b has at least twice the digits of a, and a is big enough that Karatsuba
3134 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3135 * of slices, each with a->ob_size digits, and multiply the slices by a,
3136 * one at a time. This gives k_mul balanced inputs to work with, and is
3137 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003138 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003139 * single-width slice overlap between successive partial sums).
3140 */
3141static PyLongObject *
3142k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 const Py_ssize_t asize = ABS(Py_SIZE(a));
3145 Py_ssize_t bsize = ABS(Py_SIZE(b));
3146 Py_ssize_t nbdone; /* # of b digits already multiplied */
3147 PyLongObject *ret;
3148 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 assert(asize > KARATSUBA_CUTOFF);
3151 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* Allocate result space, and zero it out. */
3154 ret = _PyLong_New(asize + bsize);
3155 if (ret == NULL)
3156 return NULL;
3157 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* Successive slices of b are copied into bslice. */
3160 bslice = _PyLong_New(asize);
3161 if (bslice == NULL)
3162 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 nbdone = 0;
3165 while (bsize > 0) {
3166 PyLongObject *product;
3167 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 /* Multiply the next slice of b by a. */
3170 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3171 nbtouse * sizeof(digit));
3172 Py_SIZE(bslice) = nbtouse;
3173 product = k_mul(a, bslice);
3174 if (product == NULL)
3175 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 /* Add into result. */
3178 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3179 product->ob_digit, Py_SIZE(product));
3180 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 bsize -= nbtouse;
3183 nbdone += nbtouse;
3184 }
Tim Peters60004642002-08-12 22:01:34 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 Py_DECREF(bslice);
3187 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003188
Mark Dickinson22b20182010-05-10 21:27:53 +00003189 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 Py_DECREF(ret);
3191 Py_XDECREF(bslice);
3192 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003193}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003194
3195static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003196long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 /* fast path for single-digit multiplication */
3203 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3204 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003205#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003207#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* if we don't have long long then we're almost certainly
3209 using 15-bit digits, so v will fit in a long. In the
3210 unlikely event that we're using 30-bit digits on a platform
3211 without long long, a large v will just cause us to fall
3212 through to the general multiplication code below. */
3213 if (v >= LONG_MIN && v <= LONG_MAX)
3214 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003215#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 z = k_mul(a, b);
3219 /* Negate if exactly one of the inputs is negative. */
3220 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3221 NEGATE(z);
3222 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003223}
3224
Guido van Rossume32e0141992-01-19 16:31:05 +00003225/* The / and % operators are now defined in terms of divmod().
3226 The expression a mod b has the value a - b*floor(a/b).
3227 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003228 |a| by |b|, with the sign of a. This is also expressed
3229 as a - b*trunc(a/b), if trunc truncates towards zero.
3230 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 a b a rem b a mod b
3232 13 10 3 3
3233 -13 10 -3 7
3234 13 -10 3 -7
3235 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003236 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003237 have different signs. We then subtract one from the 'div'
3238 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003239
Tim Peters47e52ee2004-08-30 02:44:38 +00003240/* Compute
3241 * *pdiv, *pmod = divmod(v, w)
3242 * NULL can be passed for pdiv or pmod, in which case that part of
3243 * the result is simply thrown away. The caller owns a reference to
3244 * each of these it requests (does not pass NULL for).
3245 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003246static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003247l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 if (long_divrem(v, w, &div, &mod) < 0)
3253 return -1;
3254 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3255 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3256 PyLongObject *temp;
3257 PyLongObject *one;
3258 temp = (PyLongObject *) long_add(mod, w);
3259 Py_DECREF(mod);
3260 mod = temp;
3261 if (mod == NULL) {
3262 Py_DECREF(div);
3263 return -1;
3264 }
3265 one = (PyLongObject *) PyLong_FromLong(1L);
3266 if (one == NULL ||
3267 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3268 Py_DECREF(mod);
3269 Py_DECREF(div);
3270 Py_XDECREF(one);
3271 return -1;
3272 }
3273 Py_DECREF(one);
3274 Py_DECREF(div);
3275 div = temp;
3276 }
3277 if (pdiv != NULL)
3278 *pdiv = div;
3279 else
3280 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 if (pmod != NULL)
3283 *pmod = mod;
3284 else
3285 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003288}
3289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003290static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003291long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 CHECK_BINOP(a, b);
3296 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3297 div = NULL;
3298 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003299}
3300
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003301/* PyLong/PyLong -> float, with correctly rounded result. */
3302
3303#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3304#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3305
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003306static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003307long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 PyLongObject *a, *b, *x;
3310 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3311 digit mask, low;
3312 int inexact, negate, a_is_small, b_is_small;
3313 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 CHECK_BINOP(v, w);
3316 a = (PyLongObject *)v;
3317 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 /*
3320 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3323 1. choose a suitable integer 'shift'
3324 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3325 3. adjust x for correct rounding
3326 4. convert x to a double dx with the same value
3327 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3332 returns either 0.0 or -0.0, depending on the sign of b. For a and
3333 b both nonzero, ignore signs of a and b, and add the sign back in
3334 at the end. Now write a_bits and b_bits for the bit lengths of a
3335 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3336 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3341 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3342 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3343 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 1. The integer 'shift' is chosen so that x has the right number of
3348 bits for a double, plus two or three extra bits that will be used
3349 in the rounding decisions. Writing a_bits and b_bits for the
3350 number of significant bits in a and b respectively, a
3351 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 This is fine in the usual case, but if a/b is smaller than the
3356 smallest normal float then it can lead to double rounding on an
3357 IEEE 754 platform, giving incorrectly rounded results. So we
3358 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 2. The quantity x is computed by first shifting a (left -shift bits
3363 if shift <= 0, right shift bits if shift > 0) and then dividing by
3364 b. For both the shift and the division, we keep track of whether
3365 the result is inexact, in a flag 'inexact'; this information is
3366 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 With the choice of shift above, together with our assumption that
3369 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3370 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3373 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 For float representability, we need x/2**extra_bits <
3378 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3379 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 To round, we just modify the bottom digit of x in-place; this can
3384 end up giving a digit with value > PyLONG_MASK, but that's not a
3385 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 With the original choices for shift above, extra_bits will always
3388 be 2 or 3. Then rounding under the round-half-to-even rule, we
3389 round up iff the most significant of the extra bits is 1, and
3390 either: (a) the computation of x in step 2 had an inexact result,
3391 or (b) at least one other of the extra bits is 1, or (c) the least
3392 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 4. Conversion to a double is straightforward; all floating-point
3395 operations involved in the conversion are exact, so there's no
3396 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3399 The result will always be exactly representable as a double, except
3400 in the case that it overflows. To avoid dependence on the exact
3401 behaviour of ldexp on overflow, we check for overflow before
3402 applying ldexp. The result of ldexp is adjusted for sign before
3403 returning.
3404 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 /* Reduce to case where a and b are both positive. */
3407 a_size = ABS(Py_SIZE(a));
3408 b_size = ABS(Py_SIZE(b));
3409 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3410 if (b_size == 0) {
3411 PyErr_SetString(PyExc_ZeroDivisionError,
3412 "division by zero");
3413 goto error;
3414 }
3415 if (a_size == 0)
3416 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 /* Fast path for a and b small (exactly representable in a double).
3419 Relies on floating-point division being correctly rounded; results
3420 may be subject to double rounding on x86 machines that operate with
3421 the x87 FPU set to 64-bit precision. */
3422 a_is_small = a_size <= MANT_DIG_DIGITS ||
3423 (a_size == MANT_DIG_DIGITS+1 &&
3424 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3425 b_is_small = b_size <= MANT_DIG_DIGITS ||
3426 (b_size == MANT_DIG_DIGITS+1 &&
3427 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3428 if (a_is_small && b_is_small) {
3429 double da, db;
3430 da = a->ob_digit[--a_size];
3431 while (a_size > 0)
3432 da = da * PyLong_BASE + a->ob_digit[--a_size];
3433 db = b->ob_digit[--b_size];
3434 while (b_size > 0)
3435 db = db * PyLong_BASE + b->ob_digit[--b_size];
3436 result = da / db;
3437 goto success;
3438 }
Tim Peterse2a60002001-09-04 06:17:36 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 /* Catch obvious cases of underflow and overflow */
3441 diff = a_size - b_size;
3442 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3443 /* Extreme overflow */
3444 goto overflow;
3445 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3446 /* Extreme underflow */
3447 goto underflow_or_zero;
3448 /* Next line is now safe from overflowing a Py_ssize_t */
3449 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3450 bits_in_digit(b->ob_digit[b_size - 1]);
3451 /* Now diff = a_bits - b_bits. */
3452 if (diff > DBL_MAX_EXP)
3453 goto overflow;
3454 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3455 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 /* Choose value for shift; see comments for step 1 above. */
3458 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 /* x = abs(a * 2**-shift) */
3463 if (shift <= 0) {
3464 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3465 digit rem;
3466 /* x = a << -shift */
3467 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3468 /* In practice, it's probably impossible to end up
3469 here. Both a and b would have to be enormous,
3470 using close to SIZE_T_MAX bytes of memory each. */
3471 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003472 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 goto error;
3474 }
3475 x = _PyLong_New(a_size + shift_digits + 1);
3476 if (x == NULL)
3477 goto error;
3478 for (i = 0; i < shift_digits; i++)
3479 x->ob_digit[i] = 0;
3480 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3481 a_size, -shift % PyLong_SHIFT);
3482 x->ob_digit[a_size + shift_digits] = rem;
3483 }
3484 else {
3485 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3486 digit rem;
3487 /* x = a >> shift */
3488 assert(a_size >= shift_digits);
3489 x = _PyLong_New(a_size - shift_digits);
3490 if (x == NULL)
3491 goto error;
3492 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3493 a_size - shift_digits, shift % PyLong_SHIFT);
3494 /* set inexact if any of the bits shifted out is nonzero */
3495 if (rem)
3496 inexact = 1;
3497 while (!inexact && shift_digits > 0)
3498 if (a->ob_digit[--shift_digits])
3499 inexact = 1;
3500 }
3501 long_normalize(x);
3502 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3505 reference to x, so it's safe to modify it in-place. */
3506 if (b_size == 1) {
3507 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3508 b->ob_digit[0]);
3509 long_normalize(x);
3510 if (rem)
3511 inexact = 1;
3512 }
3513 else {
3514 PyLongObject *div, *rem;
3515 div = x_divrem(x, b, &rem);
3516 Py_DECREF(x);
3517 x = div;
3518 if (x == NULL)
3519 goto error;
3520 if (Py_SIZE(rem))
3521 inexact = 1;
3522 Py_DECREF(rem);
3523 }
3524 x_size = ABS(Py_SIZE(x));
3525 assert(x_size > 0); /* result of division is never zero */
3526 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /* The number of extra bits that have to be rounded away. */
3529 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3530 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 /* Round by directly modifying the low digit of x. */
3533 mask = (digit)1 << (extra_bits - 1);
3534 low = x->ob_digit[0] | inexact;
3535 if (low & mask && low & (3*mask-1))
3536 low += mask;
3537 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 /* Convert x to a double dx; the conversion is exact. */
3540 dx = x->ob_digit[--x_size];
3541 while (x_size > 0)
3542 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3543 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 /* Check whether ldexp result will overflow a double. */
3546 if (shift + x_bits >= DBL_MAX_EXP &&
3547 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3548 goto overflow;
3549 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003550
3551 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003553
3554 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003556
3557 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 PyErr_SetString(PyExc_OverflowError,
3559 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003560 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003562}
3563
3564static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003565long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 CHECK_BINOP(a, b);
3570
3571 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3572 mod = NULL;
3573 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003574}
3575
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003576static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003577long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 PyLongObject *div, *mod;
3580 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3585 return NULL;
3586 }
3587 z = PyTuple_New(2);
3588 if (z != NULL) {
3589 PyTuple_SetItem(z, 0, (PyObject *) div);
3590 PyTuple_SetItem(z, 1, (PyObject *) mod);
3591 }
3592 else {
3593 Py_DECREF(div);
3594 Py_DECREF(mod);
3595 }
3596 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003597}
3598
Tim Peters47e52ee2004-08-30 02:44:38 +00003599/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003600static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003601long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3604 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 PyLongObject *z = NULL; /* accumulated result */
3607 Py_ssize_t i, j, k; /* counters */
3608 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 /* 5-ary values. If the exponent is large enough, table is
3611 * precomputed so that table[i] == a**i % c for i in range(32).
3612 */
3613 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3614 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 /* a, b, c = v, w, x */
3617 CHECK_BINOP(v, w);
3618 a = (PyLongObject*)v; Py_INCREF(a);
3619 b = (PyLongObject*)w; Py_INCREF(b);
3620 if (PyLong_Check(x)) {
3621 c = (PyLongObject *)x;
3622 Py_INCREF(x);
3623 }
3624 else if (x == Py_None)
3625 c = NULL;
3626 else {
3627 Py_DECREF(a);
3628 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003629 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 }
Tim Peters4c483c42001-09-05 06:24:58 +00003631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3633 if (c) {
3634 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003635 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 goto Error;
3637 }
3638 else {
3639 /* else return a float. This works because we know
3640 that this calls float_pow() which converts its
3641 arguments to double. */
3642 Py_DECREF(a);
3643 Py_DECREF(b);
3644 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3645 }
3646 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 if (c) {
3649 /* if modulus == 0:
3650 raise ValueError() */
3651 if (Py_SIZE(c) == 0) {
3652 PyErr_SetString(PyExc_ValueError,
3653 "pow() 3rd argument cannot be 0");
3654 goto Error;
3655 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 /* if modulus < 0:
3658 negativeOutput = True
3659 modulus = -modulus */
3660 if (Py_SIZE(c) < 0) {
3661 negativeOutput = 1;
3662 temp = (PyLongObject *)_PyLong_Copy(c);
3663 if (temp == NULL)
3664 goto Error;
3665 Py_DECREF(c);
3666 c = temp;
3667 temp = NULL;
3668 NEGATE(c);
3669 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 /* if modulus == 1:
3672 return 0 */
3673 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3674 z = (PyLongObject *)PyLong_FromLong(0L);
3675 goto Done;
3676 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 /* if base < 0:
3679 base = base % modulus
3680 Having the base positive just makes things easier. */
3681 if (Py_SIZE(a) < 0) {
3682 if (l_divmod(a, c, NULL, &temp) < 0)
3683 goto Error;
3684 Py_DECREF(a);
3685 a = temp;
3686 temp = NULL;
3687 }
3688 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 /* At this point a, b, and c are guaranteed non-negative UNLESS
3691 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 z = (PyLongObject *)PyLong_FromLong(1L);
3694 if (z == NULL)
3695 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 /* Perform a modular reduction, X = X % c, but leave X alone if c
3698 * is NULL.
3699 */
3700#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003701 do { \
3702 if (c != NULL) { \
3703 if (l_divmod(X, c, NULL, &temp) < 0) \
3704 goto Error; \
3705 Py_XDECREF(X); \
3706 X = temp; \
3707 temp = NULL; \
3708 } \
3709 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 /* Multiply two values, then reduce the result:
3712 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003713#define MULT(X, Y, result) \
3714 do { \
3715 temp = (PyLongObject *)long_mul(X, Y); \
3716 if (temp == NULL) \
3717 goto Error; \
3718 Py_XDECREF(result); \
3719 result = temp; \
3720 temp = NULL; \
3721 REDUCE(result); \
3722 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3725 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3726 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3727 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3728 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003731 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003733 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 }
3735 }
3736 }
3737 else {
3738 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3739 Py_INCREF(z); /* still holds 1L */
3740 table[0] = z;
3741 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003742 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3745 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3748 const int index = (bi >> j) & 0x1f;
3749 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003750 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003752 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 }
3754 }
3755 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 if (negativeOutput && (Py_SIZE(z) != 0)) {
3758 temp = (PyLongObject *)long_sub(z, c);
3759 if (temp == NULL)
3760 goto Error;
3761 Py_DECREF(z);
3762 z = temp;
3763 temp = NULL;
3764 }
3765 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003766
Mark Dickinson22b20182010-05-10 21:27:53 +00003767 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 if (z != NULL) {
3769 Py_DECREF(z);
3770 z = NULL;
3771 }
3772 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003773 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3775 for (i = 0; i < 32; ++i)
3776 Py_XDECREF(table[i]);
3777 }
3778 Py_DECREF(a);
3779 Py_DECREF(b);
3780 Py_XDECREF(c);
3781 Py_XDECREF(temp);
3782 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003783}
3784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003785static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003786long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 /* Implement ~x as -(x+1) */
3789 PyLongObject *x;
3790 PyLongObject *w;
3791 if (ABS(Py_SIZE(v)) <=1)
3792 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3793 w = (PyLongObject *)PyLong_FromLong(1L);
3794 if (w == NULL)
3795 return NULL;
3796 x = (PyLongObject *) long_add(v, w);
3797 Py_DECREF(w);
3798 if (x == NULL)
3799 return NULL;
3800 Py_SIZE(x) = -(Py_SIZE(x));
3801 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003802}
3803
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003804static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003805long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 PyLongObject *z;
3808 if (ABS(Py_SIZE(v)) <= 1)
3809 return PyLong_FromLong(-MEDIUM_VALUE(v));
3810 z = (PyLongObject *)_PyLong_Copy(v);
3811 if (z != NULL)
3812 Py_SIZE(z) = -(Py_SIZE(v));
3813 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003814}
3815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003816static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003817long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 if (Py_SIZE(v) < 0)
3820 return long_neg(v);
3821 else
3822 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003823}
3824
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003825static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003826long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003828 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003829}
3830
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003831static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003832long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 PyLongObject *z = NULL;
3835 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3836 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 if (Py_SIZE(a) < 0) {
3841 /* Right shifting negative numbers is harder */
3842 PyLongObject *a1, *a2;
3843 a1 = (PyLongObject *) long_invert(a);
3844 if (a1 == NULL)
3845 goto rshift_error;
3846 a2 = (PyLongObject *) long_rshift(a1, b);
3847 Py_DECREF(a1);
3848 if (a2 == NULL)
3849 goto rshift_error;
3850 z = (PyLongObject *) long_invert(a2);
3851 Py_DECREF(a2);
3852 }
3853 else {
3854 shiftby = PyLong_AsSsize_t((PyObject *)b);
3855 if (shiftby == -1L && PyErr_Occurred())
3856 goto rshift_error;
3857 if (shiftby < 0) {
3858 PyErr_SetString(PyExc_ValueError,
3859 "negative shift count");
3860 goto rshift_error;
3861 }
3862 wordshift = shiftby / PyLong_SHIFT;
3863 newsize = ABS(Py_SIZE(a)) - wordshift;
3864 if (newsize <= 0)
3865 return PyLong_FromLong(0);
3866 loshift = shiftby % PyLong_SHIFT;
3867 hishift = PyLong_SHIFT - loshift;
3868 lomask = ((digit)1 << hishift) - 1;
3869 himask = PyLong_MASK ^ lomask;
3870 z = _PyLong_New(newsize);
3871 if (z == NULL)
3872 goto rshift_error;
3873 if (Py_SIZE(a) < 0)
3874 Py_SIZE(z) = -(Py_SIZE(z));
3875 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3876 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3877 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003878 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 }
3880 z = long_normalize(z);
3881 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003882 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003884
Guido van Rossumc6913e71991-11-19 20:26:46 +00003885}
3886
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003887static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003888long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 /* This version due to Tim Peters */
3891 PyLongObject *a = (PyLongObject*)v;
3892 PyLongObject *b = (PyLongObject*)w;
3893 PyLongObject *z = NULL;
3894 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3895 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 shiftby = PyLong_AsSsize_t((PyObject *)b);
3900 if (shiftby == -1L && PyErr_Occurred())
3901 goto lshift_error;
3902 if (shiftby < 0) {
3903 PyErr_SetString(PyExc_ValueError, "negative shift count");
3904 goto lshift_error;
3905 }
3906 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3907 wordshift = shiftby / PyLong_SHIFT;
3908 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 oldsize = ABS(Py_SIZE(a));
3911 newsize = oldsize + wordshift;
3912 if (remshift)
3913 ++newsize;
3914 z = _PyLong_New(newsize);
3915 if (z == NULL)
3916 goto lshift_error;
3917 if (Py_SIZE(a) < 0)
3918 NEGATE(z);
3919 for (i = 0; i < wordshift; i++)
3920 z->ob_digit[i] = 0;
3921 accum = 0;
3922 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3923 accum |= (twodigits)a->ob_digit[j] << remshift;
3924 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3925 accum >>= PyLong_SHIFT;
3926 }
3927 if (remshift)
3928 z->ob_digit[newsize-1] = (digit)accum;
3929 else
3930 assert(!accum);
3931 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003932 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003934}
3935
Mark Dickinson27a87a22009-10-25 20:43:34 +00003936/* Compute two's complement of digit vector a[0:m], writing result to
3937 z[0:m]. The digit vector a need not be normalized, but should not
3938 be entirely zero. a and z may point to the same digit vector. */
3939
3940static void
3941v_complement(digit *z, digit *a, Py_ssize_t m)
3942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 Py_ssize_t i;
3944 digit carry = 1;
3945 for (i = 0; i < m; ++i) {
3946 carry += a[i] ^ PyLong_MASK;
3947 z[i] = carry & PyLong_MASK;
3948 carry >>= PyLong_SHIFT;
3949 }
3950 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003951}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003952
3953/* Bitwise and/xor/or operations */
3954
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003955static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003956long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003958 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 int nega, negb, negz;
3961 Py_ssize_t size_a, size_b, size_z, i;
3962 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 /* Bitwise operations for negative numbers operate as though
3965 on a two's complement representation. So convert arguments
3966 from sign-magnitude to two's complement, and convert the
3967 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 /* If a is negative, replace it by its two's complement. */
3970 size_a = ABS(Py_SIZE(a));
3971 nega = Py_SIZE(a) < 0;
3972 if (nega) {
3973 z = _PyLong_New(size_a);
3974 if (z == NULL)
3975 return NULL;
3976 v_complement(z->ob_digit, a->ob_digit, size_a);
3977 a = z;
3978 }
3979 else
3980 /* Keep reference count consistent. */
3981 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 /* Same for b. */
3984 size_b = ABS(Py_SIZE(b));
3985 negb = Py_SIZE(b) < 0;
3986 if (negb) {
3987 z = _PyLong_New(size_b);
3988 if (z == NULL) {
3989 Py_DECREF(a);
3990 return NULL;
3991 }
3992 v_complement(z->ob_digit, b->ob_digit, size_b);
3993 b = z;
3994 }
3995 else
3996 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003998 /* Swap a and b if necessary to ensure size_a >= size_b. */
3999 if (size_a < size_b) {
4000 z = a; a = b; b = z;
4001 size_z = size_a; size_a = size_b; size_b = size_z;
4002 negz = nega; nega = negb; negb = negz;
4003 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 /* JRH: The original logic here was to allocate the result value (z)
4006 as the longer of the two operands. However, there are some cases
4007 where the result is guaranteed to be shorter than that: AND of two
4008 positives, OR of two negatives: use the shorter number. AND with
4009 mixed signs: use the positive number. OR with mixed signs: use the
4010 negative number.
4011 */
4012 switch (op) {
4013 case '^':
4014 negz = nega ^ negb;
4015 size_z = size_a;
4016 break;
4017 case '&':
4018 negz = nega & negb;
4019 size_z = negb ? size_a : size_b;
4020 break;
4021 case '|':
4022 negz = nega | negb;
4023 size_z = negb ? size_b : size_a;
4024 break;
4025 default:
4026 PyErr_BadArgument();
4027 return NULL;
4028 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 /* We allow an extra digit if z is negative, to make sure that
4031 the final two's complement of z doesn't overflow. */
4032 z = _PyLong_New(size_z + negz);
4033 if (z == NULL) {
4034 Py_DECREF(a);
4035 Py_DECREF(b);
4036 return NULL;
4037 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 /* Compute digits for overlap of a and b. */
4040 switch(op) {
4041 case '&':
4042 for (i = 0; i < size_b; ++i)
4043 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4044 break;
4045 case '|':
4046 for (i = 0; i < size_b; ++i)
4047 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4048 break;
4049 case '^':
4050 for (i = 0; i < size_b; ++i)
4051 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4052 break;
4053 default:
4054 PyErr_BadArgument();
4055 return NULL;
4056 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 /* Copy any remaining digits of a, inverting if necessary. */
4059 if (op == '^' && negb)
4060 for (; i < size_z; ++i)
4061 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4062 else if (i < size_z)
4063 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4064 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004066 /* Complement result if negative. */
4067 if (negz) {
4068 Py_SIZE(z) = -(Py_SIZE(z));
4069 z->ob_digit[size_z] = PyLong_MASK;
4070 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4071 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 Py_DECREF(a);
4074 Py_DECREF(b);
4075 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004076}
4077
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004078static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004079long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004081 PyObject *c;
4082 CHECK_BINOP(a, b);
4083 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4084 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004085}
4086
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004087static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004088long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 PyObject *c;
4091 CHECK_BINOP(a, b);
4092 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4093 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004094}
4095
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004096static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004097long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004099 PyObject *c;
4100 CHECK_BINOP(a, b);
4101 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4102 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004103}
4104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004105static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004106long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004108 if (PyLong_CheckExact(v))
4109 Py_INCREF(v);
4110 else
4111 v = _PyLong_Copy((PyLongObject *)v);
4112 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004113}
4114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004115static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004116long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 double result;
4119 result = PyLong_AsDouble(v);
4120 if (result == -1.0 && PyErr_Occurred())
4121 return NULL;
4122 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004123}
4124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004125static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004126long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004127
Tim Peters6d6c1a32001-08-02 04:15:00 +00004128static PyObject *
4129long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4130{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004131 PyObject *obase = NULL, *x = NULL;
4132 long base;
4133 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (type != &PyLong_Type)
4137 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004138 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4139 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 return NULL;
4141 if (x == NULL)
4142 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004143 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004145
4146 base = PyLong_AsLongAndOverflow(obase, &overflow);
4147 if (base == -1 && PyErr_Occurred())
4148 return NULL;
4149 if (overflow || (base != 0 && base < 2) || base > 36) {
4150 PyErr_SetString(PyExc_ValueError,
4151 "int() arg 2 must be >= 2 and <= 36");
4152 return NULL;
4153 }
4154
4155 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004156 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4158 /* Since PyLong_FromString doesn't have a length parameter,
4159 * check here for possible NULs in the string. */
4160 char *string;
4161 Py_ssize_t size = Py_SIZE(x);
4162 if (PyByteArray_Check(x))
4163 string = PyByteArray_AS_STRING(x);
4164 else
4165 string = PyBytes_AS_STRING(x);
4166 if (strlen(string) != (size_t)size) {
4167 /* We only see this if there's a null byte in x,
4168 x is a bytes or buffer, *and* a base is given. */
4169 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004170 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004171 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 return NULL;
4173 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004174 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 }
4176 else {
4177 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004178 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 return NULL;
4180 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181}
4182
Guido van Rossumbef14172001-08-29 15:47:46 +00004183/* Wimpy, slow approach to tp_new calls for subtypes of long:
4184 first create a regular long from whatever arguments we got,
4185 then allocate a subtype instance and initialize it from
4186 the regular long. The regular long is then thrown away.
4187*/
4188static PyObject *
4189long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 PyLongObject *tmp, *newobj;
4192 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 assert(PyType_IsSubtype(type, &PyLong_Type));
4195 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4196 if (tmp == NULL)
4197 return NULL;
4198 assert(PyLong_CheckExact(tmp));
4199 n = Py_SIZE(tmp);
4200 if (n < 0)
4201 n = -n;
4202 newobj = (PyLongObject *)type->tp_alloc(type, n);
4203 if (newobj == NULL) {
4204 Py_DECREF(tmp);
4205 return NULL;
4206 }
4207 assert(PyLong_Check(newobj));
4208 Py_SIZE(newobj) = Py_SIZE(tmp);
4209 for (i = 0; i < n; i++)
4210 newobj->ob_digit[i] = tmp->ob_digit[i];
4211 Py_DECREF(tmp);
4212 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004213}
4214
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004215static PyObject *
4216long_getnewargs(PyLongObject *v)
4217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004219}
4220
Guido van Rossumb43daf72007-08-01 18:08:08 +00004221static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004222long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004224}
4225
4226static PyObject *
4227long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004229}
4230
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004231static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004232long__format__(PyObject *self, PyObject *args)
4233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4237 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004238 return _PyLong_FormatAdvanced(self, format_spec, 0,
4239 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004240}
4241
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004242/* Return a pair (q, r) such that a = b * q + r, and
4243 abs(r) <= abs(b)/2, with equality possible only if q is even.
4244 In other words, q == a / b, rounded to the nearest integer using
4245 round-half-to-even. */
4246
4247PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004248_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004249{
4250 PyLongObject *quo = NULL, *rem = NULL;
4251 PyObject *one = NULL, *twice_rem, *result, *temp;
4252 int cmp, quo_is_odd, quo_is_neg;
4253
4254 /* Equivalent Python code:
4255
4256 def divmod_near(a, b):
4257 q, r = divmod(a, b)
4258 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4259 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4260 # positive, 2 * r < b if b negative.
4261 greater_than_half = 2*r > b if b > 0 else 2*r < b
4262 exactly_half = 2*r == b
4263 if greater_than_half or exactly_half and q % 2 == 1:
4264 q += 1
4265 r -= b
4266 return q, r
4267
4268 */
4269 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4270 PyErr_SetString(PyExc_TypeError,
4271 "non-integer arguments in division");
4272 return NULL;
4273 }
4274
4275 /* Do a and b have different signs? If so, quotient is negative. */
4276 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4277
4278 one = PyLong_FromLong(1L);
4279 if (one == NULL)
4280 return NULL;
4281
4282 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4283 goto error;
4284
4285 /* compare twice the remainder with the divisor, to see
4286 if we need to adjust the quotient and remainder */
4287 twice_rem = long_lshift((PyObject *)rem, one);
4288 if (twice_rem == NULL)
4289 goto error;
4290 if (quo_is_neg) {
4291 temp = long_neg((PyLongObject*)twice_rem);
4292 Py_DECREF(twice_rem);
4293 twice_rem = temp;
4294 if (twice_rem == NULL)
4295 goto error;
4296 }
4297 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4298 Py_DECREF(twice_rem);
4299
4300 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4301 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4302 /* fix up quotient */
4303 if (quo_is_neg)
4304 temp = long_sub(quo, (PyLongObject *)one);
4305 else
4306 temp = long_add(quo, (PyLongObject *)one);
4307 Py_DECREF(quo);
4308 quo = (PyLongObject *)temp;
4309 if (quo == NULL)
4310 goto error;
4311 /* and remainder */
4312 if (quo_is_neg)
4313 temp = long_add(rem, (PyLongObject *)b);
4314 else
4315 temp = long_sub(rem, (PyLongObject *)b);
4316 Py_DECREF(rem);
4317 rem = (PyLongObject *)temp;
4318 if (rem == NULL)
4319 goto error;
4320 }
4321
4322 result = PyTuple_New(2);
4323 if (result == NULL)
4324 goto error;
4325
4326 /* PyTuple_SET_ITEM steals references */
4327 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4328 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4329 Py_DECREF(one);
4330 return result;
4331
4332 error:
4333 Py_XDECREF(quo);
4334 Py_XDECREF(rem);
4335 Py_XDECREF(one);
4336 return NULL;
4337}
4338
Eric Smith8c663262007-08-25 02:26:07 +00004339static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004340long_round(PyObject *self, PyObject *args)
4341{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004342 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004343
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004344 /* To round an integer m to the nearest 10**n (n positive), we make use of
4345 * the divmod_near operation, defined by:
4346 *
4347 * divmod_near(a, b) = (q, r)
4348 *
4349 * where q is the nearest integer to the quotient a / b (the
4350 * nearest even integer in the case of a tie) and r == a - q * b.
4351 * Hence q * b = a - r is the nearest multiple of b to a,
4352 * preferring even multiples in the case of a tie.
4353 *
4354 * So the nearest multiple of 10**n to m is:
4355 *
4356 * m - divmod_near(m, 10**n)[1].
4357 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4359 return NULL;
4360 if (o_ndigits == NULL)
4361 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004362
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004363 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (ndigits == NULL)
4365 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004366
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004367 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004368 if (Py_SIZE(ndigits) >= 0) {
4369 Py_DECREF(ndigits);
4370 return long_long(self);
4371 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004372
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004373 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4374 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004376 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004378 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004379
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004380 result = PyLong_FromLong(10L);
4381 if (result == NULL) {
4382 Py_DECREF(ndigits);
4383 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004385
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004386 temp = long_pow(result, ndigits, Py_None);
4387 Py_DECREF(ndigits);
4388 Py_DECREF(result);
4389 result = temp;
4390 if (result == NULL)
4391 return NULL;
4392
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004393 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004394 Py_DECREF(result);
4395 result = temp;
4396 if (result == NULL)
4397 return NULL;
4398
4399 temp = long_sub((PyLongObject *)self,
4400 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4401 Py_DECREF(result);
4402 result = temp;
4403
4404 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004405}
4406
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004407static PyObject *
4408long_sizeof(PyLongObject *v)
4409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4413 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004414}
4415
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004416static PyObject *
4417long_bit_length(PyLongObject *v)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 PyLongObject *result, *x, *y;
4420 Py_ssize_t ndigits, msd_bits = 0;
4421 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 assert(v != NULL);
4424 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 ndigits = ABS(Py_SIZE(v));
4427 if (ndigits == 0)
4428 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 msd = v->ob_digit[ndigits-1];
4431 while (msd >= 32) {
4432 msd_bits += 6;
4433 msd >>= 6;
4434 }
4435 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4438 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 /* expression above may overflow; use Python integers instead */
4441 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4442 if (result == NULL)
4443 return NULL;
4444 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4445 if (x == NULL)
4446 goto error;
4447 y = (PyLongObject *)long_mul(result, x);
4448 Py_DECREF(x);
4449 if (y == NULL)
4450 goto error;
4451 Py_DECREF(result);
4452 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4455 if (x == NULL)
4456 goto error;
4457 y = (PyLongObject *)long_add(result, x);
4458 Py_DECREF(x);
4459 if (y == NULL)
4460 goto error;
4461 Py_DECREF(result);
4462 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004465
Mark Dickinson22b20182010-05-10 21:27:53 +00004466 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 Py_DECREF(result);
4468 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004469}
4470
4471PyDoc_STRVAR(long_bit_length_doc,
4472"int.bit_length() -> int\n\
4473\n\
4474Number of bits necessary to represent self in binary.\n\
4475>>> bin(37)\n\
4476'0b100101'\n\
4477>>> (37).bit_length()\n\
44786");
4479
Christian Heimes53876d92008-04-19 00:31:39 +00004480#if 0
4481static PyObject *
4482long_is_finite(PyObject *v)
4483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004485}
4486#endif
4487
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004488
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004489static PyObject *
4490long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 PyObject *byteorder_str;
4493 PyObject *is_signed_obj = NULL;
4494 Py_ssize_t length;
4495 int little_endian;
4496 int is_signed;
4497 PyObject *bytes;
4498 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4501 &length, &byteorder_str,
4502 &is_signed_obj))
4503 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 if (args != NULL && Py_SIZE(args) > 2) {
4506 PyErr_SetString(PyExc_TypeError,
4507 "'signed' is a keyword-only argument");
4508 return NULL;
4509 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4512 little_endian = 1;
4513 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4514 little_endian = 0;
4515 else {
4516 PyErr_SetString(PyExc_ValueError,
4517 "byteorder must be either 'little' or 'big'");
4518 return NULL;
4519 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004521 if (is_signed_obj != NULL) {
4522 int cmp = PyObject_IsTrue(is_signed_obj);
4523 if (cmp < 0)
4524 return NULL;
4525 is_signed = cmp ? 1 : 0;
4526 }
4527 else {
4528 /* If the signed argument was omitted, use False as the
4529 default. */
4530 is_signed = 0;
4531 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004533 if (length < 0) {
4534 PyErr_SetString(PyExc_ValueError,
4535 "length argument must be non-negative");
4536 return NULL;
4537 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 bytes = PyBytes_FromStringAndSize(NULL, length);
4540 if (bytes == NULL)
4541 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4544 length, little_endian, is_signed) < 0) {
4545 Py_DECREF(bytes);
4546 return NULL;
4547 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004550}
4551
Mark Dickinson078c2532010-01-30 18:06:17 +00004552PyDoc_STRVAR(long_to_bytes_doc,
4553"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004554\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004555Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004556\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004558raised if the integer is not representable with the given number of\n\
4559bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004560\n\
4561The byteorder argument determines the byte order used to represent the\n\
4562integer. If byteorder is 'big', the most significant byte is at the\n\
4563beginning of the byte array. If byteorder is 'little', the most\n\
4564significant byte is at the end of the byte array. To request the native\n\
4565byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4566\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004567The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004569is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004570
4571static PyObject *
4572long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 PyObject *byteorder_str;
4575 PyObject *is_signed_obj = NULL;
4576 int little_endian;
4577 int is_signed;
4578 PyObject *obj;
4579 PyObject *bytes;
4580 PyObject *long_obj;
4581 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4584 &obj, &byteorder_str,
4585 &is_signed_obj))
4586 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 if (args != NULL && Py_SIZE(args) > 2) {
4589 PyErr_SetString(PyExc_TypeError,
4590 "'signed' is a keyword-only argument");
4591 return NULL;
4592 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4595 little_endian = 1;
4596 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4597 little_endian = 0;
4598 else {
4599 PyErr_SetString(PyExc_ValueError,
4600 "byteorder must be either 'little' or 'big'");
4601 return NULL;
4602 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 if (is_signed_obj != NULL) {
4605 int cmp = PyObject_IsTrue(is_signed_obj);
4606 if (cmp < 0)
4607 return NULL;
4608 is_signed = cmp ? 1 : 0;
4609 }
4610 else {
4611 /* If the signed argument was omitted, use False as the
4612 default. */
4613 is_signed = 0;
4614 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 bytes = PyObject_Bytes(obj);
4617 if (bytes == NULL)
4618 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 long_obj = _PyLong_FromByteArray(
4621 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4622 little_endian, is_signed);
4623 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 /* If from_bytes() was used on subclass, allocate new subclass
4626 * instance, initialize it with decoded long value and return it.
4627 */
4628 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4629 PyLongObject *newobj;
4630 int i;
4631 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 newobj = (PyLongObject *)type->tp_alloc(type, n);
4634 if (newobj == NULL) {
4635 Py_DECREF(long_obj);
4636 return NULL;
4637 }
4638 assert(PyLong_Check(newobj));
4639 Py_SIZE(newobj) = Py_SIZE(long_obj);
4640 for (i = 0; i < n; i++) {
4641 newobj->ob_digit[i] =
4642 ((PyLongObject *)long_obj)->ob_digit[i];
4643 }
4644 Py_DECREF(long_obj);
4645 return (PyObject *)newobj;
4646 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004649}
4650
Mark Dickinson078c2532010-01-30 18:06:17 +00004651PyDoc_STRVAR(long_from_bytes_doc,
4652"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4653\n\
4654Return the integer represented by the given array of bytes.\n\
4655\n\
4656The bytes argument must either support the buffer protocol or be an\n\
4657iterable object producing bytes. Bytes and bytearray are examples of\n\
4658built-in objects that support the buffer protocol.\n\
4659\n\
4660The byteorder argument determines the byte order used to represent the\n\
4661integer. If byteorder is 'big', the most significant byte is at the\n\
4662beginning of the byte array. If byteorder is 'little', the most\n\
4663significant byte is at the end of the byte array. To request the native\n\
4664byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4665\n\
4666The signed keyword-only argument indicates whether two's complement is\n\
4667used to represent the integer.");
4668
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004669static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4671 "Returns self, the complex conjugate of any int."},
4672 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4673 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004674#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4676 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004677#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 {"to_bytes", (PyCFunction)long_to_bytes,
4679 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4680 {"from_bytes", (PyCFunction)long_from_bytes,
4681 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4682 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4683 "Truncating an Integral returns itself."},
4684 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4685 "Flooring an Integral returns itself."},
4686 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4687 "Ceiling of an Integral returns itself."},
4688 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4689 "Rounding an Integral returns itself.\n"
4690 "Rounding with an ndigits argument also returns an integer."},
4691 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4692 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4693 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4694 "Returns size in memory, in bytes"},
4695 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004696};
4697
Guido van Rossumb43daf72007-08-01 18:08:08 +00004698static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004699 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004700 (getter)long_long, (setter)NULL,
4701 "the real part of a complex number",
4702 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004703 {"imag",
4704 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004705 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004706 NULL},
4707 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004708 (getter)long_long, (setter)NULL,
4709 "the numerator of a rational number in lowest terms",
4710 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004711 {"denominator",
4712 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004713 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004714 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004715 {NULL} /* Sentinel */
4716};
4717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004718PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004719"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004721Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722point argument will be truncated towards zero (this does not include a\n\
4723string representation of a floating point number!) When converting a\n\
4724string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004725converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004726
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004727static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004728 (binaryfunc)long_add, /*nb_add*/
4729 (binaryfunc)long_sub, /*nb_subtract*/
4730 (binaryfunc)long_mul, /*nb_multiply*/
4731 long_mod, /*nb_remainder*/
4732 long_divmod, /*nb_divmod*/
4733 long_pow, /*nb_power*/
4734 (unaryfunc)long_neg, /*nb_negative*/
4735 (unaryfunc)long_long, /*tp_positive*/
4736 (unaryfunc)long_abs, /*tp_absolute*/
4737 (inquiry)long_bool, /*tp_bool*/
4738 (unaryfunc)long_invert, /*nb_invert*/
4739 long_lshift, /*nb_lshift*/
4740 (binaryfunc)long_rshift, /*nb_rshift*/
4741 long_and, /*nb_and*/
4742 long_xor, /*nb_xor*/
4743 long_or, /*nb_or*/
4744 long_long, /*nb_int*/
4745 0, /*nb_reserved*/
4746 long_float, /*nb_float*/
4747 0, /* nb_inplace_add */
4748 0, /* nb_inplace_subtract */
4749 0, /* nb_inplace_multiply */
4750 0, /* nb_inplace_remainder */
4751 0, /* nb_inplace_power */
4752 0, /* nb_inplace_lshift */
4753 0, /* nb_inplace_rshift */
4754 0, /* nb_inplace_and */
4755 0, /* nb_inplace_xor */
4756 0, /* nb_inplace_or */
4757 long_div, /* nb_floor_divide */
4758 long_true_divide, /* nb_true_divide */
4759 0, /* nb_inplace_floor_divide */
4760 0, /* nb_inplace_true_divide */
4761 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004762};
4763
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004764PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4766 "int", /* tp_name */
4767 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4768 sizeof(digit), /* tp_itemsize */
4769 long_dealloc, /* tp_dealloc */
4770 0, /* tp_print */
4771 0, /* tp_getattr */
4772 0, /* tp_setattr */
4773 0, /* tp_reserved */
4774 long_to_decimal_string, /* tp_repr */
4775 &long_as_number, /* tp_as_number */
4776 0, /* tp_as_sequence */
4777 0, /* tp_as_mapping */
4778 (hashfunc)long_hash, /* tp_hash */
4779 0, /* tp_call */
4780 long_to_decimal_string, /* tp_str */
4781 PyObject_GenericGetAttr, /* tp_getattro */
4782 0, /* tp_setattro */
4783 0, /* tp_as_buffer */
4784 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4785 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4786 long_doc, /* tp_doc */
4787 0, /* tp_traverse */
4788 0, /* tp_clear */
4789 long_richcompare, /* tp_richcompare */
4790 0, /* tp_weaklistoffset */
4791 0, /* tp_iter */
4792 0, /* tp_iternext */
4793 long_methods, /* tp_methods */
4794 0, /* tp_members */
4795 long_getset, /* tp_getset */
4796 0, /* tp_base */
4797 0, /* tp_dict */
4798 0, /* tp_descr_get */
4799 0, /* tp_descr_set */
4800 0, /* tp_dictoffset */
4801 0, /* tp_init */
4802 0, /* tp_alloc */
4803 long_new, /* tp_new */
4804 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004805};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004806
Mark Dickinsonbd792642009-03-18 20:06:12 +00004807static PyTypeObject Int_InfoType;
4808
4809PyDoc_STRVAR(int_info__doc__,
4810"sys.int_info\n\
4811\n\
4812A struct sequence that holds information about Python's\n\
4813internal representation of integers. The attributes are read only.");
4814
4815static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004817 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004819};
4820
4821static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 "sys.int_info", /* name */
4823 int_info__doc__, /* doc */
4824 int_info_fields, /* fields */
4825 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004826};
4827
4828PyObject *
4829PyLong_GetInfo(void)
4830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004831 PyObject* int_info;
4832 int field = 0;
4833 int_info = PyStructSequence_New(&Int_InfoType);
4834 if (int_info == NULL)
4835 return NULL;
4836 PyStructSequence_SET_ITEM(int_info, field++,
4837 PyLong_FromLong(PyLong_SHIFT));
4838 PyStructSequence_SET_ITEM(int_info, field++,
4839 PyLong_FromLong(sizeof(digit)));
4840 if (PyErr_Occurred()) {
4841 Py_CLEAR(int_info);
4842 return NULL;
4843 }
4844 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004845}
4846
Guido van Rossumddefaf32007-01-14 03:31:43 +00004847int
4848_PyLong_Init(void)
4849{
4850#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 int ival, size;
4852 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4855 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4856 if (Py_TYPE(v) == &PyLong_Type) {
4857 /* The element is already initialized, most likely
4858 * the Python interpreter was initialized before.
4859 */
4860 Py_ssize_t refcnt;
4861 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004863 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4864 _Py_NewReference(op);
4865 /* _Py_NewReference sets the ref count to 1 but
4866 * the ref count might be larger. Set the refcnt
4867 * to the original refcnt + 1 */
4868 Py_REFCNT(op) = refcnt + 1;
4869 assert(Py_SIZE(op) == size);
4870 assert(v->ob_digit[0] == abs(ival));
4871 }
4872 else {
4873 PyObject_INIT(v, &PyLong_Type);
4874 }
4875 Py_SIZE(v) = size;
4876 v->ob_digit[0] = abs(ival);
4877 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004878#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004879 /* initialize int_info */
4880 if (Int_InfoType.tp_name == 0)
4881 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004884}
4885
4886void
4887PyLong_Fini(void)
4888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 /* Integers are currently statically allocated. Py_DECREF is not
4890 needed, but Python must forget about the reference or multiple
4891 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004892#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 int i;
4894 PyLongObject *v = small_ints;
4895 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4896 _Py_DEC_REFTOTAL;
4897 _Py_ForgetReference((PyObject*)v);
4898 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004899#endif
4900}