blob: 3630ae4e197d06f007d46e9ed96d02d2046c701c [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) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
Mark Dickinson8d48b432011-10-23 20:47:14 +0100323/* Get a C long int from a long int object or any object that has an __int__
324 method.
325
326 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
327 the result. Otherwise *overflow is 0.
328
329 For other errors (e.g., TypeError), return -1 and set an error condition.
330 In this case *overflow will be 0.
331*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This version by Tim Peters */
337 register PyLongObject *v;
338 unsigned long x, prev;
339 long res;
340 Py_ssize_t i;
341 int sign;
342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *overflow = 0;
345 if (vv == NULL) {
346 PyErr_BadInternalCall();
347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 nb = vv->ob_type->tp_as_number;
353 if (nb == NULL || nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError,
355 "an integer is required");
356 return -1;
357 }
358 vv = (*nb->nb_int) (vv);
359 if (vv == NULL)
360 return -1;
361 do_decref = 1;
362 if (!PyLong_Check(vv)) {
363 Py_DECREF(vv);
364 PyErr_SetString(PyExc_TypeError,
365 "nb_int should return int object");
366 return -1;
367 }
368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 res = -1;
371 v = (PyLongObject *)vv;
372 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 switch (i) {
375 case -1:
376 res = -(sdigit)v->ob_digit[0];
377 break;
378 case 0:
379 res = 0;
380 break;
381 case 1:
382 res = v->ob_digit[0];
383 break;
384 default:
385 sign = 1;
386 x = 0;
387 if (i < 0) {
388 sign = -1;
389 i = -(i);
390 }
391 while (--i >= 0) {
392 prev = x;
393 x = (x << PyLong_SHIFT) | v->ob_digit[i];
394 if ((x >> PyLong_SHIFT) != prev) {
395 *overflow = sign;
396 goto exit;
397 }
398 }
399 /* Haven't lost any bits, but casting to long requires extra
400 * care (see comment above).
401 */
402 if (x <= (unsigned long)LONG_MAX) {
403 res = (long)x * sign;
404 }
405 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
406 res = LONG_MIN;
407 }
408 else {
409 *overflow = sign;
410 /* res is already set to -1 */
411 }
412 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (do_decref) {
415 Py_DECREF(vv);
416 }
417 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000418}
419
Mark Dickinson8d48b432011-10-23 20:47:14 +0100420/* Get a C long int from a long int object or any object that has an __int__
421 method. Return -1 and set an error if overflow occurs. */
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000424PyLong_AsLong(PyObject *obj)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int overflow;
427 long result = PyLong_AsLongAndOverflow(obj, &overflow);
428 if (overflow) {
429 /* XXX: could be cute and give a different
430 message for overflow == -1 */
431 PyErr_SetString(PyExc_OverflowError,
432 "Python int too large to convert to C long");
433 }
434 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000435}
436
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000437/* Get a Py_ssize_t from a long int object.
438 Returns -1 and sets an error condition if overflow occurs. */
439
440Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 register PyLongObject *v;
443 size_t x, prev;
444 Py_ssize_t i;
445 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (vv == NULL) {
448 PyErr_BadInternalCall();
449 return -1;
450 }
451 if (!PyLong_Check(vv)) {
452 PyErr_SetString(PyExc_TypeError, "an integer is required");
453 return -1;
454 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 v = (PyLongObject *)vv;
457 i = Py_SIZE(v);
458 switch (i) {
459 case -1: return -(sdigit)v->ob_digit[0];
460 case 0: return 0;
461 case 1: return v->ob_digit[0];
462 }
463 sign = 1;
464 x = 0;
465 if (i < 0) {
466 sign = -1;
467 i = -(i);
468 }
469 while (--i >= 0) {
470 prev = x;
471 x = (x << PyLong_SHIFT) | v->ob_digit[i];
472 if ((x >> PyLong_SHIFT) != prev)
473 goto overflow;
474 }
475 /* Haven't lost any bits, but casting to a signed type requires
476 * extra care (see comment above).
477 */
478 if (x <= (size_t)PY_SSIZE_T_MAX) {
479 return (Py_ssize_t)x * sign;
480 }
481 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
482 return PY_SSIZE_T_MIN;
483 }
484 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485
Mark Dickinson22b20182010-05-10 21:27:53 +0000486 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyErr_SetString(PyExc_OverflowError,
488 "Python int too large to convert to C ssize_t");
489 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490}
491
Guido van Rossumd8c80482002-08-13 00:24:58 +0000492/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000493 Returns -1 and sets an error condition if overflow occurs. */
494
495unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000496PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 register PyLongObject *v;
499 unsigned long x, prev;
500 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (vv == NULL) {
503 PyErr_BadInternalCall();
504 return (unsigned long)-1;
505 }
506 if (!PyLong_Check(vv)) {
507 PyErr_SetString(PyExc_TypeError, "an integer is required");
508 return (unsigned long)-1;
509 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 v = (PyLongObject *)vv;
512 i = Py_SIZE(v);
513 x = 0;
514 if (i < 0) {
515 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000516 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return (unsigned long) -1;
518 }
519 switch (i) {
520 case 0: return 0;
521 case 1: return v->ob_digit[0];
522 }
523 while (--i >= 0) {
524 prev = x;
525 x = (x << PyLong_SHIFT) | v->ob_digit[i];
526 if ((x >> PyLong_SHIFT) != prev) {
527 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000528 "python int too large to convert "
529 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return (unsigned long) -1;
531 }
532 }
533 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000534}
535
Stefan Krahb77c6c62011-09-12 16:22:47 +0200536/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
537 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
539size_t
540PyLong_AsSize_t(PyObject *vv)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 register PyLongObject *v;
543 size_t x, prev;
544 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (vv == NULL) {
547 PyErr_BadInternalCall();
548 return (size_t) -1;
549 }
550 if (!PyLong_Check(vv)) {
551 PyErr_SetString(PyExc_TypeError, "an integer is required");
552 return (size_t)-1;
553 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 v = (PyLongObject *)vv;
556 i = Py_SIZE(v);
557 x = 0;
558 if (i < 0) {
559 PyErr_SetString(PyExc_OverflowError,
560 "can't convert negative value to size_t");
561 return (size_t) -1;
562 }
563 switch (i) {
564 case 0: return 0;
565 case 1: return v->ob_digit[0];
566 }
567 while (--i >= 0) {
568 prev = x;
569 x = (x << PyLong_SHIFT) | v->ob_digit[i];
570 if ((x >> PyLong_SHIFT) != prev) {
571 PyErr_SetString(PyExc_OverflowError,
572 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200573 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 }
576 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000577}
578
Thomas Hellera4ea6032003-04-17 18:55:45 +0000579/* Get a C unsigned long int from a long int object, ignoring the high bits.
580 Returns -1 and sets an error condition if an error occurs. */
581
Guido van Rossumddefaf32007-01-14 03:31:43 +0000582static unsigned long
583_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 register PyLongObject *v;
586 unsigned long x;
587 Py_ssize_t i;
588 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (vv == NULL || !PyLong_Check(vv)) {
591 PyErr_BadInternalCall();
592 return (unsigned long) -1;
593 }
594 v = (PyLongObject *)vv;
595 i = Py_SIZE(v);
596 switch (i) {
597 case 0: return 0;
598 case 1: return v->ob_digit[0];
599 }
600 sign = 1;
601 x = 0;
602 if (i < 0) {
603 sign = -1;
604 i = -i;
605 }
606 while (--i >= 0) {
607 x = (x << PyLong_SHIFT) | v->ob_digit[i];
608 }
609 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000610}
611
Guido van Rossumddefaf32007-01-14 03:31:43 +0000612unsigned long
613PyLong_AsUnsignedLongMask(register PyObject *op)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyNumberMethods *nb;
616 PyLongObject *lo;
617 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (op && PyLong_Check(op))
620 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
623 nb->nb_int == NULL) {
624 PyErr_SetString(PyExc_TypeError, "an integer is required");
625 return (unsigned long)-1;
626 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 lo = (PyLongObject*) (*nb->nb_int) (op);
629 if (lo == NULL)
630 return (unsigned long)-1;
631 if (PyLong_Check(lo)) {
632 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
633 Py_DECREF(lo);
634 if (PyErr_Occurred())
635 return (unsigned long)-1;
636 return val;
637 }
638 else
639 {
640 Py_DECREF(lo);
641 PyErr_SetString(PyExc_TypeError,
642 "nb_int should return int object");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645}
646
Tim Peters5b8132f2003-01-31 15:52:05 +0000647int
648_PyLong_Sign(PyObject *vv)
649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 assert(v != NULL);
653 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000656}
657
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658size_t
659_PyLong_NumBits(PyObject *vv)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyLongObject *v = (PyLongObject *)vv;
662 size_t result = 0;
663 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 assert(v != NULL);
666 assert(PyLong_Check(v));
667 ndigits = ABS(Py_SIZE(v));
668 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
669 if (ndigits > 0) {
670 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 result = (ndigits - 1) * PyLong_SHIFT;
673 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
674 goto Overflow;
675 do {
676 ++result;
677 if (result == 0)
678 goto Overflow;
679 msd >>= 1;
680 } while (msd);
681 }
682 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000683
Mark Dickinson22b20182010-05-10 21:27:53 +0000684 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
686 "to express in a platform size_t");
687 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000688}
689
Tim Peters2a9b3672001-06-11 21:23:58 +0000690PyObject *
691_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000693{
Mark Dickinson22b20182010-05-10 21:27:53 +0000694 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 int incr; /* direction to move pstartbyte */
696 const unsigned char* pendbyte; /* MSB of bytes */
697 size_t numsignificantbytes; /* number of bytes that matter */
698 Py_ssize_t ndigits; /* number of Python long digits */
699 PyLongObject* v; /* result */
700 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (n == 0)
703 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (little_endian) {
706 pstartbyte = bytes;
707 pendbyte = bytes + n - 1;
708 incr = 1;
709 }
710 else {
711 pstartbyte = bytes + n - 1;
712 pendbyte = bytes;
713 incr = -1;
714 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (is_signed)
717 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200720 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 is positive, and leading 0xff bytes if negative. */
722 {
723 size_t i;
724 const unsigned char* p = pendbyte;
725 const int pincr = -incr; /* search MSB to LSB */
726 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 for (i = 0; i < n; ++i, p += pincr) {
729 if (*p != insignficant)
730 break;
731 }
732 numsignificantbytes = n - i;
733 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
734 actually has 2 significant bytes. OTOH, 0xff0001 ==
735 -0x00ffff, so we wouldn't *need* to bump it there; but we
736 do for 0xffff = -0x0001. To be safe without bothering to
737 check every case, bump it regardless. */
738 if (is_signed && numsignificantbytes < n)
739 ++numsignificantbytes;
740 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* How many Python long digits do we need? We have
743 8*numsignificantbytes bits, and each Python long digit has
744 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
745 /* catch overflow before it happens */
746 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
747 PyErr_SetString(PyExc_OverflowError,
748 "byte array too long to convert to int");
749 return NULL;
750 }
751 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
752 v = _PyLong_New(ndigits);
753 if (v == NULL)
754 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Copy the bits over. The tricky parts are computing 2's-comp on
757 the fly for signed numbers, and dealing with the mismatch between
758 8-bit bytes and (probably) 15-bit Python digits.*/
759 {
760 size_t i;
761 twodigits carry = 1; /* for 2's-comp calculation */
762 twodigits accum = 0; /* sliding register */
763 unsigned int accumbits = 0; /* number of bits in accum */
764 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
767 twodigits thisbyte = *p;
768 /* Compute correction for 2's comp, if needed. */
769 if (is_signed) {
770 thisbyte = (0xff ^ thisbyte) + carry;
771 carry = thisbyte >> 8;
772 thisbyte &= 0xff;
773 }
774 /* Because we're going LSB to MSB, thisbyte is
775 more significant than what's already in accum,
776 so needs to be prepended to accum. */
777 accum |= (twodigits)thisbyte << accumbits;
778 accumbits += 8;
779 if (accumbits >= PyLong_SHIFT) {
780 /* There's enough to fill a Python digit. */
781 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000782 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 ++idigit;
784 accum >>= PyLong_SHIFT;
785 accumbits -= PyLong_SHIFT;
786 assert(accumbits < PyLong_SHIFT);
787 }
788 }
789 assert(accumbits < PyLong_SHIFT);
790 if (accumbits) {
791 assert(idigit < ndigits);
792 v->ob_digit[idigit] = (digit)accum;
793 ++idigit;
794 }
795 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 Py_SIZE(v) = is_signed ? -idigit : idigit;
798 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000799}
800
801int
802_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 unsigned char* bytes, size_t n,
804 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000807 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000809 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
811 digit carry; /* for computing 2's-comp */
812 size_t j; /* # bytes filled */
813 unsigned char* p; /* pointer to next byte in bytes */
814 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (Py_SIZE(v) < 0) {
819 ndigits = -(Py_SIZE(v));
820 if (!is_signed) {
821 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000822 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return -1;
824 }
825 do_twos_comp = 1;
826 }
827 else {
828 ndigits = Py_SIZE(v);
829 do_twos_comp = 0;
830 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (little_endian) {
833 p = bytes;
834 pincr = 1;
835 }
836 else {
837 p = bytes + n - 1;
838 pincr = -1;
839 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 /* Copy over all the Python digits.
842 It's crucial that every Python digit except for the MSD contribute
843 exactly PyLong_SHIFT bits to the total, so first assert that the long is
844 normalized. */
845 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
846 j = 0;
847 accum = 0;
848 accumbits = 0;
849 carry = do_twos_comp ? 1 : 0;
850 for (i = 0; i < ndigits; ++i) {
851 digit thisdigit = v->ob_digit[i];
852 if (do_twos_comp) {
853 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
854 carry = thisdigit >> PyLong_SHIFT;
855 thisdigit &= PyLong_MASK;
856 }
857 /* Because we're going LSB to MSB, thisdigit is more
858 significant than what's already in accum, so needs to be
859 prepended to accum. */
860 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 /* The most-significant digit may be (probably is) at least
863 partly empty. */
864 if (i == ndigits - 1) {
865 /* Count # of sign bits -- they needn't be stored,
866 * although for signed conversion we need later to
867 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000868 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 while (s != 0) {
870 s >>= 1;
871 accumbits++;
872 }
873 }
874 else
875 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Store as many bytes as possible. */
878 while (accumbits >= 8) {
879 if (j >= n)
880 goto Overflow;
881 ++j;
882 *p = (unsigned char)(accum & 0xff);
883 p += pincr;
884 accumbits -= 8;
885 accum >>= 8;
886 }
887 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Store the straggler (if any). */
890 assert(accumbits < 8);
891 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
892 if (accumbits > 0) {
893 if (j >= n)
894 goto Overflow;
895 ++j;
896 if (do_twos_comp) {
897 /* Fill leading bits of the byte with sign bits
898 (appropriately pretending that the long had an
899 infinite supply of sign bits). */
900 accum |= (~(twodigits)0) << accumbits;
901 }
902 *p = (unsigned char)(accum & 0xff);
903 p += pincr;
904 }
905 else if (j == n && n > 0 && is_signed) {
906 /* The main loop filled the byte array exactly, so the code
907 just above didn't get to ensure there's a sign bit, and the
908 loop below wouldn't add one either. Make sure a sign bit
909 exists. */
910 unsigned char msb = *(p - pincr);
911 int sign_bit_set = msb >= 0x80;
912 assert(accumbits == 0);
913 if (sign_bit_set == do_twos_comp)
914 return 0;
915 else
916 goto Overflow;
917 }
Tim Peters05607ad2001-06-13 21:01:27 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* Fill remaining bytes with copies of the sign bit. */
920 {
921 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
922 for ( ; j < n; ++j, p += pincr)
923 *p = signbyte;
924 }
Tim Peters05607ad2001-06-13 21:01:27 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000927
Mark Dickinson22b20182010-05-10 21:27:53 +0000928 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
930 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000931
Tim Peters2a9b3672001-06-11 21:23:58 +0000932}
933
Mark Dickinson8d48b432011-10-23 20:47:14 +0100934/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000935
936PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000937PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000938{
Tim Peters70128a12001-06-16 08:48:40 +0000939#ifndef HAVE_LONG_LONG
940# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
941#endif
942#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000943# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000944#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* special-case null pointer */
946 if (!p)
947 return PyLong_FromLong(0);
948 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000949
Guido van Rossum78694d91998-09-18 14:14:13 +0000950}
951
Mark Dickinson8d48b432011-10-23 20:47:14 +0100952/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000953
954void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000955PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000956{
Tim Peters70128a12001-06-16 08:48:40 +0000957#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
961 x = PyLong_AsLong(vv);
962 else
963 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000964#else
Tim Peters70128a12001-06-16 08:48:40 +0000965
966#ifndef HAVE_LONG_LONG
967# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
968#endif
969#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000971#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
975 x = PyLong_AsLongLong(vv);
976 else
977 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000978
979#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (x == -1 && PyErr_Occurred())
982 return NULL;
983 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000984}
985
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000986#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000987
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000988/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000989 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000990 */
991
Tim Peterscf37dfc2001-06-14 18:42:50 +0000992#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000993#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000994
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996
997PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000998PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyLongObject *v;
1001 unsigned PY_LONG_LONG abs_ival;
1002 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1003 int ndigits = 0;
1004 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 CHECK_SMALL_INT(ival);
1007 if (ival < 0) {
1008 /* avoid signed overflow on negation; see comments
1009 in PyLong_FromLong above. */
1010 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1011 negative = 1;
1012 }
1013 else {
1014 abs_ival = (unsigned PY_LONG_LONG)ival;
1015 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Count the number of Python digits.
1018 We used to pick 5 ("big enough for anything"), but that's a
1019 waste of time and space given that 5*15 = 75 bits are rarely
1020 needed. */
1021 t = abs_ival;
1022 while (t) {
1023 ++ndigits;
1024 t >>= PyLong_SHIFT;
1025 }
1026 v = _PyLong_New(ndigits);
1027 if (v != NULL) {
1028 digit *p = v->ob_digit;
1029 Py_SIZE(v) = negative ? -ndigits : ndigits;
1030 t = abs_ival;
1031 while (t) {
1032 *p++ = (digit)(t & PyLong_MASK);
1033 t >>= PyLong_SHIFT;
1034 }
1035 }
1036 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037}
1038
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001039/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001040
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001042PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyLongObject *v;
1045 unsigned PY_LONG_LONG t;
1046 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (ival < PyLong_BASE)
1049 return PyLong_FromLong((long)ival);
1050 /* Count the number of Python digits. */
1051 t = (unsigned PY_LONG_LONG)ival;
1052 while (t) {
1053 ++ndigits;
1054 t >>= PyLong_SHIFT;
1055 }
1056 v = _PyLong_New(ndigits);
1057 if (v != NULL) {
1058 digit *p = v->ob_digit;
1059 Py_SIZE(v) = ndigits;
1060 while (ival) {
1061 *p++ = (digit)(ival & PyLong_MASK);
1062 ival >>= PyLong_SHIFT;
1063 }
1064 }
1065 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066}
1067
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068/* Create a new long int object from a C Py_ssize_t. */
1069
1070PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001071PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyLongObject *v;
1074 size_t abs_ival;
1075 size_t t; /* unsigned so >> doesn't propagate sign bit */
1076 int ndigits = 0;
1077 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 CHECK_SMALL_INT(ival);
1080 if (ival < 0) {
1081 /* avoid signed overflow when ival = SIZE_T_MIN */
1082 abs_ival = (size_t)(-1-ival)+1;
1083 negative = 1;
1084 }
1085 else {
1086 abs_ival = (size_t)ival;
1087 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* Count the number of Python digits. */
1090 t = abs_ival;
1091 while (t) {
1092 ++ndigits;
1093 t >>= PyLong_SHIFT;
1094 }
1095 v = _PyLong_New(ndigits);
1096 if (v != NULL) {
1097 digit *p = v->ob_digit;
1098 Py_SIZE(v) = negative ? -ndigits : ndigits;
1099 t = abs_ival;
1100 while (t) {
1101 *p++ = (digit)(t & PyLong_MASK);
1102 t >>= PyLong_SHIFT;
1103 }
1104 }
1105 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106}
1107
1108/* Create a new long int object from a C size_t. */
1109
1110PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001111PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyLongObject *v;
1114 size_t t;
1115 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (ival < PyLong_BASE)
1118 return PyLong_FromLong((long)ival);
1119 /* Count the number of Python digits. */
1120 t = ival;
1121 while (t) {
1122 ++ndigits;
1123 t >>= PyLong_SHIFT;
1124 }
1125 v = _PyLong_New(ndigits);
1126 if (v != NULL) {
1127 digit *p = v->ob_digit;
1128 Py_SIZE(v) = ndigits;
1129 while (ival) {
1130 *p++ = (digit)(ival & PyLong_MASK);
1131 ival >>= PyLong_SHIFT;
1132 }
1133 }
1134 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135}
1136
Mark Dickinson8d48b432011-10-23 20:47:14 +01001137/* Get a C long long int from a long int object or any object that has an
1138 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001139
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001140PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001141PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyLongObject *v;
1144 PY_LONG_LONG bytes;
1145 int one = 1;
1146 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (vv == NULL) {
1149 PyErr_BadInternalCall();
1150 return -1;
1151 }
1152 if (!PyLong_Check(vv)) {
1153 PyNumberMethods *nb;
1154 PyObject *io;
1155 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1156 nb->nb_int == NULL) {
1157 PyErr_SetString(PyExc_TypeError, "an integer is required");
1158 return -1;
1159 }
1160 io = (*nb->nb_int) (vv);
1161 if (io == NULL)
1162 return -1;
1163 if (PyLong_Check(io)) {
1164 bytes = PyLong_AsLongLong(io);
1165 Py_DECREF(io);
1166 return bytes;
1167 }
1168 Py_DECREF(io);
1169 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1170 return -1;
1171 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 v = (PyLongObject*)vv;
1174 switch(Py_SIZE(v)) {
1175 case -1: return -(sdigit)v->ob_digit[0];
1176 case 0: return 0;
1177 case 1: return v->ob_digit[0];
1178 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001179 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1180 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1183 if (res < 0)
1184 return (PY_LONG_LONG)-1;
1185 else
1186 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187}
1188
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001189/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001190 Return -1 and set an error if overflow occurs. */
1191
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001192unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001193PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyLongObject *v;
1196 unsigned PY_LONG_LONG bytes;
1197 int one = 1;
1198 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001199
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001200 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyErr_BadInternalCall();
1202 return (unsigned PY_LONG_LONG)-1;
1203 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001204 if (!PyLong_Check(vv)) {
1205 PyErr_SetString(PyExc_TypeError, "an integer is required");
1206 return (unsigned PY_LONG_LONG)-1;
1207 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 v = (PyLongObject*)vv;
1210 switch(Py_SIZE(v)) {
1211 case 0: return 0;
1212 case 1: return v->ob_digit[0];
1213 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001214
Mark Dickinson22b20182010-05-10 21:27:53 +00001215 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1216 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1219 if (res < 0)
1220 return (unsigned PY_LONG_LONG)res;
1221 else
1222 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001223}
Tim Petersd1a7da62001-06-13 00:35:57 +00001224
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225/* Get a C unsigned long int from a long int object, ignoring the high bits.
1226 Returns -1 and sets an error condition if an error occurs. */
1227
Guido van Rossumddefaf32007-01-14 03:31:43 +00001228static unsigned PY_LONG_LONG
1229_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 register PyLongObject *v;
1232 unsigned PY_LONG_LONG x;
1233 Py_ssize_t i;
1234 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (vv == NULL || !PyLong_Check(vv)) {
1237 PyErr_BadInternalCall();
1238 return (unsigned long) -1;
1239 }
1240 v = (PyLongObject *)vv;
1241 switch(Py_SIZE(v)) {
1242 case 0: return 0;
1243 case 1: return v->ob_digit[0];
1244 }
1245 i = Py_SIZE(v);
1246 sign = 1;
1247 x = 0;
1248 if (i < 0) {
1249 sign = -1;
1250 i = -i;
1251 }
1252 while (--i >= 0) {
1253 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1254 }
1255 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001256}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257
1258unsigned PY_LONG_LONG
1259PyLong_AsUnsignedLongLongMask(register PyObject *op)
1260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyNumberMethods *nb;
1262 PyLongObject *lo;
1263 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (op && PyLong_Check(op))
1266 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1269 nb->nb_int == NULL) {
1270 PyErr_SetString(PyExc_TypeError, "an integer is required");
1271 return (unsigned PY_LONG_LONG)-1;
1272 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 lo = (PyLongObject*) (*nb->nb_int) (op);
1275 if (lo == NULL)
1276 return (unsigned PY_LONG_LONG)-1;
1277 if (PyLong_Check(lo)) {
1278 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1279 Py_DECREF(lo);
1280 if (PyErr_Occurred())
1281 return (unsigned PY_LONG_LONG)-1;
1282 return val;
1283 }
1284 else
1285 {
1286 Py_DECREF(lo);
1287 PyErr_SetString(PyExc_TypeError,
1288 "nb_int should return int object");
1289 return (unsigned PY_LONG_LONG)-1;
1290 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001291}
Tim Petersd1a7da62001-06-13 00:35:57 +00001292#undef IS_LITTLE_ENDIAN
1293
Mark Dickinson8d48b432011-10-23 20:47:14 +01001294/* Get a C long long int from a long int object or any object that has an
1295 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001296
Mark Dickinson8d48b432011-10-23 20:47:14 +01001297 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1298 the result. Otherwise *overflow is 0.
1299
1300 For other errors (e.g., TypeError), return -1 and set an error condition.
1301 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001302*/
1303
1304PY_LONG_LONG
1305PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* This version by Tim Peters */
1308 register PyLongObject *v;
1309 unsigned PY_LONG_LONG x, prev;
1310 PY_LONG_LONG res;
1311 Py_ssize_t i;
1312 int sign;
1313 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 *overflow = 0;
1316 if (vv == NULL) {
1317 PyErr_BadInternalCall();
1318 return -1;
1319 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!PyLong_Check(vv)) {
1322 PyNumberMethods *nb;
1323 nb = vv->ob_type->tp_as_number;
1324 if (nb == NULL || nb->nb_int == NULL) {
1325 PyErr_SetString(PyExc_TypeError,
1326 "an integer is required");
1327 return -1;
1328 }
1329 vv = (*nb->nb_int) (vv);
1330 if (vv == NULL)
1331 return -1;
1332 do_decref = 1;
1333 if (!PyLong_Check(vv)) {
1334 Py_DECREF(vv);
1335 PyErr_SetString(PyExc_TypeError,
1336 "nb_int should return int object");
1337 return -1;
1338 }
1339 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 res = -1;
1342 v = (PyLongObject *)vv;
1343 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 switch (i) {
1346 case -1:
1347 res = -(sdigit)v->ob_digit[0];
1348 break;
1349 case 0:
1350 res = 0;
1351 break;
1352 case 1:
1353 res = v->ob_digit[0];
1354 break;
1355 default:
1356 sign = 1;
1357 x = 0;
1358 if (i < 0) {
1359 sign = -1;
1360 i = -(i);
1361 }
1362 while (--i >= 0) {
1363 prev = x;
1364 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1365 if ((x >> PyLong_SHIFT) != prev) {
1366 *overflow = sign;
1367 goto exit;
1368 }
1369 }
1370 /* Haven't lost any bits, but casting to long requires extra
1371 * care (see comment above).
1372 */
1373 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1374 res = (PY_LONG_LONG)x * sign;
1375 }
1376 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1377 res = PY_LLONG_MIN;
1378 }
1379 else {
1380 *overflow = sign;
1381 /* res is already set to -1 */
1382 }
1383 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001384 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (do_decref) {
1386 Py_DECREF(vv);
1387 }
1388 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001389}
1390
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001391#endif /* HAVE_LONG_LONG */
1392
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001393#define CHECK_BINOP(v,w) \
1394 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001395 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1396 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001397 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001398
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001399/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1400 2**k if d is nonzero, else 0. */
1401
1402static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1404 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001405};
1406
1407static int
1408bits_in_digit(digit d)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 int d_bits = 0;
1411 while (d >= 32) {
1412 d_bits += 6;
1413 d >>= 6;
1414 }
1415 d_bits += (int)BitLengthTable[d];
1416 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001417}
1418
Tim Peters877a2122002-08-12 05:09:36 +00001419/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1420 * is modified in place, by adding y to it. Carries are propagated as far as
1421 * x[m-1], and the remaining carry (0 or 1) is returned.
1422 */
1423static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001424v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Py_ssize_t i;
1427 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 assert(m >= n);
1430 for (i = 0; i < n; ++i) {
1431 carry += x[i] + y[i];
1432 x[i] = carry & PyLong_MASK;
1433 carry >>= PyLong_SHIFT;
1434 assert((carry & 1) == carry);
1435 }
1436 for (; carry && i < m; ++i) {
1437 carry += x[i];
1438 x[i] = carry & PyLong_MASK;
1439 carry >>= PyLong_SHIFT;
1440 assert((carry & 1) == carry);
1441 }
1442 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001443}
1444
1445/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1446 * is modified in place, by subtracting y from it. Borrows are propagated as
1447 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1448 */
1449static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001450v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_ssize_t i;
1453 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 assert(m >= n);
1456 for (i = 0; i < n; ++i) {
1457 borrow = x[i] - y[i] - borrow;
1458 x[i] = borrow & PyLong_MASK;
1459 borrow >>= PyLong_SHIFT;
1460 borrow &= 1; /* keep only 1 sign bit */
1461 }
1462 for (; borrow && i < m; ++i) {
1463 borrow = x[i] - borrow;
1464 x[i] = borrow & PyLong_MASK;
1465 borrow >>= PyLong_SHIFT;
1466 borrow &= 1;
1467 }
1468 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001469}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001470
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001471/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1472 * result in z[0:m], and return the d bits shifted out of the top.
1473 */
1474static digit
1475v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 Py_ssize_t i;
1478 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 assert(0 <= d && d < PyLong_SHIFT);
1481 for (i=0; i < m; i++) {
1482 twodigits acc = (twodigits)a[i] << d | carry;
1483 z[i] = (digit)acc & PyLong_MASK;
1484 carry = (digit)(acc >> PyLong_SHIFT);
1485 }
1486 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001487}
1488
1489/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1490 * result in z[0:m], and return the d bits shifted out of the bottom.
1491 */
1492static digit
1493v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 Py_ssize_t i;
1496 digit carry = 0;
1497 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 assert(0 <= d && d < PyLong_SHIFT);
1500 for (i=m; i-- > 0;) {
1501 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1502 carry = (digit)acc & mask;
1503 z[i] = (digit)(acc >> d);
1504 }
1505 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001506}
1507
Tim Peters212e6142001-07-14 12:23:19 +00001508/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1509 in pout, and returning the remainder. pin and pout point at the LSD.
1510 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001511 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001512 immutable. */
1513
1514static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001515inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 assert(n > 0 && n <= PyLong_MASK);
1520 pin += size;
1521 pout += size;
1522 while (--size >= 0) {
1523 digit hi;
1524 rem = (rem << PyLong_SHIFT) | *--pin;
1525 *--pout = hi = (digit)(rem / n);
1526 rem -= (twodigits)hi * n;
1527 }
1528 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001529}
1530
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001531/* Divide a long integer by a digit, returning both the quotient
1532 (as function result) and the remainder (through *prem).
1533 The sign of a is ignored; n should not be zero. */
1534
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001535static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001536divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 const Py_ssize_t size = ABS(Py_SIZE(a));
1539 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 assert(n > 0 && n <= PyLong_MASK);
1542 z = _PyLong_New(size);
1543 if (z == NULL)
1544 return NULL;
1545 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1546 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547}
1548
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001549/* Convert a long integer to a base 10 string. Returns a new non-shared
1550 string. (Return value is non-shared so that callers can modify the
1551 returned value if necessary.) */
1552
1553static PyObject *
1554long_to_decimal_string(PyObject *aa)
1555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 PyLongObject *scratch, *a;
1557 PyObject *str;
1558 Py_ssize_t size, strlen, size_a, i, j;
1559 digit *pout, *pin, rem, tenpow;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 unsigned char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 a = (PyLongObject *)aa;
1564 if (a == NULL || !PyLong_Check(a)) {
1565 PyErr_BadInternalCall();
1566 return NULL;
1567 }
1568 size_a = ABS(Py_SIZE(a));
1569 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* quick and dirty upper bound for the number of digits
1572 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 But log2(a) < size_a * PyLong_SHIFT, and
1577 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1578 > 3 * _PyLong_DECIMAL_SHIFT
1579 */
1580 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1581 PyErr_SetString(PyExc_OverflowError,
1582 "long is too large to format");
1583 return NULL;
1584 }
1585 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1586 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1587 scratch = _PyLong_New(size);
1588 if (scratch == NULL)
1589 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 /* convert array of base _PyLong_BASE digits in pin to an array of
1592 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1593 Volume 2 (3rd edn), section 4.4, Method 1b). */
1594 pin = a->ob_digit;
1595 pout = scratch->ob_digit;
1596 size = 0;
1597 for (i = size_a; --i >= 0; ) {
1598 digit hi = pin[i];
1599 for (j = 0; j < size; j++) {
1600 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1601 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1602 pout[j] = (digit)(z - (twodigits)hi *
1603 _PyLong_DECIMAL_BASE);
1604 }
1605 while (hi) {
1606 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1607 hi /= _PyLong_DECIMAL_BASE;
1608 }
1609 /* check for keyboard interrupt */
1610 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001611 Py_DECREF(scratch);
1612 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001613 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 }
1615 /* pout should have at least one digit, so that the case when a = 0
1616 works correctly */
1617 if (size == 0)
1618 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 /* calculate exact length of output string, and allocate */
1621 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1622 tenpow = 10;
1623 rem = pout[size-1];
1624 while (rem >= tenpow) {
1625 tenpow *= 10;
1626 strlen++;
1627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628 str = PyUnicode_New(strlen, '9');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (str == NULL) {
1630 Py_DECREF(scratch);
1631 return NULL;
1632 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 /* fill the string right-to-left */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 assert(PyUnicode_KIND(str) == PyUnicode_1BYTE_KIND);
1636 p = PyUnicode_1BYTE_DATA(str) + strlen;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 *p = '\0';
1638 /* pout[0] through pout[size-2] contribute exactly
1639 _PyLong_DECIMAL_SHIFT digits each */
1640 for (i=0; i < size - 1; i++) {
1641 rem = pout[i];
1642 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1643 *--p = '0' + rem % 10;
1644 rem /= 10;
1645 }
1646 }
1647 /* pout[size-1]: always produce at least one decimal digit */
1648 rem = pout[i];
1649 do {
1650 *--p = '0' + rem % 10;
1651 rem /= 10;
1652 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* and sign */
1655 if (negative)
1656 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* check we've counted correctly */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001659 assert(p == PyUnicode_1BYTE_DATA(str));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 Py_DECREF(scratch);
1661 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001662}
1663
Mark Dickinsoncd068122009-09-18 14:53:08 +00001664/* Convert a long int object to a string, using a given conversion base,
1665 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001666 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001667
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001668PyObject *
1669_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001672 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001673 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 Py_ssize_t size_a;
Mark Dickinsone2846542012-04-20 21:21:24 +01001675 Py_UCS1 *p;
1676 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 assert(base == 2 || base == 8 || base == 10 || base == 16);
1680 if (base == 10)
1681 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 if (a == NULL || !PyLong_Check(a)) {
1684 PyErr_BadInternalCall();
1685 return NULL;
1686 }
1687 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001688 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* Compute a rough upper bound for the length of the string */
1691 switch (base) {
1692 case 16:
1693 bits = 4;
1694 break;
1695 case 8:
1696 bits = 3;
1697 break;
1698 case 2:
1699 bits = 1;
1700 break;
1701 default:
1702 assert(0); /* shouldn't ever get here */
1703 bits = 0; /* to silence gcc warning */
1704 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001705
Mark Dickinsone2846542012-04-20 21:21:24 +01001706 /* Compute exact length 'sz' of output string. */
1707 if (size_a == 0) {
1708 sz = 3;
1709 }
1710 else {
1711 Py_ssize_t size_a_in_bits;
1712 /* Ensure overflow doesn't occur during computation of sz. */
1713 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1714 PyErr_SetString(PyExc_OverflowError,
1715 "int is too large to format");
1716 return NULL;
1717 }
1718 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1719 bits_in_digit(a->ob_digit[size_a - 1]);
1720 /* Allow 2 characters for prefix and 1 for a '-' sign. */
1721 sz = 2 + negative + (size_a_in_bits + (bits - 1)) / bits;
1722 }
1723
1724 v = PyUnicode_New(sz, 'x');
1725 if (v == NULL) {
1726 return NULL;
1727 }
1728 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
1729
1730 p = PyUnicode_1BYTE_DATA(v) + sz;
1731 if (size_a == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 *--p = '0';
1733 }
1734 else {
1735 /* JRH: special case for power-of-2 bases */
1736 twodigits accum = 0;
1737 int accumbits = 0; /* # of bits in accum */
Mark Dickinsone2846542012-04-20 21:21:24 +01001738 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 for (i = 0; i < size_a; ++i) {
1740 accum |= (twodigits)a->ob_digit[i] << accumbits;
1741 accumbits += PyLong_SHIFT;
1742 assert(accumbits >= bits);
1743 do {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001744 char cdigit;
1745 cdigit = (char)(accum & (base - 1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 cdigit += (cdigit < 10) ? '0' : 'a'-10;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 *--p = cdigit;
1748 accumbits -= bits;
1749 accum >>= bits;
1750 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1751 }
1752 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 if (base == 16)
1755 *--p = 'x';
1756 else if (base == 8)
1757 *--p = 'o';
1758 else /* (base == 2) */
1759 *--p = 'b';
1760 *--p = '0';
Mark Dickinsone2846542012-04-20 21:21:24 +01001761 if (negative)
1762 *--p = '-';
1763 assert(p == PyUnicode_1BYTE_DATA(v));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001765}
1766
Thomas Wouters477c8d52006-05-27 19:21:47 +00001767/* Table of digit values for 8-bit string -> integer conversion.
1768 * '0' maps to 0, ..., '9' maps to 9.
1769 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1770 * All other indices map to 37.
1771 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001772 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001773 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001774unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1776 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1777 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1778 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1779 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1780 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1784 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1785 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1786 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1787 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001791};
1792
1793/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001794 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1795 * non-digit (which may be *str!). A normalized long is returned.
1796 * The point to this routine is that it takes time linear in the number of
1797 * string characters.
1798 */
1799static PyLongObject *
1800long_from_binary_base(char **str, int base)
1801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 char *p = *str;
1803 char *start = p;
1804 int bits_per_char;
1805 Py_ssize_t n;
1806 PyLongObject *z;
1807 twodigits accum;
1808 int bits_in_accum;
1809 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1812 n = base;
1813 for (bits_per_char = -1; n; ++bits_per_char)
1814 n >>= 1;
1815 /* n <- total # of bits needed, while setting p to end-of-string */
1816 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1817 ++p;
1818 *str = p;
1819 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1820 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1821 if (n / bits_per_char < p - start) {
1822 PyErr_SetString(PyExc_ValueError,
1823 "int string too large to convert");
1824 return NULL;
1825 }
1826 n = n / PyLong_SHIFT;
1827 z = _PyLong_New(n);
1828 if (z == NULL)
1829 return NULL;
1830 /* Read string from right, and fill in long from left; i.e.,
1831 * from least to most significant in both.
1832 */
1833 accum = 0;
1834 bits_in_accum = 0;
1835 pdigit = z->ob_digit;
1836 while (--p >= start) {
1837 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1838 assert(k >= 0 && k < base);
1839 accum |= (twodigits)k << bits_in_accum;
1840 bits_in_accum += bits_per_char;
1841 if (bits_in_accum >= PyLong_SHIFT) {
1842 *pdigit++ = (digit)(accum & PyLong_MASK);
1843 assert(pdigit - z->ob_digit <= n);
1844 accum >>= PyLong_SHIFT;
1845 bits_in_accum -= PyLong_SHIFT;
1846 assert(bits_in_accum < PyLong_SHIFT);
1847 }
1848 }
1849 if (bits_in_accum) {
1850 assert(bits_in_accum <= PyLong_SHIFT);
1851 *pdigit++ = (digit)accum;
1852 assert(pdigit - z->ob_digit <= n);
1853 }
1854 while (pdigit - z->ob_digit < n)
1855 *pdigit++ = 0;
1856 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001857}
1858
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001859PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001860PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 int sign = 1, error_if_nonzero = 0;
1863 char *start, *orig_str = str;
1864 PyLongObject *z = NULL;
1865 PyObject *strobj;
1866 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if ((base != 0 && base < 2) || base > 36) {
1869 PyErr_SetString(PyExc_ValueError,
1870 "int() arg 2 must be >= 2 and <= 36");
1871 return NULL;
1872 }
1873 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1874 str++;
1875 if (*str == '+')
1876 ++str;
1877 else if (*str == '-') {
1878 ++str;
1879 sign = -1;
1880 }
1881 if (base == 0) {
1882 if (str[0] != '0')
1883 base = 10;
1884 else if (str[1] == 'x' || str[1] == 'X')
1885 base = 16;
1886 else if (str[1] == 'o' || str[1] == 'O')
1887 base = 8;
1888 else if (str[1] == 'b' || str[1] == 'B')
1889 base = 2;
1890 else {
1891 /* "old" (C-style) octal literal, now invalid.
1892 it might still be zero though */
1893 error_if_nonzero = 1;
1894 base = 10;
1895 }
1896 }
1897 if (str[0] == '0' &&
1898 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1899 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1900 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1901 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 start = str;
1904 if ((base & (base - 1)) == 0)
1905 z = long_from_binary_base(&str, base);
1906 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001907/***
1908Binary bases can be converted in time linear in the number of digits, because
1909Python's representation base is binary. Other bases (including decimal!) use
1910the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001911
Thomas Wouters477c8d52006-05-27 19:21:47 +00001912First some math: the largest integer that can be expressed in N base-B digits
1913is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1914case number of Python digits needed to hold it is the smallest integer n s.t.
1915
1916 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1917 BASE**n >= B**N [taking logs to base BASE]
1918 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1919
1920The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1921this quickly. A Python long with that much space is reserved near the start,
1922and the result is computed into it.
1923
1924The input string is actually treated as being in base base**i (i.e., i digits
1925are processed at a time), where two more static arrays hold:
1926
1927 convwidth_base[base] = the largest integer i such that base**i <= BASE
1928 convmultmax_base[base] = base ** convwidth_base[base]
1929
1930The first of these is the largest i such that i consecutive input digits
1931must fit in a single Python digit. The second is effectively the input
1932base we're really using.
1933
1934Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1935convmultmax_base[base], the result is "simply"
1936
1937 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1938
1939where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001940
1941Error analysis: as above, the number of Python digits `n` needed is worst-
1942case
1943
1944 n >= N * log(B)/log(BASE)
1945
1946where `N` is the number of input digits in base `B`. This is computed via
1947
1948 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1949
1950below. Two numeric concerns are how much space this can waste, and whether
1951the computed result can be too small. To be concrete, assume BASE = 2**15,
1952which is the default (and it's unlikely anyone changes that).
1953
1954Waste isn't a problem: provided the first input digit isn't 0, the difference
1955between the worst-case input with N digits and the smallest input with N
1956digits is about a factor of B, but B is small compared to BASE so at most
1957one allocated Python digit can remain unused on that count. If
1958N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1959and adding 1 returns a result 1 larger than necessary. However, that can't
1960happen: whenever B is a power of 2, long_from_binary_base() is called
1961instead, and it's impossible for B**i to be an integer power of 2**15 when
1962B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1963an exact integer when B is not a power of 2, since B**i has a prime factor
1964other than 2 in that case, but (2**15)**j's only prime factor is 2).
1965
1966The computed result can be too small if the true value of N*log(B)/log(BASE)
1967is a little bit larger than an exact integer, but due to roundoff errors (in
1968computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1969yields a numeric result a little less than that integer. Unfortunately, "how
1970close can a transcendental function get to an integer over some range?"
1971questions are generally theoretically intractable. Computer analysis via
1972continued fractions is practical: expand log(B)/log(BASE) via continued
1973fractions, giving a sequence i/j of "the best" rational approximations. Then
1974j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1975we can get very close to being in trouble, but very rarely. For example,
197676573 is a denominator in one of the continued-fraction approximations to
1977log(10)/log(2**15), and indeed:
1978
1979 >>> log(10)/log(2**15)*76573
1980 16958.000000654003
1981
1982is very close to an integer. If we were working with IEEE single-precision,
1983rounding errors could kill us. Finding worst cases in IEEE double-precision
1984requires better-than-double-precision log() functions, and Tim didn't bother.
1985Instead the code checks to see whether the allocated space is enough as each
1986new Python digit is added, and copies the whole thing to a larger long if not.
1987This should happen extremely rarely, and in fact I don't have a test case
1988that triggers it(!). Instead the code was tested by artificially allocating
1989just 1 digit at the start, so that the copying code was exercised for every
1990digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 register twodigits c; /* current input character */
1993 Py_ssize_t size_z;
1994 int i;
1995 int convwidth;
1996 twodigits convmultmax, convmult;
1997 digit *pz, *pzstop;
1998 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 static double log_base_BASE[37] = {0.0e0,};
2001 static int convwidth_base[37] = {0,};
2002 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (log_base_BASE[base] == 0.0) {
2005 twodigits convmax = base;
2006 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002007
Mark Dickinson22b20182010-05-10 21:27:53 +00002008 log_base_BASE[base] = (log((double)base) /
2009 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 for (;;) {
2011 twodigits next = convmax * base;
2012 if (next > PyLong_BASE)
2013 break;
2014 convmax = next;
2015 ++i;
2016 }
2017 convmultmax_base[base] = convmax;
2018 assert(i > 0);
2019 convwidth_base[base] = i;
2020 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* Find length of the string of numeric characters. */
2023 scan = str;
2024 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2025 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* Create a long object that can contain the largest possible
2028 * integer with this base and length. Note that there's no
2029 * need to initialize z->ob_digit -- no slot is read up before
2030 * being stored into.
2031 */
2032 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2033 /* Uncomment next line to test exceedingly rare copy code */
2034 /* size_z = 1; */
2035 assert(size_z > 0);
2036 z = _PyLong_New(size_z);
2037 if (z == NULL)
2038 return NULL;
2039 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* `convwidth` consecutive input digits are treated as a single
2042 * digit in base `convmultmax`.
2043 */
2044 convwidth = convwidth_base[base];
2045 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 /* Work ;-) */
2048 while (str < scan) {
2049 /* grab up to convwidth digits from the input string */
2050 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2051 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2052 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002053 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 assert(c < PyLong_BASE);
2055 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 convmult = convmultmax;
2058 /* Calculate the shift only if we couldn't get
2059 * convwidth digits.
2060 */
2061 if (i != convwidth) {
2062 convmult = base;
2063 for ( ; i > 1; --i)
2064 convmult *= base;
2065 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 /* Multiply z by convmult, and add c. */
2068 pz = z->ob_digit;
2069 pzstop = pz + Py_SIZE(z);
2070 for (; pz < pzstop; ++pz) {
2071 c += (twodigits)*pz * convmult;
2072 *pz = (digit)(c & PyLong_MASK);
2073 c >>= PyLong_SHIFT;
2074 }
2075 /* carry off the current end? */
2076 if (c) {
2077 assert(c < PyLong_BASE);
2078 if (Py_SIZE(z) < size_z) {
2079 *pz = (digit)c;
2080 ++Py_SIZE(z);
2081 }
2082 else {
2083 PyLongObject *tmp;
2084 /* Extremely rare. Get more space. */
2085 assert(Py_SIZE(z) == size_z);
2086 tmp = _PyLong_New(size_z + 1);
2087 if (tmp == NULL) {
2088 Py_DECREF(z);
2089 return NULL;
2090 }
2091 memcpy(tmp->ob_digit,
2092 z->ob_digit,
2093 sizeof(digit) * size_z);
2094 Py_DECREF(z);
2095 z = tmp;
2096 z->ob_digit[size_z] = (digit)c;
2097 ++size_z;
2098 }
2099 }
2100 }
2101 }
2102 if (z == NULL)
2103 return NULL;
2104 if (error_if_nonzero) {
2105 /* reset the base to 0, else the exception message
2106 doesn't make too much sense */
2107 base = 0;
2108 if (Py_SIZE(z) != 0)
2109 goto onError;
2110 /* there might still be other problems, therefore base
2111 remains zero here for the same reason */
2112 }
2113 if (str == start)
2114 goto onError;
2115 if (sign < 0)
2116 Py_SIZE(z) = -(Py_SIZE(z));
2117 while (*str && isspace(Py_CHARMASK(*str)))
2118 str++;
2119 if (*str != '\0')
2120 goto onError;
2121 if (pend)
2122 *pend = str;
2123 long_normalize(z);
2124 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002125
Mark Dickinson22b20182010-05-10 21:27:53 +00002126 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 Py_XDECREF(z);
2128 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2129 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2130 if (strobj == NULL)
2131 return NULL;
2132 PyErr_Format(PyExc_ValueError,
2133 "invalid literal for int() with base %d: %R",
2134 base, strobj);
2135 Py_DECREF(strobj);
2136 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002137}
2138
2139PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002140PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002141{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002142 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2143 if (unicode == NULL)
2144 return NULL;
2145 v = PyLong_FromUnicodeObject(unicode, base);
2146 Py_DECREF(unicode);
2147 return v;
2148}
2149
2150PyObject *
2151PyLong_FromUnicodeObject(PyObject *u, int base)
2152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002154 PyObject *asciidig;
2155 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002156 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002158 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002159 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002161 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002162 if (buffer == NULL) {
2163 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 return NULL;
2165 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002166 result = PyLong_FromString(buffer, &end, base);
2167 if (result != NULL && end != buffer + buflen) {
2168 PyErr_SetString(PyExc_ValueError,
2169 "null byte in argument for int()");
2170 Py_DECREF(result);
2171 result = NULL;
2172 }
2173 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002175}
2176
Tim Peters9f688bf2000-07-07 15:53:28 +00002177/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002178static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002180static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002181
2182/* Long division with remainder, top-level routine */
2183
Guido van Rossume32e0141992-01-19 16:31:05 +00002184static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002185long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2189 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (size_b == 0) {
2192 PyErr_SetString(PyExc_ZeroDivisionError,
2193 "integer division or modulo by zero");
2194 return -1;
2195 }
2196 if (size_a < size_b ||
2197 (size_a == size_b &&
2198 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2199 /* |a| < |b|. */
2200 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2201 if (*pdiv == NULL)
2202 return -1;
2203 Py_INCREF(a);
2204 *prem = (PyLongObject *) a;
2205 return 0;
2206 }
2207 if (size_b == 1) {
2208 digit rem = 0;
2209 z = divrem1(a, b->ob_digit[0], &rem);
2210 if (z == NULL)
2211 return -1;
2212 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2213 if (*prem == NULL) {
2214 Py_DECREF(z);
2215 return -1;
2216 }
2217 }
2218 else {
2219 z = x_divrem(a, b, prem);
2220 if (z == NULL)
2221 return -1;
2222 }
2223 /* Set the signs.
2224 The quotient z has the sign of a*b;
2225 the remainder r has the sign of a,
2226 so a = b*z + r. */
2227 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2228 NEGATE(z);
2229 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2230 NEGATE(*prem);
2231 *pdiv = maybe_small_long(z);
2232 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233}
2234
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002235/* Unsigned long division with remainder -- the algorithm. The arguments v1
2236 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002237
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002238static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002239x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 PyLongObject *v, *w, *a;
2242 Py_ssize_t i, k, size_v, size_w;
2243 int d;
2244 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2245 twodigits vv;
2246 sdigit zhi;
2247 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2250 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2251 handle the special case when the initial estimate q for a quotient
2252 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2253 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 /* allocate space; w will also be used to hold the final remainder */
2256 size_v = ABS(Py_SIZE(v1));
2257 size_w = ABS(Py_SIZE(w1));
2258 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2259 v = _PyLong_New(size_v+1);
2260 if (v == NULL) {
2261 *prem = NULL;
2262 return NULL;
2263 }
2264 w = _PyLong_New(size_w);
2265 if (w == NULL) {
2266 Py_DECREF(v);
2267 *prem = NULL;
2268 return NULL;
2269 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2272 shift v1 left by the same amount. Results go into w and v. */
2273 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2274 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2275 assert(carry == 0);
2276 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2277 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2278 v->ob_digit[size_v] = carry;
2279 size_v++;
2280 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2283 at most (and usually exactly) k = size_v - size_w digits. */
2284 k = size_v - size_w;
2285 assert(k >= 0);
2286 a = _PyLong_New(k);
2287 if (a == NULL) {
2288 Py_DECREF(w);
2289 Py_DECREF(v);
2290 *prem = NULL;
2291 return NULL;
2292 }
2293 v0 = v->ob_digit;
2294 w0 = w->ob_digit;
2295 wm1 = w0[size_w-1];
2296 wm2 = w0[size_w-2];
2297 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2298 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2299 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002302 Py_DECREF(a);
2303 Py_DECREF(w);
2304 Py_DECREF(v);
2305 *prem = NULL;
2306 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002307 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 /* estimate quotient digit q; may overestimate by 1 (rare) */
2310 vtop = vk[size_w];
2311 assert(vtop <= wm1);
2312 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2313 q = (digit)(vv / wm1);
2314 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2315 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2316 | vk[size_w-2])) {
2317 --q;
2318 r += wm1;
2319 if (r >= PyLong_BASE)
2320 break;
2321 }
2322 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2325 zhi = 0;
2326 for (i = 0; i < size_w; ++i) {
2327 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2328 -PyLong_BASE * q <= z < PyLong_BASE */
2329 z = (sdigit)vk[i] + zhi -
2330 (stwodigits)q * (stwodigits)w0[i];
2331 vk[i] = (digit)z & PyLong_MASK;
2332 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002333 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* add w back if q was too large (this branch taken rarely) */
2337 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2338 if ((sdigit)vtop + zhi < 0) {
2339 carry = 0;
2340 for (i = 0; i < size_w; ++i) {
2341 carry += vk[i] + w0[i];
2342 vk[i] = carry & PyLong_MASK;
2343 carry >>= PyLong_SHIFT;
2344 }
2345 --q;
2346 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* store quotient digit */
2349 assert(q < PyLong_BASE);
2350 *--ak = q;
2351 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 /* unshift remainder; we reuse w to store the result */
2354 carry = v_rshift(w0, v0, size_w, d);
2355 assert(carry==0);
2356 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 *prem = long_normalize(w);
2359 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002360}
2361
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002362/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2363 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2364 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2365 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2366 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2367 -1.0. */
2368
2369/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2370#if DBL_MANT_DIG == 53
2371#define EXP2_DBL_MANT_DIG 9007199254740992.0
2372#else
2373#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2374#endif
2375
2376double
2377_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2380 /* See below for why x_digits is always large enough. */
2381 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2382 double dx;
2383 /* Correction term for round-half-to-even rounding. For a digit x,
2384 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2385 multiple of 4, rounding ties to a multiple of 8. */
2386 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 a_size = ABS(Py_SIZE(a));
2389 if (a_size == 0) {
2390 /* Special case for 0: significand 0.0, exponent 0. */
2391 *e = 0;
2392 return 0.0;
2393 }
2394 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2395 /* The following is an overflow-free version of the check
2396 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2397 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2398 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2399 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002400 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2404 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 Number of digits needed for result: write // for floor division.
2407 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2416 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2419 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2420 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 in both cases.
2427 */
2428 if (a_bits <= DBL_MANT_DIG + 2) {
2429 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2430 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2431 x_size = 0;
2432 while (x_size < shift_digits)
2433 x_digits[x_size++] = 0;
2434 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2435 (int)shift_bits);
2436 x_size += a_size;
2437 x_digits[x_size++] = rem;
2438 }
2439 else {
2440 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2441 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2442 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2443 a_size - shift_digits, (int)shift_bits);
2444 x_size = a_size - shift_digits;
2445 /* For correct rounding below, we need the least significant
2446 bit of x to be 'sticky' for this shift: if any of the bits
2447 shifted out was nonzero, we set the least significant bit
2448 of x. */
2449 if (rem)
2450 x_digits[0] |= 1;
2451 else
2452 while (shift_digits > 0)
2453 if (a->ob_digit[--shift_digits]) {
2454 x_digits[0] |= 1;
2455 break;
2456 }
2457 }
Victor Stinner63941882011-09-29 00:42:28 +02002458 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* Round, and convert to double. */
2461 x_digits[0] += half_even_correction[x_digits[0] & 7];
2462 dx = x_digits[--x_size];
2463 while (x_size > 0)
2464 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /* Rescale; make correction if result is 1.0. */
2467 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2468 if (dx == 1.0) {
2469 if (a_bits == PY_SSIZE_T_MAX)
2470 goto overflow;
2471 dx = 0.5;
2472 a_bits += 1;
2473 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 *e = a_bits;
2476 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002477
2478 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* exponent > PY_SSIZE_T_MAX */
2480 PyErr_SetString(PyExc_OverflowError,
2481 "huge integer: number of bits overflows a Py_ssize_t");
2482 *e = 0;
2483 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002484}
2485
2486/* Get a C double from a long int object. Rounds to the nearest double,
2487 using the round-half-to-even rule in the case of a tie. */
2488
2489double
2490PyLong_AsDouble(PyObject *v)
2491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 Py_ssize_t exponent;
2493 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002494
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002495 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 PyErr_BadInternalCall();
2497 return -1.0;
2498 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002499 if (!PyLong_Check(v)) {
2500 PyErr_SetString(PyExc_TypeError, "an integer is required");
2501 return -1.0;
2502 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2504 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2505 PyErr_SetString(PyExc_OverflowError,
2506 "long int too large to convert to float");
2507 return -1.0;
2508 }
2509 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002510}
2511
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002512/* Methods */
2513
2514static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002515long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002518}
2519
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002520static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002521long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 if (Py_SIZE(a) != Py_SIZE(b)) {
2526 sign = Py_SIZE(a) - Py_SIZE(b);
2527 }
2528 else {
2529 Py_ssize_t i = ABS(Py_SIZE(a));
2530 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2531 ;
2532 if (i < 0)
2533 sign = 0;
2534 else {
2535 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2536 if (Py_SIZE(a) < 0)
2537 sign = -sign;
2538 }
2539 }
2540 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002541}
2542
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002543#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002545
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002546static PyObject *
2547long_richcompare(PyObject *self, PyObject *other, int op)
2548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 int result;
2550 PyObject *v;
2551 CHECK_BINOP(self, other);
2552 if (self == other)
2553 result = 0;
2554 else
2555 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2556 /* Convert the return value to a Boolean */
2557 switch (op) {
2558 case Py_EQ:
2559 v = TEST_COND(result == 0);
2560 break;
2561 case Py_NE:
2562 v = TEST_COND(result != 0);
2563 break;
2564 case Py_LE:
2565 v = TEST_COND(result <= 0);
2566 break;
2567 case Py_GE:
2568 v = TEST_COND(result >= 0);
2569 break;
2570 case Py_LT:
2571 v = TEST_COND(result == -1);
2572 break;
2573 case Py_GT:
2574 v = TEST_COND(result == 1);
2575 break;
2576 default:
2577 PyErr_BadArgument();
2578 return NULL;
2579 }
2580 Py_INCREF(v);
2581 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002582}
2583
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002584static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002585long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002586{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002587 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 Py_ssize_t i;
2589 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 i = Py_SIZE(v);
2592 switch(i) {
2593 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2594 case 0: return 0;
2595 case 1: return v->ob_digit[0];
2596 }
2597 sign = 1;
2598 x = 0;
2599 if (i < 0) {
2600 sign = -1;
2601 i = -(i);
2602 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002604 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2605 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2606 _PyHASH_MODULUS.
2607
2608 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2609 amounts to a rotation of the bits of x. To see this, write
2610
2611 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2612
2613 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2614 PyLong_SHIFT bits of x (those that are shifted out of the
2615 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2616 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2617 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2618 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2619 congruent to y modulo _PyHASH_MODULUS. So
2620
2621 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2622
2623 The right-hand side is just the result of rotating the
2624 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2625 not all _PyHASH_BITS bits of x are 1s, the same is true
2626 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2627 the reduction of x*2**PyLong_SHIFT modulo
2628 _PyHASH_MODULUS. */
2629 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2630 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002632 if (x >= _PyHASH_MODULUS)
2633 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 }
2635 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002636 if (x == (Py_uhash_t)-1)
2637 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002638 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002639}
2640
2641
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002642/* Add the absolute values of two long integers. */
2643
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002644static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002645x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2648 PyLongObject *z;
2649 Py_ssize_t i;
2650 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* Ensure a is the larger of the two: */
2653 if (size_a < size_b) {
2654 { PyLongObject *temp = a; a = b; b = temp; }
2655 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002656 size_a = size_b;
2657 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 }
2659 z = _PyLong_New(size_a+1);
2660 if (z == NULL)
2661 return NULL;
2662 for (i = 0; i < size_b; ++i) {
2663 carry += a->ob_digit[i] + b->ob_digit[i];
2664 z->ob_digit[i] = carry & PyLong_MASK;
2665 carry >>= PyLong_SHIFT;
2666 }
2667 for (; i < size_a; ++i) {
2668 carry += a->ob_digit[i];
2669 z->ob_digit[i] = carry & PyLong_MASK;
2670 carry >>= PyLong_SHIFT;
2671 }
2672 z->ob_digit[i] = carry;
2673 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002674}
2675
2676/* Subtract the absolute values of two integers. */
2677
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002678static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002679x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2682 PyLongObject *z;
2683 Py_ssize_t i;
2684 int sign = 1;
2685 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 /* Ensure a is the larger of the two: */
2688 if (size_a < size_b) {
2689 sign = -1;
2690 { PyLongObject *temp = a; a = b; b = temp; }
2691 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002692 size_a = size_b;
2693 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
2695 else if (size_a == size_b) {
2696 /* Find highest digit where a and b differ: */
2697 i = size_a;
2698 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2699 ;
2700 if (i < 0)
2701 return (PyLongObject *)PyLong_FromLong(0);
2702 if (a->ob_digit[i] < b->ob_digit[i]) {
2703 sign = -1;
2704 { PyLongObject *temp = a; a = b; b = temp; }
2705 }
2706 size_a = size_b = i+1;
2707 }
2708 z = _PyLong_New(size_a);
2709 if (z == NULL)
2710 return NULL;
2711 for (i = 0; i < size_b; ++i) {
2712 /* The following assumes unsigned arithmetic
2713 works module 2**N for some N>PyLong_SHIFT. */
2714 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2715 z->ob_digit[i] = borrow & PyLong_MASK;
2716 borrow >>= PyLong_SHIFT;
2717 borrow &= 1; /* Keep only one sign bit */
2718 }
2719 for (; i < size_a; ++i) {
2720 borrow = a->ob_digit[i] - borrow;
2721 z->ob_digit[i] = borrow & PyLong_MASK;
2722 borrow >>= PyLong_SHIFT;
2723 borrow &= 1; /* Keep only one sign bit */
2724 }
2725 assert(borrow == 0);
2726 if (sign < 0)
2727 NEGATE(z);
2728 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002729}
2730
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002731static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002732long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2739 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2740 MEDIUM_VALUE(b));
2741 return result;
2742 }
2743 if (Py_SIZE(a) < 0) {
2744 if (Py_SIZE(b) < 0) {
2745 z = x_add(a, b);
2746 if (z != NULL && Py_SIZE(z) != 0)
2747 Py_SIZE(z) = -(Py_SIZE(z));
2748 }
2749 else
2750 z = x_sub(b, a);
2751 }
2752 else {
2753 if (Py_SIZE(b) < 0)
2754 z = x_sub(a, b);
2755 else
2756 z = x_add(a, b);
2757 }
2758 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002759}
2760
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002761static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002762long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2769 PyObject* r;
2770 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2771 return r;
2772 }
2773 if (Py_SIZE(a) < 0) {
2774 if (Py_SIZE(b) < 0)
2775 z = x_sub(a, b);
2776 else
2777 z = x_add(a, b);
2778 if (z != NULL && Py_SIZE(z) != 0)
2779 Py_SIZE(z) = -(Py_SIZE(z));
2780 }
2781 else {
2782 if (Py_SIZE(b) < 0)
2783 z = x_add(a, b);
2784 else
2785 z = x_sub(a, b);
2786 }
2787 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002788}
2789
Tim Peters5af4e6c2002-08-12 02:31:19 +00002790/* Grade school multiplication, ignoring the signs.
2791 * Returns the absolute value of the product, or NULL if error.
2792 */
2793static PyLongObject *
2794x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 PyLongObject *z;
2797 Py_ssize_t size_a = ABS(Py_SIZE(a));
2798 Py_ssize_t size_b = ABS(Py_SIZE(b));
2799 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 z = _PyLong_New(size_a + size_b);
2802 if (z == NULL)
2803 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2806 if (a == b) {
2807 /* Efficient squaring per HAC, Algorithm 14.16:
2808 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2809 * Gives slightly less than a 2x speedup when a == b,
2810 * via exploiting that each entry in the multiplication
2811 * pyramid appears twice (except for the size_a squares).
2812 */
2813 for (i = 0; i < size_a; ++i) {
2814 twodigits carry;
2815 twodigits f = a->ob_digit[i];
2816 digit *pz = z->ob_digit + (i << 1);
2817 digit *pa = a->ob_digit + i + 1;
2818 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002821 Py_DECREF(z);
2822 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002823 });
Tim Peters0973b992004-08-29 22:16:50 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 carry = *pz + f * f;
2826 *pz++ = (digit)(carry & PyLong_MASK);
2827 carry >>= PyLong_SHIFT;
2828 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 /* Now f is added in twice in each column of the
2831 * pyramid it appears. Same as adding f<<1 once.
2832 */
2833 f <<= 1;
2834 while (pa < paend) {
2835 carry += *pz + *pa++ * f;
2836 *pz++ = (digit)(carry & PyLong_MASK);
2837 carry >>= PyLong_SHIFT;
2838 assert(carry <= (PyLong_MASK << 1));
2839 }
2840 if (carry) {
2841 carry += *pz;
2842 *pz++ = (digit)(carry & PyLong_MASK);
2843 carry >>= PyLong_SHIFT;
2844 }
2845 if (carry)
2846 *pz += (digit)(carry & PyLong_MASK);
2847 assert((carry >> PyLong_SHIFT) == 0);
2848 }
2849 }
2850 else { /* a is not the same as b -- gradeschool long mult */
2851 for (i = 0; i < size_a; ++i) {
2852 twodigits carry = 0;
2853 twodigits f = a->ob_digit[i];
2854 digit *pz = z->ob_digit + i;
2855 digit *pb = b->ob_digit;
2856 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002859 Py_DECREF(z);
2860 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002861 });
Tim Peters0973b992004-08-29 22:16:50 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 while (pb < pbend) {
2864 carry += *pz + *pb++ * f;
2865 *pz++ = (digit)(carry & PyLong_MASK);
2866 carry >>= PyLong_SHIFT;
2867 assert(carry <= PyLong_MASK);
2868 }
2869 if (carry)
2870 *pz += (digit)(carry & PyLong_MASK);
2871 assert((carry >> PyLong_SHIFT) == 0);
2872 }
2873 }
2874 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002875}
2876
2877/* A helper for Karatsuba multiplication (k_mul).
2878 Takes a long "n" and an integer "size" representing the place to
2879 split, and sets low and high such that abs(n) == (high << size) + low,
2880 viewing the shift as being by digits. The sign bit is ignored, and
2881 the return values are >= 0.
2882 Returns 0 on success, -1 on failure.
2883*/
2884static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002885kmul_split(PyLongObject *n,
2886 Py_ssize_t size,
2887 PyLongObject **high,
2888 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 PyLongObject *hi, *lo;
2891 Py_ssize_t size_lo, size_hi;
2892 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002894 size_lo = MIN(size_n, size);
2895 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 if ((hi = _PyLong_New(size_hi)) == NULL)
2898 return -1;
2899 if ((lo = _PyLong_New(size_lo)) == NULL) {
2900 Py_DECREF(hi);
2901 return -1;
2902 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2905 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 *high = long_normalize(hi);
2908 *low = long_normalize(lo);
2909 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002910}
2911
Tim Peters60004642002-08-12 22:01:34 +00002912static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2913
Tim Peters5af4e6c2002-08-12 02:31:19 +00002914/* Karatsuba multiplication. Ignores the input signs, and returns the
2915 * absolute value of the product (or NULL if error).
2916 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2917 */
2918static PyLongObject *
2919k_mul(PyLongObject *a, PyLongObject *b)
2920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 Py_ssize_t asize = ABS(Py_SIZE(a));
2922 Py_ssize_t bsize = ABS(Py_SIZE(b));
2923 PyLongObject *ah = NULL;
2924 PyLongObject *al = NULL;
2925 PyLongObject *bh = NULL;
2926 PyLongObject *bl = NULL;
2927 PyLongObject *ret = NULL;
2928 PyLongObject *t1, *t2, *t3;
2929 Py_ssize_t shift; /* the number of digits we split off */
2930 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2933 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2934 * Then the original product is
2935 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2936 * By picking X to be a power of 2, "*X" is just shifting, and it's
2937 * been reduced to 3 multiplies on numbers half the size.
2938 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 /* We want to split based on the larger number; fiddle so that b
2941 * is largest.
2942 */
2943 if (asize > bsize) {
2944 t1 = a;
2945 a = b;
2946 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 i = asize;
2949 asize = bsize;
2950 bsize = i;
2951 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 /* Use gradeschool math when either number is too small. */
2954 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2955 if (asize <= i) {
2956 if (asize == 0)
2957 return (PyLongObject *)PyLong_FromLong(0);
2958 else
2959 return x_mul(a, b);
2960 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 /* If a is small compared to b, splitting on b gives a degenerate
2963 * case with ah==0, and Karatsuba may be (even much) less efficient
2964 * than "grade school" then. However, we can still win, by viewing
2965 * b as a string of "big digits", each of width a->ob_size. That
2966 * leads to a sequence of balanced calls to k_mul.
2967 */
2968 if (2 * asize <= bsize)
2969 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 /* Split a & b into hi & lo pieces. */
2972 shift = bsize >> 1;
2973 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2974 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 if (a == b) {
2977 bh = ah;
2978 bl = al;
2979 Py_INCREF(bh);
2980 Py_INCREF(bl);
2981 }
2982 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 /* The plan:
2985 * 1. Allocate result space (asize + bsize digits: that's always
2986 * enough).
2987 * 2. Compute ah*bh, and copy into result at 2*shift.
2988 * 3. Compute al*bl, and copy into result at 0. Note that this
2989 * can't overlap with #2.
2990 * 4. Subtract al*bl from the result, starting at shift. This may
2991 * underflow (borrow out of the high digit), but we don't care:
2992 * we're effectively doing unsigned arithmetic mod
2993 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2994 * borrows and carries out of the high digit can be ignored.
2995 * 5. Subtract ah*bh from the result, starting at shift.
2996 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2997 * at shift.
2998 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 /* 1. Allocate result space. */
3001 ret = _PyLong_New(asize + bsize);
3002 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003003#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 /* Fill with trash, to catch reference to uninitialized digits. */
3005 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003006#endif
Tim Peters44121a62002-08-12 06:17:58 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3009 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3010 assert(Py_SIZE(t1) >= 0);
3011 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3012 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3013 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 /* Zero-out the digits higher than the ah*bh copy. */
3016 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3017 if (i)
3018 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3019 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 /* 3. t2 <- al*bl, and copy into the low digits. */
3022 if ((t2 = k_mul(al, bl)) == NULL) {
3023 Py_DECREF(t1);
3024 goto fail;
3025 }
3026 assert(Py_SIZE(t2) >= 0);
3027 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3028 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 /* Zero out remaining digits. */
3031 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3032 if (i)
3033 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3036 * because it's fresher in cache.
3037 */
3038 i = Py_SIZE(ret) - shift; /* # digits after shift */
3039 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3040 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3043 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3046 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3047 Py_DECREF(ah);
3048 Py_DECREF(al);
3049 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (a == b) {
3052 t2 = t1;
3053 Py_INCREF(t2);
3054 }
3055 else if ((t2 = x_add(bh, bl)) == NULL) {
3056 Py_DECREF(t1);
3057 goto fail;
3058 }
3059 Py_DECREF(bh);
3060 Py_DECREF(bl);
3061 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 t3 = k_mul(t1, t2);
3064 Py_DECREF(t1);
3065 Py_DECREF(t2);
3066 if (t3 == NULL) goto fail;
3067 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 /* Add t3. It's not obvious why we can't run out of room here.
3070 * See the (*) comment after this function.
3071 */
3072 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3073 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003076
Mark Dickinson22b20182010-05-10 21:27:53 +00003077 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 Py_XDECREF(ret);
3079 Py_XDECREF(ah);
3080 Py_XDECREF(al);
3081 Py_XDECREF(bh);
3082 Py_XDECREF(bl);
3083 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003084}
3085
Tim Petersd6974a52002-08-13 20:37:51 +00003086/* (*) Why adding t3 can't "run out of room" above.
3087
Tim Petersab86c2b2002-08-15 20:06:00 +00003088Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3089to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003090
Tim Petersab86c2b2002-08-15 20:06:00 +000030911. For any integer i, i = c(i/2) + f(i/2). In particular,
3092 bsize = c(bsize/2) + f(bsize/2).
30932. shift = f(bsize/2)
30943. asize <= bsize
30954. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3096 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003097
Tim Petersab86c2b2002-08-15 20:06:00 +00003098We allocated asize + bsize result digits, and add t3 into them at an offset
3099of shift. This leaves asize+bsize-shift allocated digit positions for t3
3100to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3101asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003102
Tim Petersab86c2b2002-08-15 20:06:00 +00003103bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3104at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003105
Tim Petersab86c2b2002-08-15 20:06:00 +00003106If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3107digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3108most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003109
Tim Petersab86c2b2002-08-15 20:06:00 +00003110The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003111
Tim Petersab86c2b2002-08-15 20:06:00 +00003112 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003113
Tim Petersab86c2b2002-08-15 20:06:00 +00003114and we have asize + c(bsize/2) available digit positions. We need to show
3115this is always enough. An instance of c(bsize/2) cancels out in both, so
3116the question reduces to whether asize digits is enough to hold
3117(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3118then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3119asize 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 +00003120digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003121asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003122c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3123is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3124bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003125
Tim Peters48d52c02002-08-14 17:07:32 +00003126Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3127clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3128ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003129*/
3130
Tim Peters60004642002-08-12 22:01:34 +00003131/* b has at least twice the digits of a, and a is big enough that Karatsuba
3132 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3133 * of slices, each with a->ob_size digits, and multiply the slices by a,
3134 * one at a time. This gives k_mul balanced inputs to work with, and is
3135 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003136 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003137 * single-width slice overlap between successive partial sums).
3138 */
3139static PyLongObject *
3140k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 const Py_ssize_t asize = ABS(Py_SIZE(a));
3143 Py_ssize_t bsize = ABS(Py_SIZE(b));
3144 Py_ssize_t nbdone; /* # of b digits already multiplied */
3145 PyLongObject *ret;
3146 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 assert(asize > KARATSUBA_CUTOFF);
3149 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 /* Allocate result space, and zero it out. */
3152 ret = _PyLong_New(asize + bsize);
3153 if (ret == NULL)
3154 return NULL;
3155 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* Successive slices of b are copied into bslice. */
3158 bslice = _PyLong_New(asize);
3159 if (bslice == NULL)
3160 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 nbdone = 0;
3163 while (bsize > 0) {
3164 PyLongObject *product;
3165 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 /* Multiply the next slice of b by a. */
3168 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3169 nbtouse * sizeof(digit));
3170 Py_SIZE(bslice) = nbtouse;
3171 product = k_mul(a, bslice);
3172 if (product == NULL)
3173 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 /* Add into result. */
3176 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3177 product->ob_digit, Py_SIZE(product));
3178 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 bsize -= nbtouse;
3181 nbdone += nbtouse;
3182 }
Tim Peters60004642002-08-12 22:01:34 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 Py_DECREF(bslice);
3185 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003186
Mark Dickinson22b20182010-05-10 21:27:53 +00003187 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 Py_DECREF(ret);
3189 Py_XDECREF(bslice);
3190 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003191}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003192
3193static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003194long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 /* fast path for single-digit multiplication */
3201 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3202 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003203#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003205#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 /* if we don't have long long then we're almost certainly
3207 using 15-bit digits, so v will fit in a long. In the
3208 unlikely event that we're using 30-bit digits on a platform
3209 without long long, a large v will just cause us to fall
3210 through to the general multiplication code below. */
3211 if (v >= LONG_MIN && v <= LONG_MAX)
3212 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003213#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 z = k_mul(a, b);
3217 /* Negate if exactly one of the inputs is negative. */
3218 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3219 NEGATE(z);
3220 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003221}
3222
Guido van Rossume32e0141992-01-19 16:31:05 +00003223/* The / and % operators are now defined in terms of divmod().
3224 The expression a mod b has the value a - b*floor(a/b).
3225 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003226 |a| by |b|, with the sign of a. This is also expressed
3227 as a - b*trunc(a/b), if trunc truncates towards zero.
3228 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 a b a rem b a mod b
3230 13 10 3 3
3231 -13 10 -3 7
3232 13 -10 3 -7
3233 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003234 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003235 have different signs. We then subtract one from the 'div'
3236 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003237
Tim Peters47e52ee2004-08-30 02:44:38 +00003238/* Compute
3239 * *pdiv, *pmod = divmod(v, w)
3240 * NULL can be passed for pdiv or pmod, in which case that part of
3241 * the result is simply thrown away. The caller owns a reference to
3242 * each of these it requests (does not pass NULL for).
3243 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003244static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003245l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (long_divrem(v, w, &div, &mod) < 0)
3251 return -1;
3252 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3253 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3254 PyLongObject *temp;
3255 PyLongObject *one;
3256 temp = (PyLongObject *) long_add(mod, w);
3257 Py_DECREF(mod);
3258 mod = temp;
3259 if (mod == NULL) {
3260 Py_DECREF(div);
3261 return -1;
3262 }
3263 one = (PyLongObject *) PyLong_FromLong(1L);
3264 if (one == NULL ||
3265 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3266 Py_DECREF(mod);
3267 Py_DECREF(div);
3268 Py_XDECREF(one);
3269 return -1;
3270 }
3271 Py_DECREF(one);
3272 Py_DECREF(div);
3273 div = temp;
3274 }
3275 if (pdiv != NULL)
3276 *pdiv = div;
3277 else
3278 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 if (pmod != NULL)
3281 *pmod = mod;
3282 else
3283 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003286}
3287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003288static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003289long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003293 CHECK_BINOP(a, b);
3294 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3295 div = NULL;
3296 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003297}
3298
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003299/* PyLong/PyLong -> float, with correctly rounded result. */
3300
3301#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3302#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3303
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003304static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003305long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 PyLongObject *a, *b, *x;
3308 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3309 digit mask, low;
3310 int inexact, negate, a_is_small, b_is_small;
3311 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 CHECK_BINOP(v, w);
3314 a = (PyLongObject *)v;
3315 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 /*
3318 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3321 1. choose a suitable integer 'shift'
3322 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3323 3. adjust x for correct rounding
3324 4. convert x to a double dx with the same value
3325 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003327 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3330 returns either 0.0 or -0.0, depending on the sign of b. For a and
3331 b both nonzero, ignore signs of a and b, and add the sign back in
3332 at the end. Now write a_bits and b_bits for the bit lengths of a
3333 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3334 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3339 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3340 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3341 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 1. The integer 'shift' is chosen so that x has the right number of
3346 bits for a double, plus two or three extra bits that will be used
3347 in the rounding decisions. Writing a_bits and b_bits for the
3348 number of significant bits in a and b respectively, a
3349 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 This is fine in the usual case, but if a/b is smaller than the
3354 smallest normal float then it can lead to double rounding on an
3355 IEEE 754 platform, giving incorrectly rounded results. So we
3356 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 2. The quantity x is computed by first shifting a (left -shift bits
3361 if shift <= 0, right shift bits if shift > 0) and then dividing by
3362 b. For both the shift and the division, we keep track of whether
3363 the result is inexact, in a flag 'inexact'; this information is
3364 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 With the choice of shift above, together with our assumption that
3367 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3368 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3371 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 For float representability, we need x/2**extra_bits <
3376 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3377 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 To round, we just modify the bottom digit of x in-place; this can
3382 end up giving a digit with value > PyLONG_MASK, but that's not a
3383 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 With the original choices for shift above, extra_bits will always
3386 be 2 or 3. Then rounding under the round-half-to-even rule, we
3387 round up iff the most significant of the extra bits is 1, and
3388 either: (a) the computation of x in step 2 had an inexact result,
3389 or (b) at least one other of the extra bits is 1, or (c) the least
3390 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 4. Conversion to a double is straightforward; all floating-point
3393 operations involved in the conversion are exact, so there's no
3394 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3397 The result will always be exactly representable as a double, except
3398 in the case that it overflows. To avoid dependence on the exact
3399 behaviour of ldexp on overflow, we check for overflow before
3400 applying ldexp. The result of ldexp is adjusted for sign before
3401 returning.
3402 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 /* Reduce to case where a and b are both positive. */
3405 a_size = ABS(Py_SIZE(a));
3406 b_size = ABS(Py_SIZE(b));
3407 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3408 if (b_size == 0) {
3409 PyErr_SetString(PyExc_ZeroDivisionError,
3410 "division by zero");
3411 goto error;
3412 }
3413 if (a_size == 0)
3414 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 /* Fast path for a and b small (exactly representable in a double).
3417 Relies on floating-point division being correctly rounded; results
3418 may be subject to double rounding on x86 machines that operate with
3419 the x87 FPU set to 64-bit precision. */
3420 a_is_small = a_size <= MANT_DIG_DIGITS ||
3421 (a_size == MANT_DIG_DIGITS+1 &&
3422 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3423 b_is_small = b_size <= MANT_DIG_DIGITS ||
3424 (b_size == MANT_DIG_DIGITS+1 &&
3425 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3426 if (a_is_small && b_is_small) {
3427 double da, db;
3428 da = a->ob_digit[--a_size];
3429 while (a_size > 0)
3430 da = da * PyLong_BASE + a->ob_digit[--a_size];
3431 db = b->ob_digit[--b_size];
3432 while (b_size > 0)
3433 db = db * PyLong_BASE + b->ob_digit[--b_size];
3434 result = da / db;
3435 goto success;
3436 }
Tim Peterse2a60002001-09-04 06:17:36 +00003437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 /* Catch obvious cases of underflow and overflow */
3439 diff = a_size - b_size;
3440 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3441 /* Extreme overflow */
3442 goto overflow;
3443 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3444 /* Extreme underflow */
3445 goto underflow_or_zero;
3446 /* Next line is now safe from overflowing a Py_ssize_t */
3447 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3448 bits_in_digit(b->ob_digit[b_size - 1]);
3449 /* Now diff = a_bits - b_bits. */
3450 if (diff > DBL_MAX_EXP)
3451 goto overflow;
3452 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3453 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 /* Choose value for shift; see comments for step 1 above. */
3456 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 /* x = abs(a * 2**-shift) */
3461 if (shift <= 0) {
3462 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3463 digit rem;
3464 /* x = a << -shift */
3465 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3466 /* In practice, it's probably impossible to end up
3467 here. Both a and b would have to be enormous,
3468 using close to SIZE_T_MAX bytes of memory each. */
3469 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003470 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 goto error;
3472 }
3473 x = _PyLong_New(a_size + shift_digits + 1);
3474 if (x == NULL)
3475 goto error;
3476 for (i = 0; i < shift_digits; i++)
3477 x->ob_digit[i] = 0;
3478 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3479 a_size, -shift % PyLong_SHIFT);
3480 x->ob_digit[a_size + shift_digits] = rem;
3481 }
3482 else {
3483 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3484 digit rem;
3485 /* x = a >> shift */
3486 assert(a_size >= shift_digits);
3487 x = _PyLong_New(a_size - shift_digits);
3488 if (x == NULL)
3489 goto error;
3490 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3491 a_size - shift_digits, shift % PyLong_SHIFT);
3492 /* set inexact if any of the bits shifted out is nonzero */
3493 if (rem)
3494 inexact = 1;
3495 while (!inexact && shift_digits > 0)
3496 if (a->ob_digit[--shift_digits])
3497 inexact = 1;
3498 }
3499 long_normalize(x);
3500 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3503 reference to x, so it's safe to modify it in-place. */
3504 if (b_size == 1) {
3505 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3506 b->ob_digit[0]);
3507 long_normalize(x);
3508 if (rem)
3509 inexact = 1;
3510 }
3511 else {
3512 PyLongObject *div, *rem;
3513 div = x_divrem(x, b, &rem);
3514 Py_DECREF(x);
3515 x = div;
3516 if (x == NULL)
3517 goto error;
3518 if (Py_SIZE(rem))
3519 inexact = 1;
3520 Py_DECREF(rem);
3521 }
3522 x_size = ABS(Py_SIZE(x));
3523 assert(x_size > 0); /* result of division is never zero */
3524 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003526 /* The number of extra bits that have to be rounded away. */
3527 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3528 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 /* Round by directly modifying the low digit of x. */
3531 mask = (digit)1 << (extra_bits - 1);
3532 low = x->ob_digit[0] | inexact;
3533 if (low & mask && low & (3*mask-1))
3534 low += mask;
3535 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* Convert x to a double dx; the conversion is exact. */
3538 dx = x->ob_digit[--x_size];
3539 while (x_size > 0)
3540 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3541 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 /* Check whether ldexp result will overflow a double. */
3544 if (shift + x_bits >= DBL_MAX_EXP &&
3545 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3546 goto overflow;
3547 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003548
3549 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003551
3552 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003554
3555 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 PyErr_SetString(PyExc_OverflowError,
3557 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003558 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003560}
3561
3562static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003563long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 CHECK_BINOP(a, b);
3568
3569 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3570 mod = NULL;
3571 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003572}
3573
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003574static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003575long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 PyLongObject *div, *mod;
3578 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3583 return NULL;
3584 }
3585 z = PyTuple_New(2);
3586 if (z != NULL) {
3587 PyTuple_SetItem(z, 0, (PyObject *) div);
3588 PyTuple_SetItem(z, 1, (PyObject *) mod);
3589 }
3590 else {
3591 Py_DECREF(div);
3592 Py_DECREF(mod);
3593 }
3594 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003595}
3596
Tim Peters47e52ee2004-08-30 02:44:38 +00003597/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003598static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003599long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3602 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 PyLongObject *z = NULL; /* accumulated result */
3605 Py_ssize_t i, j, k; /* counters */
3606 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 /* 5-ary values. If the exponent is large enough, table is
3609 * precomputed so that table[i] == a**i % c for i in range(32).
3610 */
3611 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3612 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 /* a, b, c = v, w, x */
3615 CHECK_BINOP(v, w);
3616 a = (PyLongObject*)v; Py_INCREF(a);
3617 b = (PyLongObject*)w; Py_INCREF(b);
3618 if (PyLong_Check(x)) {
3619 c = (PyLongObject *)x;
3620 Py_INCREF(x);
3621 }
3622 else if (x == Py_None)
3623 c = NULL;
3624 else {
3625 Py_DECREF(a);
3626 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003627 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 }
Tim Peters4c483c42001-09-05 06:24:58 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3631 if (c) {
3632 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003633 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 goto Error;
3635 }
3636 else {
3637 /* else return a float. This works because we know
3638 that this calls float_pow() which converts its
3639 arguments to double. */
3640 Py_DECREF(a);
3641 Py_DECREF(b);
3642 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3643 }
3644 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 if (c) {
3647 /* if modulus == 0:
3648 raise ValueError() */
3649 if (Py_SIZE(c) == 0) {
3650 PyErr_SetString(PyExc_ValueError,
3651 "pow() 3rd argument cannot be 0");
3652 goto Error;
3653 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 /* if modulus < 0:
3656 negativeOutput = True
3657 modulus = -modulus */
3658 if (Py_SIZE(c) < 0) {
3659 negativeOutput = 1;
3660 temp = (PyLongObject *)_PyLong_Copy(c);
3661 if (temp == NULL)
3662 goto Error;
3663 Py_DECREF(c);
3664 c = temp;
3665 temp = NULL;
3666 NEGATE(c);
3667 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 /* if modulus == 1:
3670 return 0 */
3671 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3672 z = (PyLongObject *)PyLong_FromLong(0L);
3673 goto Done;
3674 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 /* if base < 0:
3677 base = base % modulus
3678 Having the base positive just makes things easier. */
3679 if (Py_SIZE(a) < 0) {
3680 if (l_divmod(a, c, NULL, &temp) < 0)
3681 goto Error;
3682 Py_DECREF(a);
3683 a = temp;
3684 temp = NULL;
3685 }
3686 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 /* At this point a, b, and c are guaranteed non-negative UNLESS
3689 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 z = (PyLongObject *)PyLong_FromLong(1L);
3692 if (z == NULL)
3693 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 /* Perform a modular reduction, X = X % c, but leave X alone if c
3696 * is NULL.
3697 */
3698#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003699 do { \
3700 if (c != NULL) { \
3701 if (l_divmod(X, c, NULL, &temp) < 0) \
3702 goto Error; \
3703 Py_XDECREF(X); \
3704 X = temp; \
3705 temp = NULL; \
3706 } \
3707 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 /* Multiply two values, then reduce the result:
3710 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003711#define MULT(X, Y, result) \
3712 do { \
3713 temp = (PyLongObject *)long_mul(X, Y); \
3714 if (temp == NULL) \
3715 goto Error; \
3716 Py_XDECREF(result); \
3717 result = temp; \
3718 temp = NULL; \
3719 REDUCE(result); \
3720 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3723 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3724 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3725 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3726 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003729 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003731 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 }
3733 }
3734 }
3735 else {
3736 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3737 Py_INCREF(z); /* still holds 1L */
3738 table[0] = z;
3739 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003740 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3743 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3746 const int index = (bi >> j) & 0x1f;
3747 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003748 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003750 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 }
3752 }
3753 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 if (negativeOutput && (Py_SIZE(z) != 0)) {
3756 temp = (PyLongObject *)long_sub(z, c);
3757 if (temp == NULL)
3758 goto Error;
3759 Py_DECREF(z);
3760 z = temp;
3761 temp = NULL;
3762 }
3763 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003764
Mark Dickinson22b20182010-05-10 21:27:53 +00003765 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 if (z != NULL) {
3767 Py_DECREF(z);
3768 z = NULL;
3769 }
3770 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003771 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3773 for (i = 0; i < 32; ++i)
3774 Py_XDECREF(table[i]);
3775 }
3776 Py_DECREF(a);
3777 Py_DECREF(b);
3778 Py_XDECREF(c);
3779 Py_XDECREF(temp);
3780 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003781}
3782
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003783static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003784long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003786 /* Implement ~x as -(x+1) */
3787 PyLongObject *x;
3788 PyLongObject *w;
3789 if (ABS(Py_SIZE(v)) <=1)
3790 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3791 w = (PyLongObject *)PyLong_FromLong(1L);
3792 if (w == NULL)
3793 return NULL;
3794 x = (PyLongObject *) long_add(v, w);
3795 Py_DECREF(w);
3796 if (x == NULL)
3797 return NULL;
3798 Py_SIZE(x) = -(Py_SIZE(x));
3799 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003800}
3801
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003802static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003803long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 PyLongObject *z;
3806 if (ABS(Py_SIZE(v)) <= 1)
3807 return PyLong_FromLong(-MEDIUM_VALUE(v));
3808 z = (PyLongObject *)_PyLong_Copy(v);
3809 if (z != NULL)
3810 Py_SIZE(z) = -(Py_SIZE(v));
3811 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003812}
3813
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003814static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003815long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 if (Py_SIZE(v) < 0)
3818 return long_neg(v);
3819 else
3820 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003821}
3822
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003823static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003824long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003827}
3828
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003829static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003830long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 PyLongObject *z = NULL;
3833 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3834 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 if (Py_SIZE(a) < 0) {
3839 /* Right shifting negative numbers is harder */
3840 PyLongObject *a1, *a2;
3841 a1 = (PyLongObject *) long_invert(a);
3842 if (a1 == NULL)
3843 goto rshift_error;
3844 a2 = (PyLongObject *) long_rshift(a1, b);
3845 Py_DECREF(a1);
3846 if (a2 == NULL)
3847 goto rshift_error;
3848 z = (PyLongObject *) long_invert(a2);
3849 Py_DECREF(a2);
3850 }
3851 else {
3852 shiftby = PyLong_AsSsize_t((PyObject *)b);
3853 if (shiftby == -1L && PyErr_Occurred())
3854 goto rshift_error;
3855 if (shiftby < 0) {
3856 PyErr_SetString(PyExc_ValueError,
3857 "negative shift count");
3858 goto rshift_error;
3859 }
3860 wordshift = shiftby / PyLong_SHIFT;
3861 newsize = ABS(Py_SIZE(a)) - wordshift;
3862 if (newsize <= 0)
3863 return PyLong_FromLong(0);
3864 loshift = shiftby % PyLong_SHIFT;
3865 hishift = PyLong_SHIFT - loshift;
3866 lomask = ((digit)1 << hishift) - 1;
3867 himask = PyLong_MASK ^ lomask;
3868 z = _PyLong_New(newsize);
3869 if (z == NULL)
3870 goto rshift_error;
3871 if (Py_SIZE(a) < 0)
3872 Py_SIZE(z) = -(Py_SIZE(z));
3873 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3874 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3875 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003876 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 }
3878 z = long_normalize(z);
3879 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003880 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003882
Guido van Rossumc6913e71991-11-19 20:26:46 +00003883}
3884
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003885static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003886long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 /* This version due to Tim Peters */
3889 PyLongObject *a = (PyLongObject*)v;
3890 PyLongObject *b = (PyLongObject*)w;
3891 PyLongObject *z = NULL;
3892 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3893 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003897 shiftby = PyLong_AsSsize_t((PyObject *)b);
3898 if (shiftby == -1L && PyErr_Occurred())
3899 goto lshift_error;
3900 if (shiftby < 0) {
3901 PyErr_SetString(PyExc_ValueError, "negative shift count");
3902 goto lshift_error;
3903 }
3904 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3905 wordshift = shiftby / PyLong_SHIFT;
3906 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 oldsize = ABS(Py_SIZE(a));
3909 newsize = oldsize + wordshift;
3910 if (remshift)
3911 ++newsize;
3912 z = _PyLong_New(newsize);
3913 if (z == NULL)
3914 goto lshift_error;
3915 if (Py_SIZE(a) < 0)
3916 NEGATE(z);
3917 for (i = 0; i < wordshift; i++)
3918 z->ob_digit[i] = 0;
3919 accum = 0;
3920 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3921 accum |= (twodigits)a->ob_digit[j] << remshift;
3922 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3923 accum >>= PyLong_SHIFT;
3924 }
3925 if (remshift)
3926 z->ob_digit[newsize-1] = (digit)accum;
3927 else
3928 assert(!accum);
3929 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003930 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003932}
3933
Mark Dickinson27a87a22009-10-25 20:43:34 +00003934/* Compute two's complement of digit vector a[0:m], writing result to
3935 z[0:m]. The digit vector a need not be normalized, but should not
3936 be entirely zero. a and z may point to the same digit vector. */
3937
3938static void
3939v_complement(digit *z, digit *a, Py_ssize_t m)
3940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 Py_ssize_t i;
3942 digit carry = 1;
3943 for (i = 0; i < m; ++i) {
3944 carry += a[i] ^ PyLong_MASK;
3945 z[i] = carry & PyLong_MASK;
3946 carry >>= PyLong_SHIFT;
3947 }
3948 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003949}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003950
3951/* Bitwise and/xor/or operations */
3952
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003953static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003954long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003956 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003958 int nega, negb, negz;
3959 Py_ssize_t size_a, size_b, size_z, i;
3960 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 /* Bitwise operations for negative numbers operate as though
3963 on a two's complement representation. So convert arguments
3964 from sign-magnitude to two's complement, and convert the
3965 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* If a is negative, replace it by its two's complement. */
3968 size_a = ABS(Py_SIZE(a));
3969 nega = Py_SIZE(a) < 0;
3970 if (nega) {
3971 z = _PyLong_New(size_a);
3972 if (z == NULL)
3973 return NULL;
3974 v_complement(z->ob_digit, a->ob_digit, size_a);
3975 a = z;
3976 }
3977 else
3978 /* Keep reference count consistent. */
3979 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 /* Same for b. */
3982 size_b = ABS(Py_SIZE(b));
3983 negb = Py_SIZE(b) < 0;
3984 if (negb) {
3985 z = _PyLong_New(size_b);
3986 if (z == NULL) {
3987 Py_DECREF(a);
3988 return NULL;
3989 }
3990 v_complement(z->ob_digit, b->ob_digit, size_b);
3991 b = z;
3992 }
3993 else
3994 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003996 /* Swap a and b if necessary to ensure size_a >= size_b. */
3997 if (size_a < size_b) {
3998 z = a; a = b; b = z;
3999 size_z = size_a; size_a = size_b; size_b = size_z;
4000 negz = nega; nega = negb; negb = negz;
4001 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 /* JRH: The original logic here was to allocate the result value (z)
4004 as the longer of the two operands. However, there are some cases
4005 where the result is guaranteed to be shorter than that: AND of two
4006 positives, OR of two negatives: use the shorter number. AND with
4007 mixed signs: use the positive number. OR with mixed signs: use the
4008 negative number.
4009 */
4010 switch (op) {
4011 case '^':
4012 negz = nega ^ negb;
4013 size_z = size_a;
4014 break;
4015 case '&':
4016 negz = nega & negb;
4017 size_z = negb ? size_a : size_b;
4018 break;
4019 case '|':
4020 negz = nega | negb;
4021 size_z = negb ? size_b : size_a;
4022 break;
4023 default:
4024 PyErr_BadArgument();
4025 return NULL;
4026 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 /* We allow an extra digit if z is negative, to make sure that
4029 the final two's complement of z doesn't overflow. */
4030 z = _PyLong_New(size_z + negz);
4031 if (z == NULL) {
4032 Py_DECREF(a);
4033 Py_DECREF(b);
4034 return NULL;
4035 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 /* Compute digits for overlap of a and b. */
4038 switch(op) {
4039 case '&':
4040 for (i = 0; i < size_b; ++i)
4041 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4042 break;
4043 case '|':
4044 for (i = 0; i < size_b; ++i)
4045 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4046 break;
4047 case '^':
4048 for (i = 0; i < size_b; ++i)
4049 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4050 break;
4051 default:
4052 PyErr_BadArgument();
4053 return NULL;
4054 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 /* Copy any remaining digits of a, inverting if necessary. */
4057 if (op == '^' && negb)
4058 for (; i < size_z; ++i)
4059 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4060 else if (i < size_z)
4061 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4062 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004064 /* Complement result if negative. */
4065 if (negz) {
4066 Py_SIZE(z) = -(Py_SIZE(z));
4067 z->ob_digit[size_z] = PyLong_MASK;
4068 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4069 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004071 Py_DECREF(a);
4072 Py_DECREF(b);
4073 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004074}
4075
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004076static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004077long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 PyObject *c;
4080 CHECK_BINOP(a, b);
4081 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4082 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004083}
4084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004085static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004086long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004088 PyObject *c;
4089 CHECK_BINOP(a, b);
4090 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4091 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004092}
4093
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004094static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004095long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 PyObject *c;
4098 CHECK_BINOP(a, b);
4099 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4100 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004101}
4102
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004103static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004104long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004106 if (PyLong_CheckExact(v))
4107 Py_INCREF(v);
4108 else
4109 v = _PyLong_Copy((PyLongObject *)v);
4110 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004111}
4112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004113static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004114long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 double result;
4117 result = PyLong_AsDouble(v);
4118 if (result == -1.0 && PyErr_Occurred())
4119 return NULL;
4120 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004121}
4122
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004123static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004124long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004125
Tim Peters6d6c1a32001-08-02 04:15:00 +00004126static PyObject *
4127long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4128{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004129 PyObject *obase = NULL, *x = NULL;
4130 long base;
4131 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 if (type != &PyLong_Type)
4135 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004136 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4137 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004138 return NULL;
4139 if (x == NULL)
4140 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004141 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004143
4144 base = PyLong_AsLongAndOverflow(obase, &overflow);
4145 if (base == -1 && PyErr_Occurred())
4146 return NULL;
4147 if (overflow || (base != 0 && base < 2) || base > 36) {
4148 PyErr_SetString(PyExc_ValueError,
4149 "int() arg 2 must be >= 2 and <= 36");
4150 return NULL;
4151 }
4152
4153 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004154 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004155 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4156 /* Since PyLong_FromString doesn't have a length parameter,
4157 * check here for possible NULs in the string. */
4158 char *string;
4159 Py_ssize_t size = Py_SIZE(x);
4160 if (PyByteArray_Check(x))
4161 string = PyByteArray_AS_STRING(x);
4162 else
4163 string = PyBytes_AS_STRING(x);
4164 if (strlen(string) != (size_t)size) {
4165 /* We only see this if there's a null byte in x,
4166 x is a bytes or buffer, *and* a base is given. */
4167 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004168 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004169 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 return NULL;
4171 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004172 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004173 }
4174 else {
4175 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004176 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 return NULL;
4178 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004179}
4180
Guido van Rossumbef14172001-08-29 15:47:46 +00004181/* Wimpy, slow approach to tp_new calls for subtypes of long:
4182 first create a regular long from whatever arguments we got,
4183 then allocate a subtype instance and initialize it from
4184 the regular long. The regular long is then thrown away.
4185*/
4186static PyObject *
4187long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 PyLongObject *tmp, *newobj;
4190 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004192 assert(PyType_IsSubtype(type, &PyLong_Type));
4193 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4194 if (tmp == NULL)
4195 return NULL;
4196 assert(PyLong_CheckExact(tmp));
4197 n = Py_SIZE(tmp);
4198 if (n < 0)
4199 n = -n;
4200 newobj = (PyLongObject *)type->tp_alloc(type, n);
4201 if (newobj == NULL) {
4202 Py_DECREF(tmp);
4203 return NULL;
4204 }
4205 assert(PyLong_Check(newobj));
4206 Py_SIZE(newobj) = Py_SIZE(tmp);
4207 for (i = 0; i < n; i++)
4208 newobj->ob_digit[i] = tmp->ob_digit[i];
4209 Py_DECREF(tmp);
4210 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004211}
4212
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004213static PyObject *
4214long_getnewargs(PyLongObject *v)
4215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004216 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004217}
4218
Guido van Rossumb43daf72007-08-01 18:08:08 +00004219static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004220long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004222}
4223
4224static PyObject *
4225long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004227}
4228
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004229static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004230long__format__(PyObject *self, PyObject *args)
4231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004232 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4235 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004236 return _PyLong_FormatAdvanced(self, format_spec, 0,
4237 PyUnicode_GET_LENGTH(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004238}
4239
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004240/* Return a pair (q, r) such that a = b * q + r, and
4241 abs(r) <= abs(b)/2, with equality possible only if q is even.
4242 In other words, q == a / b, rounded to the nearest integer using
4243 round-half-to-even. */
4244
4245PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004246_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004247{
4248 PyLongObject *quo = NULL, *rem = NULL;
4249 PyObject *one = NULL, *twice_rem, *result, *temp;
4250 int cmp, quo_is_odd, quo_is_neg;
4251
4252 /* Equivalent Python code:
4253
4254 def divmod_near(a, b):
4255 q, r = divmod(a, b)
4256 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4257 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4258 # positive, 2 * r < b if b negative.
4259 greater_than_half = 2*r > b if b > 0 else 2*r < b
4260 exactly_half = 2*r == b
4261 if greater_than_half or exactly_half and q % 2 == 1:
4262 q += 1
4263 r -= b
4264 return q, r
4265
4266 */
4267 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4268 PyErr_SetString(PyExc_TypeError,
4269 "non-integer arguments in division");
4270 return NULL;
4271 }
4272
4273 /* Do a and b have different signs? If so, quotient is negative. */
4274 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4275
4276 one = PyLong_FromLong(1L);
4277 if (one == NULL)
4278 return NULL;
4279
4280 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4281 goto error;
4282
4283 /* compare twice the remainder with the divisor, to see
4284 if we need to adjust the quotient and remainder */
4285 twice_rem = long_lshift((PyObject *)rem, one);
4286 if (twice_rem == NULL)
4287 goto error;
4288 if (quo_is_neg) {
4289 temp = long_neg((PyLongObject*)twice_rem);
4290 Py_DECREF(twice_rem);
4291 twice_rem = temp;
4292 if (twice_rem == NULL)
4293 goto error;
4294 }
4295 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4296 Py_DECREF(twice_rem);
4297
4298 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4299 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4300 /* fix up quotient */
4301 if (quo_is_neg)
4302 temp = long_sub(quo, (PyLongObject *)one);
4303 else
4304 temp = long_add(quo, (PyLongObject *)one);
4305 Py_DECREF(quo);
4306 quo = (PyLongObject *)temp;
4307 if (quo == NULL)
4308 goto error;
4309 /* and remainder */
4310 if (quo_is_neg)
4311 temp = long_add(rem, (PyLongObject *)b);
4312 else
4313 temp = long_sub(rem, (PyLongObject *)b);
4314 Py_DECREF(rem);
4315 rem = (PyLongObject *)temp;
4316 if (rem == NULL)
4317 goto error;
4318 }
4319
4320 result = PyTuple_New(2);
4321 if (result == NULL)
4322 goto error;
4323
4324 /* PyTuple_SET_ITEM steals references */
4325 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4326 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4327 Py_DECREF(one);
4328 return result;
4329
4330 error:
4331 Py_XDECREF(quo);
4332 Py_XDECREF(rem);
4333 Py_XDECREF(one);
4334 return NULL;
4335}
4336
Eric Smith8c663262007-08-25 02:26:07 +00004337static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004338long_round(PyObject *self, PyObject *args)
4339{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004340 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004341
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004342 /* To round an integer m to the nearest 10**n (n positive), we make use of
4343 * the divmod_near operation, defined by:
4344 *
4345 * divmod_near(a, b) = (q, r)
4346 *
4347 * where q is the nearest integer to the quotient a / b (the
4348 * nearest even integer in the case of a tie) and r == a - q * b.
4349 * Hence q * b = a - r is the nearest multiple of b to a,
4350 * preferring even multiples in the case of a tie.
4351 *
4352 * So the nearest multiple of 10**n to m is:
4353 *
4354 * m - divmod_near(m, 10**n)[1].
4355 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4357 return NULL;
4358 if (o_ndigits == NULL)
4359 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004360
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004361 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 if (ndigits == NULL)
4363 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004364
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004365 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 if (Py_SIZE(ndigits) >= 0) {
4367 Py_DECREF(ndigits);
4368 return long_long(self);
4369 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004370
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004371 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4372 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004374 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004376 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004377
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004378 result = PyLong_FromLong(10L);
4379 if (result == NULL) {
4380 Py_DECREF(ndigits);
4381 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004383
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004384 temp = long_pow(result, ndigits, Py_None);
4385 Py_DECREF(ndigits);
4386 Py_DECREF(result);
4387 result = temp;
4388 if (result == NULL)
4389 return NULL;
4390
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004391 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004392 Py_DECREF(result);
4393 result = temp;
4394 if (result == NULL)
4395 return NULL;
4396
4397 temp = long_sub((PyLongObject *)self,
4398 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4399 Py_DECREF(result);
4400 result = temp;
4401
4402 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004403}
4404
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004405static PyObject *
4406long_sizeof(PyLongObject *v)
4407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4411 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004412}
4413
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004414static PyObject *
4415long_bit_length(PyLongObject *v)
4416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 PyLongObject *result, *x, *y;
4418 Py_ssize_t ndigits, msd_bits = 0;
4419 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 assert(v != NULL);
4422 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 ndigits = ABS(Py_SIZE(v));
4425 if (ndigits == 0)
4426 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 msd = v->ob_digit[ndigits-1];
4429 while (msd >= 32) {
4430 msd_bits += 6;
4431 msd >>= 6;
4432 }
4433 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4436 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 /* expression above may overflow; use Python integers instead */
4439 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4440 if (result == NULL)
4441 return NULL;
4442 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4443 if (x == NULL)
4444 goto error;
4445 y = (PyLongObject *)long_mul(result, x);
4446 Py_DECREF(x);
4447 if (y == NULL)
4448 goto error;
4449 Py_DECREF(result);
4450 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4453 if (x == NULL)
4454 goto error;
4455 y = (PyLongObject *)long_add(result, x);
4456 Py_DECREF(x);
4457 if (y == NULL)
4458 goto error;
4459 Py_DECREF(result);
4460 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004463
Mark Dickinson22b20182010-05-10 21:27:53 +00004464 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 Py_DECREF(result);
4466 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004467}
4468
4469PyDoc_STRVAR(long_bit_length_doc,
4470"int.bit_length() -> int\n\
4471\n\
4472Number of bits necessary to represent self in binary.\n\
4473>>> bin(37)\n\
4474'0b100101'\n\
4475>>> (37).bit_length()\n\
44766");
4477
Christian Heimes53876d92008-04-19 00:31:39 +00004478#if 0
4479static PyObject *
4480long_is_finite(PyObject *v)
4481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004483}
4484#endif
4485
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004486
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004487static PyObject *
4488long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004490 PyObject *byteorder_str;
4491 PyObject *is_signed_obj = NULL;
4492 Py_ssize_t length;
4493 int little_endian;
4494 int is_signed;
4495 PyObject *bytes;
4496 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4499 &length, &byteorder_str,
4500 &is_signed_obj))
4501 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 if (args != NULL && Py_SIZE(args) > 2) {
4504 PyErr_SetString(PyExc_TypeError,
4505 "'signed' is a keyword-only argument");
4506 return NULL;
4507 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4510 little_endian = 1;
4511 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4512 little_endian = 0;
4513 else {
4514 PyErr_SetString(PyExc_ValueError,
4515 "byteorder must be either 'little' or 'big'");
4516 return NULL;
4517 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 if (is_signed_obj != NULL) {
4520 int cmp = PyObject_IsTrue(is_signed_obj);
4521 if (cmp < 0)
4522 return NULL;
4523 is_signed = cmp ? 1 : 0;
4524 }
4525 else {
4526 /* If the signed argument was omitted, use False as the
4527 default. */
4528 is_signed = 0;
4529 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 if (length < 0) {
4532 PyErr_SetString(PyExc_ValueError,
4533 "length argument must be non-negative");
4534 return NULL;
4535 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004537 bytes = PyBytes_FromStringAndSize(NULL, length);
4538 if (bytes == NULL)
4539 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4542 length, little_endian, is_signed) < 0) {
4543 Py_DECREF(bytes);
4544 return NULL;
4545 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004547 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004548}
4549
Mark Dickinson078c2532010-01-30 18:06:17 +00004550PyDoc_STRVAR(long_to_bytes_doc,
4551"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004552\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004553Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004554\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004556raised if the integer is not representable with the given number of\n\
4557bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004558\n\
4559The byteorder argument determines the byte order used to represent the\n\
4560integer. If byteorder is 'big', the most significant byte is at the\n\
4561beginning of the byte array. If byteorder is 'little', the most\n\
4562significant byte is at the end of the byte array. To request the native\n\
4563byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4564\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004565The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004567is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004568
4569static PyObject *
4570long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004572 PyObject *byteorder_str;
4573 PyObject *is_signed_obj = NULL;
4574 int little_endian;
4575 int is_signed;
4576 PyObject *obj;
4577 PyObject *bytes;
4578 PyObject *long_obj;
4579 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4582 &obj, &byteorder_str,
4583 &is_signed_obj))
4584 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004586 if (args != NULL && Py_SIZE(args) > 2) {
4587 PyErr_SetString(PyExc_TypeError,
4588 "'signed' is a keyword-only argument");
4589 return NULL;
4590 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4593 little_endian = 1;
4594 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4595 little_endian = 0;
4596 else {
4597 PyErr_SetString(PyExc_ValueError,
4598 "byteorder must be either 'little' or 'big'");
4599 return NULL;
4600 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 if (is_signed_obj != NULL) {
4603 int cmp = PyObject_IsTrue(is_signed_obj);
4604 if (cmp < 0)
4605 return NULL;
4606 is_signed = cmp ? 1 : 0;
4607 }
4608 else {
4609 /* If the signed argument was omitted, use False as the
4610 default. */
4611 is_signed = 0;
4612 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 bytes = PyObject_Bytes(obj);
4615 if (bytes == NULL)
4616 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 long_obj = _PyLong_FromByteArray(
4619 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4620 little_endian, is_signed);
4621 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 /* If from_bytes() was used on subclass, allocate new subclass
4624 * instance, initialize it with decoded long value and return it.
4625 */
4626 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4627 PyLongObject *newobj;
4628 int i;
4629 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 newobj = (PyLongObject *)type->tp_alloc(type, n);
4632 if (newobj == NULL) {
4633 Py_DECREF(long_obj);
4634 return NULL;
4635 }
4636 assert(PyLong_Check(newobj));
4637 Py_SIZE(newobj) = Py_SIZE(long_obj);
4638 for (i = 0; i < n; i++) {
4639 newobj->ob_digit[i] =
4640 ((PyLongObject *)long_obj)->ob_digit[i];
4641 }
4642 Py_DECREF(long_obj);
4643 return (PyObject *)newobj;
4644 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004647}
4648
Mark Dickinson078c2532010-01-30 18:06:17 +00004649PyDoc_STRVAR(long_from_bytes_doc,
4650"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4651\n\
4652Return the integer represented by the given array of bytes.\n\
4653\n\
4654The bytes argument must either support the buffer protocol or be an\n\
4655iterable object producing bytes. Bytes and bytearray are examples of\n\
4656built-in objects that support the buffer protocol.\n\
4657\n\
4658The byteorder argument determines the byte order used to represent the\n\
4659integer. If byteorder is 'big', the most significant byte is at the\n\
4660beginning of the byte array. If byteorder is 'little', the most\n\
4661significant byte is at the end of the byte array. To request the native\n\
4662byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4663\n\
4664The signed keyword-only argument indicates whether two's complement is\n\
4665used to represent the integer.");
4666
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004667static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4669 "Returns self, the complex conjugate of any int."},
4670 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4671 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004672#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4674 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004675#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 {"to_bytes", (PyCFunction)long_to_bytes,
4677 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4678 {"from_bytes", (PyCFunction)long_from_bytes,
4679 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4680 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4681 "Truncating an Integral returns itself."},
4682 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4683 "Flooring an Integral returns itself."},
4684 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4685 "Ceiling of an Integral returns itself."},
4686 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4687 "Rounding an Integral returns itself.\n"
4688 "Rounding with an ndigits argument also returns an integer."},
4689 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4690 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4691 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4692 "Returns size in memory, in bytes"},
4693 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004694};
4695
Guido van Rossumb43daf72007-08-01 18:08:08 +00004696static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004697 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004698 (getter)long_long, (setter)NULL,
4699 "the real part of a complex number",
4700 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004701 {"imag",
4702 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004703 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004704 NULL},
4705 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004706 (getter)long_long, (setter)NULL,
4707 "the numerator of a rational number in lowest terms",
4708 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004709 {"denominator",
4710 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004711 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004712 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004713 {NULL} /* Sentinel */
4714};
4715
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004716PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004717"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004718\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004719Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004720point argument will be truncated towards zero (this does not include a\n\
4721string representation of a floating point number!) When converting a\n\
4722string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004723converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004724
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004725static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004726 (binaryfunc)long_add, /*nb_add*/
4727 (binaryfunc)long_sub, /*nb_subtract*/
4728 (binaryfunc)long_mul, /*nb_multiply*/
4729 long_mod, /*nb_remainder*/
4730 long_divmod, /*nb_divmod*/
4731 long_pow, /*nb_power*/
4732 (unaryfunc)long_neg, /*nb_negative*/
4733 (unaryfunc)long_long, /*tp_positive*/
4734 (unaryfunc)long_abs, /*tp_absolute*/
4735 (inquiry)long_bool, /*tp_bool*/
4736 (unaryfunc)long_invert, /*nb_invert*/
4737 long_lshift, /*nb_lshift*/
4738 (binaryfunc)long_rshift, /*nb_rshift*/
4739 long_and, /*nb_and*/
4740 long_xor, /*nb_xor*/
4741 long_or, /*nb_or*/
4742 long_long, /*nb_int*/
4743 0, /*nb_reserved*/
4744 long_float, /*nb_float*/
4745 0, /* nb_inplace_add */
4746 0, /* nb_inplace_subtract */
4747 0, /* nb_inplace_multiply */
4748 0, /* nb_inplace_remainder */
4749 0, /* nb_inplace_power */
4750 0, /* nb_inplace_lshift */
4751 0, /* nb_inplace_rshift */
4752 0, /* nb_inplace_and */
4753 0, /* nb_inplace_xor */
4754 0, /* nb_inplace_or */
4755 long_div, /* nb_floor_divide */
4756 long_true_divide, /* nb_true_divide */
4757 0, /* nb_inplace_floor_divide */
4758 0, /* nb_inplace_true_divide */
4759 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004760};
4761
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004762PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4764 "int", /* tp_name */
4765 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4766 sizeof(digit), /* tp_itemsize */
4767 long_dealloc, /* tp_dealloc */
4768 0, /* tp_print */
4769 0, /* tp_getattr */
4770 0, /* tp_setattr */
4771 0, /* tp_reserved */
4772 long_to_decimal_string, /* tp_repr */
4773 &long_as_number, /* tp_as_number */
4774 0, /* tp_as_sequence */
4775 0, /* tp_as_mapping */
4776 (hashfunc)long_hash, /* tp_hash */
4777 0, /* tp_call */
4778 long_to_decimal_string, /* tp_str */
4779 PyObject_GenericGetAttr, /* tp_getattro */
4780 0, /* tp_setattro */
4781 0, /* tp_as_buffer */
4782 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4783 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4784 long_doc, /* tp_doc */
4785 0, /* tp_traverse */
4786 0, /* tp_clear */
4787 long_richcompare, /* tp_richcompare */
4788 0, /* tp_weaklistoffset */
4789 0, /* tp_iter */
4790 0, /* tp_iternext */
4791 long_methods, /* tp_methods */
4792 0, /* tp_members */
4793 long_getset, /* tp_getset */
4794 0, /* tp_base */
4795 0, /* tp_dict */
4796 0, /* tp_descr_get */
4797 0, /* tp_descr_set */
4798 0, /* tp_dictoffset */
4799 0, /* tp_init */
4800 0, /* tp_alloc */
4801 long_new, /* tp_new */
4802 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004803};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004804
Mark Dickinsonbd792642009-03-18 20:06:12 +00004805static PyTypeObject Int_InfoType;
4806
4807PyDoc_STRVAR(int_info__doc__,
4808"sys.int_info\n\
4809\n\
4810A struct sequence that holds information about Python's\n\
4811internal representation of integers. The attributes are read only.");
4812
4813static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004815 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004817};
4818
4819static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004820 "sys.int_info", /* name */
4821 int_info__doc__, /* doc */
4822 int_info_fields, /* fields */
4823 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004824};
4825
4826PyObject *
4827PyLong_GetInfo(void)
4828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004829 PyObject* int_info;
4830 int field = 0;
4831 int_info = PyStructSequence_New(&Int_InfoType);
4832 if (int_info == NULL)
4833 return NULL;
4834 PyStructSequence_SET_ITEM(int_info, field++,
4835 PyLong_FromLong(PyLong_SHIFT));
4836 PyStructSequence_SET_ITEM(int_info, field++,
4837 PyLong_FromLong(sizeof(digit)));
4838 if (PyErr_Occurred()) {
4839 Py_CLEAR(int_info);
4840 return NULL;
4841 }
4842 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004843}
4844
Guido van Rossumddefaf32007-01-14 03:31:43 +00004845int
4846_PyLong_Init(void)
4847{
4848#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 int ival, size;
4850 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4853 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4854 if (Py_TYPE(v) == &PyLong_Type) {
4855 /* The element is already initialized, most likely
4856 * the Python interpreter was initialized before.
4857 */
4858 Py_ssize_t refcnt;
4859 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004861 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4862 _Py_NewReference(op);
4863 /* _Py_NewReference sets the ref count to 1 but
4864 * the ref count might be larger. Set the refcnt
4865 * to the original refcnt + 1 */
4866 Py_REFCNT(op) = refcnt + 1;
4867 assert(Py_SIZE(op) == size);
4868 assert(v->ob_digit[0] == abs(ival));
4869 }
4870 else {
4871 PyObject_INIT(v, &PyLong_Type);
4872 }
4873 Py_SIZE(v) = size;
4874 v->ob_digit[0] = abs(ival);
4875 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004876#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 /* initialize int_info */
4878 if (Int_InfoType.tp_name == 0)
4879 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004882}
4883
4884void
4885PyLong_Fini(void)
4886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 /* Integers are currently statically allocated. Py_DECREF is not
4888 needed, but Python must forget about the reference or multiple
4889 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004890#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 int i;
4892 PyLongObject *v = small_ints;
4893 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4894 _Py_DEC_REFTOTAL;
4895 _Py_ForgetReference((PyObject*)v);
4896 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004897#endif
4898}