blob: e2a4ef9c5efa35df281d5e8caedd55ce9c56512e [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
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#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
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000323/* Get a C long int from a long int object.
324 Returns -1 and sets an error condition if overflow occurs. */
325
326long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000327PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 /* This version by Tim Peters */
330 register PyLongObject *v;
331 unsigned long x, prev;
332 long res;
333 Py_ssize_t i;
334 int sign;
335 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 *overflow = 0;
338 if (vv == NULL) {
339 PyErr_BadInternalCall();
340 return -1;
341 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 if (!PyLong_Check(vv)) {
344 PyNumberMethods *nb;
345 nb = vv->ob_type->tp_as_number;
346 if (nb == NULL || nb->nb_int == NULL) {
347 PyErr_SetString(PyExc_TypeError,
348 "an integer is required");
349 return -1;
350 }
351 vv = (*nb->nb_int) (vv);
352 if (vv == NULL)
353 return -1;
354 do_decref = 1;
355 if (!PyLong_Check(vv)) {
356 Py_DECREF(vv);
357 PyErr_SetString(PyExc_TypeError,
358 "nb_int should return int object");
359 return -1;
360 }
361 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 res = -1;
364 v = (PyLongObject *)vv;
365 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 switch (i) {
368 case -1:
369 res = -(sdigit)v->ob_digit[0];
370 break;
371 case 0:
372 res = 0;
373 break;
374 case 1:
375 res = v->ob_digit[0];
376 break;
377 default:
378 sign = 1;
379 x = 0;
380 if (i < 0) {
381 sign = -1;
382 i = -(i);
383 }
384 while (--i >= 0) {
385 prev = x;
386 x = (x << PyLong_SHIFT) | v->ob_digit[i];
387 if ((x >> PyLong_SHIFT) != prev) {
388 *overflow = sign;
389 goto exit;
390 }
391 }
392 /* Haven't lost any bits, but casting to long requires extra
393 * care (see comment above).
394 */
395 if (x <= (unsigned long)LONG_MAX) {
396 res = (long)x * sign;
397 }
398 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
399 res = LONG_MIN;
400 }
401 else {
402 *overflow = sign;
403 /* res is already set to -1 */
404 }
405 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000406 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (do_decref) {
408 Py_DECREF(vv);
409 }
410 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000411}
412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000414PyLong_AsLong(PyObject *obj)
415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 int overflow;
417 long result = PyLong_AsLongAndOverflow(obj, &overflow);
418 if (overflow) {
419 /* XXX: could be cute and give a different
420 message for overflow == -1 */
421 PyErr_SetString(PyExc_OverflowError,
422 "Python int too large to convert to C long");
423 }
424 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000425}
426
Serhiy Storchaka441d30f2013-01-19 12:26:26 +0200427/* Get a C int from a long int object or any object that has an __int__
428 method. Return -1 and set an error if overflow occurs. */
429
430int
431_PyLong_AsInt(PyObject *obj)
432{
433 int overflow;
434 long result = PyLong_AsLongAndOverflow(obj, &overflow);
435 if (overflow || result > INT_MAX || result < INT_MIN) {
436 /* XXX: could be cute and give a different
437 message for overflow == -1 */
438 PyErr_SetString(PyExc_OverflowError,
439 "Python int too large to convert to C int");
440 return -1;
441 }
442 return (int)result;
443}
444
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000445/* Get a Py_ssize_t from a long int object.
446 Returns -1 and sets an error condition if overflow occurs. */
447
448Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000449PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 register PyLongObject *v;
451 size_t x, prev;
452 Py_ssize_t i;
453 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (vv == NULL) {
456 PyErr_BadInternalCall();
457 return -1;
458 }
459 if (!PyLong_Check(vv)) {
460 PyErr_SetString(PyExc_TypeError, "an integer is required");
461 return -1;
462 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 v = (PyLongObject *)vv;
465 i = Py_SIZE(v);
466 switch (i) {
467 case -1: return -(sdigit)v->ob_digit[0];
468 case 0: return 0;
469 case 1: return v->ob_digit[0];
470 }
471 sign = 1;
472 x = 0;
473 if (i < 0) {
474 sign = -1;
475 i = -(i);
476 }
477 while (--i >= 0) {
478 prev = x;
479 x = (x << PyLong_SHIFT) | v->ob_digit[i];
480 if ((x >> PyLong_SHIFT) != prev)
481 goto overflow;
482 }
483 /* Haven't lost any bits, but casting to a signed type requires
484 * extra care (see comment above).
485 */
486 if (x <= (size_t)PY_SSIZE_T_MAX) {
487 return (Py_ssize_t)x * sign;
488 }
489 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
490 return PY_SSIZE_T_MIN;
491 }
492 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000493
Mark Dickinson22b20182010-05-10 21:27:53 +0000494 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 PyErr_SetString(PyExc_OverflowError,
496 "Python int too large to convert to C ssize_t");
497 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000498}
499
Guido van Rossumd8c80482002-08-13 00:24:58 +0000500/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000501 Returns -1 and sets an error condition if overflow occurs. */
502
503unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000504PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 register PyLongObject *v;
507 unsigned long x, prev;
508 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (vv == NULL) {
511 PyErr_BadInternalCall();
512 return (unsigned long)-1;
513 }
514 if (!PyLong_Check(vv)) {
515 PyErr_SetString(PyExc_TypeError, "an integer is required");
516 return (unsigned long)-1;
517 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 v = (PyLongObject *)vv;
520 i = Py_SIZE(v);
521 x = 0;
522 if (i < 0) {
523 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000524 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 return (unsigned long) -1;
526 }
527 switch (i) {
528 case 0: return 0;
529 case 1: return v->ob_digit[0];
530 }
531 while (--i >= 0) {
532 prev = x;
533 x = (x << PyLong_SHIFT) | v->ob_digit[i];
534 if ((x >> PyLong_SHIFT) != prev) {
535 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000536 "python int too large to convert "
537 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return (unsigned long) -1;
539 }
540 }
541 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000542}
543
Stefan Krahb77c6c62011-09-12 16:22:47 +0200544/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
545 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000546
547size_t
548PyLong_AsSize_t(PyObject *vv)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 register PyLongObject *v;
551 size_t x, prev;
552 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (vv == NULL) {
555 PyErr_BadInternalCall();
556 return (size_t) -1;
557 }
558 if (!PyLong_Check(vv)) {
559 PyErr_SetString(PyExc_TypeError, "an integer is required");
560 return (size_t)-1;
561 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 v = (PyLongObject *)vv;
564 i = Py_SIZE(v);
565 x = 0;
566 if (i < 0) {
567 PyErr_SetString(PyExc_OverflowError,
568 "can't convert negative value to size_t");
569 return (size_t) -1;
570 }
571 switch (i) {
572 case 0: return 0;
573 case 1: return v->ob_digit[0];
574 }
575 while (--i >= 0) {
576 prev = x;
577 x = (x << PyLong_SHIFT) | v->ob_digit[i];
578 if ((x >> PyLong_SHIFT) != prev) {
579 PyErr_SetString(PyExc_OverflowError,
580 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200581 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 }
583 }
584 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000585}
586
Thomas Hellera4ea6032003-04-17 18:55:45 +0000587/* Get a C unsigned long int from a long int object, ignoring the high bits.
588 Returns -1 and sets an error condition if an error occurs. */
589
Guido van Rossumddefaf32007-01-14 03:31:43 +0000590static unsigned long
591_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 register PyLongObject *v;
594 unsigned long x;
595 Py_ssize_t i;
596 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (vv == NULL || !PyLong_Check(vv)) {
599 PyErr_BadInternalCall();
600 return (unsigned long) -1;
601 }
602 v = (PyLongObject *)vv;
603 i = Py_SIZE(v);
604 switch (i) {
605 case 0: return 0;
606 case 1: return v->ob_digit[0];
607 }
608 sign = 1;
609 x = 0;
610 if (i < 0) {
611 sign = -1;
612 i = -i;
613 }
614 while (--i >= 0) {
615 x = (x << PyLong_SHIFT) | v->ob_digit[i];
616 }
617 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000618}
619
Guido van Rossumddefaf32007-01-14 03:31:43 +0000620unsigned long
621PyLong_AsUnsignedLongMask(register PyObject *op)
622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyNumberMethods *nb;
624 PyLongObject *lo;
625 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (op && PyLong_Check(op))
628 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
631 nb->nb_int == NULL) {
632 PyErr_SetString(PyExc_TypeError, "an integer is required");
633 return (unsigned long)-1;
634 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 lo = (PyLongObject*) (*nb->nb_int) (op);
637 if (lo == NULL)
638 return (unsigned long)-1;
639 if (PyLong_Check(lo)) {
640 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
641 Py_DECREF(lo);
642 if (PyErr_Occurred())
643 return (unsigned long)-1;
644 return val;
645 }
646 else
647 {
648 Py_DECREF(lo);
649 PyErr_SetString(PyExc_TypeError,
650 "nb_int should return int object");
651 return (unsigned long)-1;
652 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000653}
654
Tim Peters5b8132f2003-01-31 15:52:05 +0000655int
656_PyLong_Sign(PyObject *vv)
657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 assert(v != NULL);
661 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000664}
665
Tim Petersbaefd9e2003-01-28 20:37:45 +0000666size_t
667_PyLong_NumBits(PyObject *vv)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 PyLongObject *v = (PyLongObject *)vv;
670 size_t result = 0;
671 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 assert(v != NULL);
674 assert(PyLong_Check(v));
675 ndigits = ABS(Py_SIZE(v));
676 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
677 if (ndigits > 0) {
678 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 result = (ndigits - 1) * PyLong_SHIFT;
681 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
682 goto Overflow;
683 do {
684 ++result;
685 if (result == 0)
686 goto Overflow;
687 msd >>= 1;
688 } while (msd);
689 }
690 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000691
Mark Dickinson22b20182010-05-10 21:27:53 +0000692 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
694 "to express in a platform size_t");
695 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000696}
697
Tim Peters2a9b3672001-06-11 21:23:58 +0000698PyObject *
699_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000701{
Mark Dickinson22b20182010-05-10 21:27:53 +0000702 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 int incr; /* direction to move pstartbyte */
704 const unsigned char* pendbyte; /* MSB of bytes */
705 size_t numsignificantbytes; /* number of bytes that matter */
706 Py_ssize_t ndigits; /* number of Python long digits */
707 PyLongObject* v; /* result */
708 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (n == 0)
711 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (little_endian) {
714 pstartbyte = bytes;
715 pendbyte = bytes + n - 1;
716 incr = 1;
717 }
718 else {
719 pstartbyte = bytes + n - 1;
720 pendbyte = bytes;
721 incr = -1;
722 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 if (is_signed)
725 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200728 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 is positive, and leading 0xff bytes if negative. */
730 {
731 size_t i;
732 const unsigned char* p = pendbyte;
733 const int pincr = -incr; /* search MSB to LSB */
734 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 for (i = 0; i < n; ++i, p += pincr) {
737 if (*p != insignficant)
738 break;
739 }
740 numsignificantbytes = n - i;
741 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
742 actually has 2 significant bytes. OTOH, 0xff0001 ==
743 -0x00ffff, so we wouldn't *need* to bump it there; but we
744 do for 0xffff = -0x0001. To be safe without bothering to
745 check every case, bump it regardless. */
746 if (is_signed && numsignificantbytes < n)
747 ++numsignificantbytes;
748 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* How many Python long digits do we need? We have
751 8*numsignificantbytes bits, and each Python long digit has
752 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
753 /* catch overflow before it happens */
754 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
755 PyErr_SetString(PyExc_OverflowError,
756 "byte array too long to convert to int");
757 return NULL;
758 }
759 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
760 v = _PyLong_New(ndigits);
761 if (v == NULL)
762 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 /* Copy the bits over. The tricky parts are computing 2's-comp on
765 the fly for signed numbers, and dealing with the mismatch between
766 8-bit bytes and (probably) 15-bit Python digits.*/
767 {
768 size_t i;
769 twodigits carry = 1; /* for 2's-comp calculation */
770 twodigits accum = 0; /* sliding register */
771 unsigned int accumbits = 0; /* number of bits in accum */
772 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
775 twodigits thisbyte = *p;
776 /* Compute correction for 2's comp, if needed. */
777 if (is_signed) {
778 thisbyte = (0xff ^ thisbyte) + carry;
779 carry = thisbyte >> 8;
780 thisbyte &= 0xff;
781 }
782 /* Because we're going LSB to MSB, thisbyte is
783 more significant than what's already in accum,
784 so needs to be prepended to accum. */
785 accum |= (twodigits)thisbyte << accumbits;
786 accumbits += 8;
787 if (accumbits >= PyLong_SHIFT) {
788 /* There's enough to fill a Python digit. */
789 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000790 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 ++idigit;
792 accum >>= PyLong_SHIFT;
793 accumbits -= PyLong_SHIFT;
794 assert(accumbits < PyLong_SHIFT);
795 }
796 }
797 assert(accumbits < PyLong_SHIFT);
798 if (accumbits) {
799 assert(idigit < ndigits);
800 v->ob_digit[idigit] = (digit)accum;
801 ++idigit;
802 }
803 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 Py_SIZE(v) = is_signed ? -idigit : idigit;
806 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000807}
808
809int
810_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 unsigned char* bytes, size_t n,
812 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000815 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000817 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
819 digit carry; /* for computing 2's-comp */
820 size_t j; /* # bytes filled */
821 unsigned char* p; /* pointer to next byte in bytes */
822 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (Py_SIZE(v) < 0) {
827 ndigits = -(Py_SIZE(v));
828 if (!is_signed) {
829 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000830 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return -1;
832 }
833 do_twos_comp = 1;
834 }
835 else {
836 ndigits = Py_SIZE(v);
837 do_twos_comp = 0;
838 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 if (little_endian) {
841 p = bytes;
842 pincr = 1;
843 }
844 else {
845 p = bytes + n - 1;
846 pincr = -1;
847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* Copy over all the Python digits.
850 It's crucial that every Python digit except for the MSD contribute
851 exactly PyLong_SHIFT bits to the total, so first assert that the long is
852 normalized. */
853 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
854 j = 0;
855 accum = 0;
856 accumbits = 0;
857 carry = do_twos_comp ? 1 : 0;
858 for (i = 0; i < ndigits; ++i) {
859 digit thisdigit = v->ob_digit[i];
860 if (do_twos_comp) {
861 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
862 carry = thisdigit >> PyLong_SHIFT;
863 thisdigit &= PyLong_MASK;
864 }
865 /* Because we're going LSB to MSB, thisdigit is more
866 significant than what's already in accum, so needs to be
867 prepended to accum. */
868 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 /* The most-significant digit may be (probably is) at least
871 partly empty. */
872 if (i == ndigits - 1) {
873 /* Count # of sign bits -- they needn't be stored,
874 * although for signed conversion we need later to
875 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000876 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 while (s != 0) {
878 s >>= 1;
879 accumbits++;
880 }
881 }
882 else
883 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Store as many bytes as possible. */
886 while (accumbits >= 8) {
887 if (j >= n)
888 goto Overflow;
889 ++j;
890 *p = (unsigned char)(accum & 0xff);
891 p += pincr;
892 accumbits -= 8;
893 accum >>= 8;
894 }
895 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* Store the straggler (if any). */
898 assert(accumbits < 8);
899 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
900 if (accumbits > 0) {
901 if (j >= n)
902 goto Overflow;
903 ++j;
904 if (do_twos_comp) {
905 /* Fill leading bits of the byte with sign bits
906 (appropriately pretending that the long had an
907 infinite supply of sign bits). */
908 accum |= (~(twodigits)0) << accumbits;
909 }
910 *p = (unsigned char)(accum & 0xff);
911 p += pincr;
912 }
913 else if (j == n && n > 0 && is_signed) {
914 /* The main loop filled the byte array exactly, so the code
915 just above didn't get to ensure there's a sign bit, and the
916 loop below wouldn't add one either. Make sure a sign bit
917 exists. */
918 unsigned char msb = *(p - pincr);
919 int sign_bit_set = msb >= 0x80;
920 assert(accumbits == 0);
921 if (sign_bit_set == do_twos_comp)
922 return 0;
923 else
924 goto Overflow;
925 }
Tim Peters05607ad2001-06-13 21:01:27 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Fill remaining bytes with copies of the sign bit. */
928 {
929 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
930 for ( ; j < n; ++j, p += pincr)
931 *p = signbyte;
932 }
Tim Peters05607ad2001-06-13 21:01:27 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000935
Mark Dickinson22b20182010-05-10 21:27:53 +0000936 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
938 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000939
Tim Peters2a9b3672001-06-11 21:23:58 +0000940}
941
Guido van Rossum78694d91998-09-18 14:14:13 +0000942/* Create a new long (or int) object from a C pointer */
943
944PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000945PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000946{
Mark Dickinson91044792012-10-18 19:21:43 +0100947#if SIZEOF_VOID_P <= SIZEOF_LONG
948 /* special-case null pointer */
949 if (!p)
950 return PyLong_FromLong(0);
951 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
952#else
953
Tim Peters70128a12001-06-16 08:48:40 +0000954#ifndef HAVE_LONG_LONG
955# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
956#endif
957#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000958# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000959#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* special-case null pointer */
961 if (!p)
962 return PyLong_FromLong(0);
963 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100964#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000965
Guido van Rossum78694d91998-09-18 14:14:13 +0000966}
967
968/* Get a C pointer from a long object (or an int object in some cases) */
969
970void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000971PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 /* This function will allow int or long objects. If vv is neither,
974 then the PyLong_AsLong*() functions will raise the exception:
975 PyExc_SystemError, "bad argument to internal function"
976 */
Tim Peters70128a12001-06-16 08:48:40 +0000977#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
981 x = PyLong_AsLong(vv);
982 else
983 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000984#else
Tim Peters70128a12001-06-16 08:48:40 +0000985
986#ifndef HAVE_LONG_LONG
987# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
988#endif
989#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000991#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
995 x = PyLong_AsLongLong(vv);
996 else
997 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000998
999#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (x == -1 && PyErr_Occurred())
1002 return NULL;
1003 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001004}
1005
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001006#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001007
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001008/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001009 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001010 */
1011
Tim Peterscf37dfc2001-06-14 18:42:50 +00001012#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +00001013#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001014
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001015/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001016
1017PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001018PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyLongObject *v;
1021 unsigned PY_LONG_LONG abs_ival;
1022 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1023 int ndigits = 0;
1024 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 CHECK_SMALL_INT(ival);
1027 if (ival < 0) {
1028 /* avoid signed overflow on negation; see comments
1029 in PyLong_FromLong above. */
1030 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1031 negative = 1;
1032 }
1033 else {
1034 abs_ival = (unsigned PY_LONG_LONG)ival;
1035 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Count the number of Python digits.
1038 We used to pick 5 ("big enough for anything"), but that's a
1039 waste of time and space given that 5*15 = 75 bits are rarely
1040 needed. */
1041 t = abs_ival;
1042 while (t) {
1043 ++ndigits;
1044 t >>= PyLong_SHIFT;
1045 }
1046 v = _PyLong_New(ndigits);
1047 if (v != NULL) {
1048 digit *p = v->ob_digit;
1049 Py_SIZE(v) = negative ? -ndigits : ndigits;
1050 t = abs_ival;
1051 while (t) {
1052 *p++ = (digit)(t & PyLong_MASK);
1053 t >>= PyLong_SHIFT;
1054 }
1055 }
1056 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001057}
1058
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001059/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001060
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001061PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001062PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyLongObject *v;
1065 unsigned PY_LONG_LONG t;
1066 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (ival < PyLong_BASE)
1069 return PyLong_FromLong((long)ival);
1070 /* Count the number of Python digits. */
1071 t = (unsigned PY_LONG_LONG)ival;
1072 while (t) {
1073 ++ndigits;
1074 t >>= PyLong_SHIFT;
1075 }
1076 v = _PyLong_New(ndigits);
1077 if (v != NULL) {
1078 digit *p = v->ob_digit;
1079 Py_SIZE(v) = ndigits;
1080 while (ival) {
1081 *p++ = (digit)(ival & PyLong_MASK);
1082 ival >>= PyLong_SHIFT;
1083 }
1084 }
1085 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001086}
1087
Martin v. Löwis18e16552006-02-15 17:27:45 +00001088/* Create a new long int object from a C Py_ssize_t. */
1089
1090PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001091PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyLongObject *v;
1094 size_t abs_ival;
1095 size_t t; /* unsigned so >> doesn't propagate sign bit */
1096 int ndigits = 0;
1097 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 CHECK_SMALL_INT(ival);
1100 if (ival < 0) {
1101 /* avoid signed overflow when ival = SIZE_T_MIN */
1102 abs_ival = (size_t)(-1-ival)+1;
1103 negative = 1;
1104 }
1105 else {
1106 abs_ival = (size_t)ival;
1107 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 /* Count the number of Python digits. */
1110 t = abs_ival;
1111 while (t) {
1112 ++ndigits;
1113 t >>= PyLong_SHIFT;
1114 }
1115 v = _PyLong_New(ndigits);
1116 if (v != NULL) {
1117 digit *p = v->ob_digit;
1118 Py_SIZE(v) = negative ? -ndigits : ndigits;
1119 t = abs_ival;
1120 while (t) {
1121 *p++ = (digit)(t & PyLong_MASK);
1122 t >>= PyLong_SHIFT;
1123 }
1124 }
1125 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001126}
1127
1128/* Create a new long int object from a C size_t. */
1129
1130PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001131PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 PyLongObject *v;
1134 size_t t;
1135 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 if (ival < PyLong_BASE)
1138 return PyLong_FromLong((long)ival);
1139 /* Count the number of Python digits. */
1140 t = ival;
1141 while (t) {
1142 ++ndigits;
1143 t >>= PyLong_SHIFT;
1144 }
1145 v = _PyLong_New(ndigits);
1146 if (v != NULL) {
1147 digit *p = v->ob_digit;
1148 Py_SIZE(v) = ndigits;
1149 while (ival) {
1150 *p++ = (digit)(ival & PyLong_MASK);
1151 ival >>= PyLong_SHIFT;
1152 }
1153 }
1154 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001155}
1156
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001157/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001158 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001159
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001160PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001161PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyLongObject *v;
1164 PY_LONG_LONG bytes;
1165 int one = 1;
1166 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (vv == NULL) {
1169 PyErr_BadInternalCall();
1170 return -1;
1171 }
1172 if (!PyLong_Check(vv)) {
1173 PyNumberMethods *nb;
1174 PyObject *io;
1175 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1176 nb->nb_int == NULL) {
1177 PyErr_SetString(PyExc_TypeError, "an integer is required");
1178 return -1;
1179 }
1180 io = (*nb->nb_int) (vv);
1181 if (io == NULL)
1182 return -1;
1183 if (PyLong_Check(io)) {
1184 bytes = PyLong_AsLongLong(io);
1185 Py_DECREF(io);
1186 return bytes;
1187 }
1188 Py_DECREF(io);
1189 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1190 return -1;
1191 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 v = (PyLongObject*)vv;
1194 switch(Py_SIZE(v)) {
1195 case -1: return -(sdigit)v->ob_digit[0];
1196 case 0: return 0;
1197 case 1: return v->ob_digit[0];
1198 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001199 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1200 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1203 if (res < 0)
1204 return (PY_LONG_LONG)-1;
1205 else
1206 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001207}
1208
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001209/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001210 Return -1 and set an error if overflow occurs. */
1211
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001212unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001213PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyLongObject *v;
1216 unsigned PY_LONG_LONG bytes;
1217 int one = 1;
1218 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (vv == NULL || !PyLong_Check(vv)) {
1221 PyErr_BadInternalCall();
1222 return (unsigned PY_LONG_LONG)-1;
1223 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 v = (PyLongObject*)vv;
1226 switch(Py_SIZE(v)) {
1227 case 0: return 0;
1228 case 1: return v->ob_digit[0];
1229 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230
Mark Dickinson22b20182010-05-10 21:27:53 +00001231 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1232 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1235 if (res < 0)
1236 return (unsigned PY_LONG_LONG)res;
1237 else
1238 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239}
Tim Petersd1a7da62001-06-13 00:35:57 +00001240
Thomas Hellera4ea6032003-04-17 18:55:45 +00001241/* Get a C unsigned long int from a long int object, ignoring the high bits.
1242 Returns -1 and sets an error condition if an error occurs. */
1243
Guido van Rossumddefaf32007-01-14 03:31:43 +00001244static unsigned PY_LONG_LONG
1245_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 register PyLongObject *v;
1248 unsigned PY_LONG_LONG x;
1249 Py_ssize_t i;
1250 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (vv == NULL || !PyLong_Check(vv)) {
1253 PyErr_BadInternalCall();
1254 return (unsigned long) -1;
1255 }
1256 v = (PyLongObject *)vv;
1257 switch(Py_SIZE(v)) {
1258 case 0: return 0;
1259 case 1: return v->ob_digit[0];
1260 }
1261 i = Py_SIZE(v);
1262 sign = 1;
1263 x = 0;
1264 if (i < 0) {
1265 sign = -1;
1266 i = -i;
1267 }
1268 while (--i >= 0) {
1269 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1270 }
1271 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001272}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273
1274unsigned PY_LONG_LONG
1275PyLong_AsUnsignedLongLongMask(register PyObject *op)
1276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 PyNumberMethods *nb;
1278 PyLongObject *lo;
1279 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (op && PyLong_Check(op))
1282 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1285 nb->nb_int == NULL) {
1286 PyErr_SetString(PyExc_TypeError, "an integer is required");
1287 return (unsigned PY_LONG_LONG)-1;
1288 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 lo = (PyLongObject*) (*nb->nb_int) (op);
1291 if (lo == NULL)
1292 return (unsigned PY_LONG_LONG)-1;
1293 if (PyLong_Check(lo)) {
1294 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1295 Py_DECREF(lo);
1296 if (PyErr_Occurred())
1297 return (unsigned PY_LONG_LONG)-1;
1298 return val;
1299 }
1300 else
1301 {
1302 Py_DECREF(lo);
1303 PyErr_SetString(PyExc_TypeError,
1304 "nb_int should return int object");
1305 return (unsigned PY_LONG_LONG)-1;
1306 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001307}
Tim Petersd1a7da62001-06-13 00:35:57 +00001308#undef IS_LITTLE_ENDIAN
1309
Mark Dickinson93f562c2010-01-30 10:30:15 +00001310/* Get a C long long int from a Python long or Python int object.
1311 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1312 on the sign of the result. Otherwise *overflow is 0.
1313
1314 For other errors (e.g., type error), returns -1 and sets an error
1315 condition.
1316*/
1317
1318PY_LONG_LONG
1319PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* This version by Tim Peters */
1322 register PyLongObject *v;
1323 unsigned PY_LONG_LONG x, prev;
1324 PY_LONG_LONG res;
1325 Py_ssize_t i;
1326 int sign;
1327 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 *overflow = 0;
1330 if (vv == NULL) {
1331 PyErr_BadInternalCall();
1332 return -1;
1333 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (!PyLong_Check(vv)) {
1336 PyNumberMethods *nb;
1337 nb = vv->ob_type->tp_as_number;
1338 if (nb == NULL || nb->nb_int == NULL) {
1339 PyErr_SetString(PyExc_TypeError,
1340 "an integer is required");
1341 return -1;
1342 }
1343 vv = (*nb->nb_int) (vv);
1344 if (vv == NULL)
1345 return -1;
1346 do_decref = 1;
1347 if (!PyLong_Check(vv)) {
1348 Py_DECREF(vv);
1349 PyErr_SetString(PyExc_TypeError,
1350 "nb_int should return int object");
1351 return -1;
1352 }
1353 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 res = -1;
1356 v = (PyLongObject *)vv;
1357 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 switch (i) {
1360 case -1:
1361 res = -(sdigit)v->ob_digit[0];
1362 break;
1363 case 0:
1364 res = 0;
1365 break;
1366 case 1:
1367 res = v->ob_digit[0];
1368 break;
1369 default:
1370 sign = 1;
1371 x = 0;
1372 if (i < 0) {
1373 sign = -1;
1374 i = -(i);
1375 }
1376 while (--i >= 0) {
1377 prev = x;
1378 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1379 if ((x >> PyLong_SHIFT) != prev) {
1380 *overflow = sign;
1381 goto exit;
1382 }
1383 }
1384 /* Haven't lost any bits, but casting to long requires extra
1385 * care (see comment above).
1386 */
1387 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1388 res = (PY_LONG_LONG)x * sign;
1389 }
1390 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1391 res = PY_LLONG_MIN;
1392 }
1393 else {
1394 *overflow = sign;
1395 /* res is already set to -1 */
1396 }
1397 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001398 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 if (do_decref) {
1400 Py_DECREF(vv);
1401 }
1402 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001403}
1404
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001405#endif /* HAVE_LONG_LONG */
1406
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001407#define CHECK_BINOP(v,w) \
1408 do { \
1409 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1410 Py_INCREF(Py_NotImplemented); \
1411 return Py_NotImplemented; \
1412 } \
1413 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001414
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001415/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1416 2**k if d is nonzero, else 0. */
1417
1418static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1420 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001421};
1422
1423static int
1424bits_in_digit(digit d)
1425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 int d_bits = 0;
1427 while (d >= 32) {
1428 d_bits += 6;
1429 d >>= 6;
1430 }
1431 d_bits += (int)BitLengthTable[d];
1432 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001433}
1434
Tim Peters877a2122002-08-12 05:09:36 +00001435/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1436 * is modified in place, by adding y to it. Carries are propagated as far as
1437 * x[m-1], and the remaining carry (0 or 1) is returned.
1438 */
1439static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001440v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_ssize_t i;
1443 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 assert(m >= n);
1446 for (i = 0; i < n; ++i) {
1447 carry += x[i] + y[i];
1448 x[i] = carry & PyLong_MASK;
1449 carry >>= PyLong_SHIFT;
1450 assert((carry & 1) == carry);
1451 }
1452 for (; carry && i < m; ++i) {
1453 carry += x[i];
1454 x[i] = carry & PyLong_MASK;
1455 carry >>= PyLong_SHIFT;
1456 assert((carry & 1) == carry);
1457 }
1458 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001459}
1460
1461/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1462 * is modified in place, by subtracting y from it. Borrows are propagated as
1463 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1464 */
1465static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001466v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 Py_ssize_t i;
1469 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 assert(m >= n);
1472 for (i = 0; i < n; ++i) {
1473 borrow = x[i] - y[i] - borrow;
1474 x[i] = borrow & PyLong_MASK;
1475 borrow >>= PyLong_SHIFT;
1476 borrow &= 1; /* keep only 1 sign bit */
1477 }
1478 for (; borrow && i < m; ++i) {
1479 borrow = x[i] - borrow;
1480 x[i] = borrow & PyLong_MASK;
1481 borrow >>= PyLong_SHIFT;
1482 borrow &= 1;
1483 }
1484 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001485}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001486
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001487/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1488 * result in z[0:m], and return the d bits shifted out of the top.
1489 */
1490static digit
1491v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 Py_ssize_t i;
1494 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 assert(0 <= d && d < PyLong_SHIFT);
1497 for (i=0; i < m; i++) {
1498 twodigits acc = (twodigits)a[i] << d | carry;
1499 z[i] = (digit)acc & PyLong_MASK;
1500 carry = (digit)(acc >> PyLong_SHIFT);
1501 }
1502 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001503}
1504
1505/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1506 * result in z[0:m], and return the d bits shifted out of the bottom.
1507 */
1508static digit
1509v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 Py_ssize_t i;
1512 digit carry = 0;
1513 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 assert(0 <= d && d < PyLong_SHIFT);
1516 for (i=m; i-- > 0;) {
1517 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1518 carry = (digit)acc & mask;
1519 z[i] = (digit)(acc >> d);
1520 }
1521 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001522}
1523
Tim Peters212e6142001-07-14 12:23:19 +00001524/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1525 in pout, and returning the remainder. pin and pout point at the LSD.
1526 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001527 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001528 immutable. */
1529
1530static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001531inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 assert(n > 0 && n <= PyLong_MASK);
1536 pin += size;
1537 pout += size;
1538 while (--size >= 0) {
1539 digit hi;
1540 rem = (rem << PyLong_SHIFT) | *--pin;
1541 *--pout = hi = (digit)(rem / n);
1542 rem -= (twodigits)hi * n;
1543 }
1544 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001545}
1546
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547/* Divide a long integer by a digit, returning both the quotient
1548 (as function result) and the remainder (through *prem).
1549 The sign of a is ignored; n should not be zero. */
1550
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001551static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001552divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 const Py_ssize_t size = ABS(Py_SIZE(a));
1555 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 assert(n > 0 && n <= PyLong_MASK);
1558 z = _PyLong_New(size);
1559 if (z == NULL)
1560 return NULL;
1561 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1562 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001563}
1564
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001565/* Convert a long integer to a base 10 string. Returns a new non-shared
1566 string. (Return value is non-shared so that callers can modify the
1567 returned value if necessary.) */
1568
1569static PyObject *
1570long_to_decimal_string(PyObject *aa)
1571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyLongObject *scratch, *a;
1573 PyObject *str;
1574 Py_ssize_t size, strlen, size_a, i, j;
1575 digit *pout, *pin, rem, tenpow;
1576 Py_UNICODE *p;
1577 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 a = (PyLongObject *)aa;
1580 if (a == NULL || !PyLong_Check(a)) {
1581 PyErr_BadInternalCall();
1582 return NULL;
1583 }
1584 size_a = ABS(Py_SIZE(a));
1585 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 /* quick and dirty upper bound for the number of digits
1588 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 But log2(a) < size_a * PyLong_SHIFT, and
1593 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1594 > 3 * _PyLong_DECIMAL_SHIFT
1595 */
1596 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1597 PyErr_SetString(PyExc_OverflowError,
1598 "long is too large to format");
1599 return NULL;
1600 }
1601 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1602 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1603 scratch = _PyLong_New(size);
1604 if (scratch == NULL)
1605 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 /* convert array of base _PyLong_BASE digits in pin to an array of
1608 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1609 Volume 2 (3rd edn), section 4.4, Method 1b). */
1610 pin = a->ob_digit;
1611 pout = scratch->ob_digit;
1612 size = 0;
1613 for (i = size_a; --i >= 0; ) {
1614 digit hi = pin[i];
1615 for (j = 0; j < size; j++) {
1616 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1617 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1618 pout[j] = (digit)(z - (twodigits)hi *
1619 _PyLong_DECIMAL_BASE);
1620 }
1621 while (hi) {
1622 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1623 hi /= _PyLong_DECIMAL_BASE;
1624 }
1625 /* check for keyboard interrupt */
1626 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001627 Py_DECREF(scratch);
1628 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001629 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 }
1631 /* pout should have at least one digit, so that the case when a = 0
1632 works correctly */
1633 if (size == 0)
1634 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 /* calculate exact length of output string, and allocate */
1637 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1638 tenpow = 10;
1639 rem = pout[size-1];
1640 while (rem >= tenpow) {
1641 tenpow *= 10;
1642 strlen++;
1643 }
1644 str = PyUnicode_FromUnicode(NULL, strlen);
1645 if (str == NULL) {
1646 Py_DECREF(scratch);
1647 return NULL;
1648 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* fill the string right-to-left */
1651 p = PyUnicode_AS_UNICODE(str) + strlen;
1652 *p = '\0';
1653 /* pout[0] through pout[size-2] contribute exactly
1654 _PyLong_DECIMAL_SHIFT digits each */
1655 for (i=0; i < size - 1; i++) {
1656 rem = pout[i];
1657 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1658 *--p = '0' + rem % 10;
1659 rem /= 10;
1660 }
1661 }
1662 /* pout[size-1]: always produce at least one decimal digit */
1663 rem = pout[i];
1664 do {
1665 *--p = '0' + rem % 10;
1666 rem /= 10;
1667 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* and sign */
1670 if (negative)
1671 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 /* check we've counted correctly */
1674 assert(p == PyUnicode_AS_UNICODE(str));
1675 Py_DECREF(scratch);
1676 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001677}
1678
Mark Dickinsoncd068122009-09-18 14:53:08 +00001679/* Convert a long int object to a string, using a given conversion base,
1680 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001681 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001682
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001683PyObject *
1684_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 register PyLongObject *a = (PyLongObject *)aa;
1687 PyObject *str;
1688 Py_ssize_t i, sz;
1689 Py_ssize_t size_a;
1690 Py_UNICODE *p, sign = '\0';
1691 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 assert(base == 2 || base == 8 || base == 10 || base == 16);
1694 if (base == 10)
1695 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 if (a == NULL || !PyLong_Check(a)) {
1698 PyErr_BadInternalCall();
1699 return NULL;
1700 }
1701 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 /* Compute a rough upper bound for the length of the string */
1704 switch (base) {
1705 case 16:
1706 bits = 4;
1707 break;
1708 case 8:
1709 bits = 3;
1710 break;
1711 case 2:
1712 bits = 1;
1713 break;
1714 default:
1715 assert(0); /* shouldn't ever get here */
1716 bits = 0; /* to silence gcc warning */
1717 }
1718 /* compute length of output string: allow 2 characters for prefix and
1719 1 for possible '-' sign. */
1720 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1721 PyErr_SetString(PyExc_OverflowError,
1722 "int is too large to format");
1723 return NULL;
1724 }
1725 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1726 is safe from overflow */
1727 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1728 assert(sz >= 0);
1729 str = PyUnicode_FromUnicode(NULL, sz);
1730 if (str == NULL)
1731 return NULL;
1732 p = PyUnicode_AS_UNICODE(str) + sz;
1733 *p = '\0';
1734 if (Py_SIZE(a) < 0)
1735 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (Py_SIZE(a) == 0) {
1738 *--p = '0';
1739 }
1740 else {
1741 /* JRH: special case for power-of-2 bases */
1742 twodigits accum = 0;
1743 int accumbits = 0; /* # of bits in accum */
1744 for (i = 0; i < size_a; ++i) {
1745 accum |= (twodigits)a->ob_digit[i] << accumbits;
1746 accumbits += PyLong_SHIFT;
1747 assert(accumbits >= bits);
1748 do {
1749 Py_UNICODE cdigit;
1750 cdigit = (Py_UNICODE)(accum & (base - 1));
1751 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1752 assert(p > PyUnicode_AS_UNICODE(str));
1753 *--p = cdigit;
1754 accumbits -= bits;
1755 accum >>= bits;
1756 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1757 }
1758 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (base == 16)
1761 *--p = 'x';
1762 else if (base == 8)
1763 *--p = 'o';
1764 else /* (base == 2) */
1765 *--p = 'b';
1766 *--p = '0';
1767 if (sign)
1768 *--p = sign;
1769 if (p != PyUnicode_AS_UNICODE(str)) {
1770 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1771 assert(p > q);
1772 do {
1773 } while ((*q++ = *p++) != '\0');
1774 q--;
1775 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1776 PyUnicode_AS_UNICODE(str)))) {
1777 Py_DECREF(str);
1778 return NULL;
1779 }
1780 }
1781 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001782}
1783
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784/* Table of digit values for 8-bit string -> integer conversion.
1785 * '0' maps to 0, ..., '9' maps to 9.
1786 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1787 * All other indices map to 37.
1788 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001789 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001790 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001791unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1793 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1794 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1795 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1796 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1797 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1798 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1799 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1800 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1801 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1802 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1803 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1804 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1805 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1806 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1807 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001808};
1809
1810/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001811 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1812 * non-digit (which may be *str!). A normalized long is returned.
1813 * The point to this routine is that it takes time linear in the number of
1814 * string characters.
1815 */
1816static PyLongObject *
1817long_from_binary_base(char **str, int base)
1818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 char *p = *str;
1820 char *start = p;
1821 int bits_per_char;
1822 Py_ssize_t n;
1823 PyLongObject *z;
1824 twodigits accum;
1825 int bits_in_accum;
1826 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1829 n = base;
1830 for (bits_per_char = -1; n; ++bits_per_char)
1831 n >>= 1;
1832 /* n <- total # of bits needed, while setting p to end-of-string */
1833 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1834 ++p;
1835 *str = p;
1836 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1837 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1838 if (n / bits_per_char < p - start) {
1839 PyErr_SetString(PyExc_ValueError,
1840 "int string too large to convert");
1841 return NULL;
1842 }
1843 n = n / PyLong_SHIFT;
1844 z = _PyLong_New(n);
1845 if (z == NULL)
1846 return NULL;
1847 /* Read string from right, and fill in long from left; i.e.,
1848 * from least to most significant in both.
1849 */
1850 accum = 0;
1851 bits_in_accum = 0;
1852 pdigit = z->ob_digit;
1853 while (--p >= start) {
1854 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1855 assert(k >= 0 && k < base);
1856 accum |= (twodigits)k << bits_in_accum;
1857 bits_in_accum += bits_per_char;
1858 if (bits_in_accum >= PyLong_SHIFT) {
1859 *pdigit++ = (digit)(accum & PyLong_MASK);
1860 assert(pdigit - z->ob_digit <= n);
1861 accum >>= PyLong_SHIFT;
1862 bits_in_accum -= PyLong_SHIFT;
1863 assert(bits_in_accum < PyLong_SHIFT);
1864 }
1865 }
1866 if (bits_in_accum) {
1867 assert(bits_in_accum <= PyLong_SHIFT);
1868 *pdigit++ = (digit)accum;
1869 assert(pdigit - z->ob_digit <= n);
1870 }
1871 while (pdigit - z->ob_digit < n)
1872 *pdigit++ = 0;
1873 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001874}
1875
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001877PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 int sign = 1, error_if_nonzero = 0;
1880 char *start, *orig_str = str;
1881 PyLongObject *z = NULL;
1882 PyObject *strobj;
1883 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 if ((base != 0 && base < 2) || base > 36) {
1886 PyErr_SetString(PyExc_ValueError,
1887 "int() arg 2 must be >= 2 and <= 36");
1888 return NULL;
1889 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01001890 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 str++;
1892 if (*str == '+')
1893 ++str;
1894 else if (*str == '-') {
1895 ++str;
1896 sign = -1;
1897 }
1898 if (base == 0) {
1899 if (str[0] != '0')
1900 base = 10;
1901 else if (str[1] == 'x' || str[1] == 'X')
1902 base = 16;
1903 else if (str[1] == 'o' || str[1] == 'O')
1904 base = 8;
1905 else if (str[1] == 'b' || str[1] == 'B')
1906 base = 2;
1907 else {
1908 /* "old" (C-style) octal literal, now invalid.
1909 it might still be zero though */
1910 error_if_nonzero = 1;
1911 base = 10;
1912 }
1913 }
1914 if (str[0] == '0' &&
1915 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1916 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1917 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1918 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 start = str;
1921 if ((base & (base - 1)) == 0)
1922 z = long_from_binary_base(&str, base);
1923 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001924/***
1925Binary bases can be converted in time linear in the number of digits, because
1926Python's representation base is binary. Other bases (including decimal!) use
1927the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001928
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929First some math: the largest integer that can be expressed in N base-B digits
1930is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1931case number of Python digits needed to hold it is the smallest integer n s.t.
1932
1933 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1934 BASE**n >= B**N [taking logs to base BASE]
1935 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1936
1937The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1938this quickly. A Python long with that much space is reserved near the start,
1939and the result is computed into it.
1940
1941The input string is actually treated as being in base base**i (i.e., i digits
1942are processed at a time), where two more static arrays hold:
1943
1944 convwidth_base[base] = the largest integer i such that base**i <= BASE
1945 convmultmax_base[base] = base ** convwidth_base[base]
1946
1947The first of these is the largest i such that i consecutive input digits
1948must fit in a single Python digit. The second is effectively the input
1949base we're really using.
1950
1951Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1952convmultmax_base[base], the result is "simply"
1953
1954 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1955
1956where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001957
1958Error analysis: as above, the number of Python digits `n` needed is worst-
1959case
1960
1961 n >= N * log(B)/log(BASE)
1962
1963where `N` is the number of input digits in base `B`. This is computed via
1964
1965 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1966
1967below. Two numeric concerns are how much space this can waste, and whether
1968the computed result can be too small. To be concrete, assume BASE = 2**15,
1969which is the default (and it's unlikely anyone changes that).
1970
1971Waste isn't a problem: provided the first input digit isn't 0, the difference
1972between the worst-case input with N digits and the smallest input with N
1973digits is about a factor of B, but B is small compared to BASE so at most
1974one allocated Python digit can remain unused on that count. If
1975N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1976and adding 1 returns a result 1 larger than necessary. However, that can't
1977happen: whenever B is a power of 2, long_from_binary_base() is called
1978instead, and it's impossible for B**i to be an integer power of 2**15 when
1979B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1980an exact integer when B is not a power of 2, since B**i has a prime factor
1981other than 2 in that case, but (2**15)**j's only prime factor is 2).
1982
1983The computed result can be too small if the true value of N*log(B)/log(BASE)
1984is a little bit larger than an exact integer, but due to roundoff errors (in
1985computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1986yields a numeric result a little less than that integer. Unfortunately, "how
1987close can a transcendental function get to an integer over some range?"
1988questions are generally theoretically intractable. Computer analysis via
1989continued fractions is practical: expand log(B)/log(BASE) via continued
1990fractions, giving a sequence i/j of "the best" rational approximations. Then
1991j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1992we can get very close to being in trouble, but very rarely. For example,
199376573 is a denominator in one of the continued-fraction approximations to
1994log(10)/log(2**15), and indeed:
1995
1996 >>> log(10)/log(2**15)*76573
1997 16958.000000654003
1998
1999is very close to an integer. If we were working with IEEE single-precision,
2000rounding errors could kill us. Finding worst cases in IEEE double-precision
2001requires better-than-double-precision log() functions, and Tim didn't bother.
2002Instead the code checks to see whether the allocated space is enough as each
2003new Python digit is added, and copies the whole thing to a larger long if not.
2004This should happen extremely rarely, and in fact I don't have a test case
2005that triggers it(!). Instead the code was tested by artificially allocating
2006just 1 digit at the start, so that the copying code was exercised for every
2007digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002008***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 register twodigits c; /* current input character */
2010 Py_ssize_t size_z;
2011 int i;
2012 int convwidth;
2013 twodigits convmultmax, convmult;
2014 digit *pz, *pzstop;
2015 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 static double log_base_BASE[37] = {0.0e0,};
2018 static int convwidth_base[37] = {0,};
2019 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (log_base_BASE[base] == 0.0) {
2022 twodigits convmax = base;
2023 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024
Mark Dickinson22b20182010-05-10 21:27:53 +00002025 log_base_BASE[base] = (log((double)base) /
2026 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 for (;;) {
2028 twodigits next = convmax * base;
2029 if (next > PyLong_BASE)
2030 break;
2031 convmax = next;
2032 ++i;
2033 }
2034 convmultmax_base[base] = convmax;
2035 assert(i > 0);
2036 convwidth_base[base] = i;
2037 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* Find length of the string of numeric characters. */
2040 scan = str;
2041 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2042 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* Create a long object that can contain the largest possible
2045 * integer with this base and length. Note that there's no
2046 * need to initialize z->ob_digit -- no slot is read up before
2047 * being stored into.
2048 */
2049 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2050 /* Uncomment next line to test exceedingly rare copy code */
2051 /* size_z = 1; */
2052 assert(size_z > 0);
2053 z = _PyLong_New(size_z);
2054 if (z == NULL)
2055 return NULL;
2056 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* `convwidth` consecutive input digits are treated as a single
2059 * digit in base `convmultmax`.
2060 */
2061 convwidth = convwidth_base[base];
2062 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* Work ;-) */
2065 while (str < scan) {
2066 /* grab up to convwidth digits from the input string */
2067 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2068 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2069 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002070 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 assert(c < PyLong_BASE);
2072 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 convmult = convmultmax;
2075 /* Calculate the shift only if we couldn't get
2076 * convwidth digits.
2077 */
2078 if (i != convwidth) {
2079 convmult = base;
2080 for ( ; i > 1; --i)
2081 convmult *= base;
2082 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 /* Multiply z by convmult, and add c. */
2085 pz = z->ob_digit;
2086 pzstop = pz + Py_SIZE(z);
2087 for (; pz < pzstop; ++pz) {
2088 c += (twodigits)*pz * convmult;
2089 *pz = (digit)(c & PyLong_MASK);
2090 c >>= PyLong_SHIFT;
2091 }
2092 /* carry off the current end? */
2093 if (c) {
2094 assert(c < PyLong_BASE);
2095 if (Py_SIZE(z) < size_z) {
2096 *pz = (digit)c;
2097 ++Py_SIZE(z);
2098 }
2099 else {
2100 PyLongObject *tmp;
2101 /* Extremely rare. Get more space. */
2102 assert(Py_SIZE(z) == size_z);
2103 tmp = _PyLong_New(size_z + 1);
2104 if (tmp == NULL) {
2105 Py_DECREF(z);
2106 return NULL;
2107 }
2108 memcpy(tmp->ob_digit,
2109 z->ob_digit,
2110 sizeof(digit) * size_z);
2111 Py_DECREF(z);
2112 z = tmp;
2113 z->ob_digit[size_z] = (digit)c;
2114 ++size_z;
2115 }
2116 }
2117 }
2118 }
2119 if (z == NULL)
2120 return NULL;
2121 if (error_if_nonzero) {
2122 /* reset the base to 0, else the exception message
2123 doesn't make too much sense */
2124 base = 0;
2125 if (Py_SIZE(z) != 0)
2126 goto onError;
2127 /* there might still be other problems, therefore base
2128 remains zero here for the same reason */
2129 }
2130 if (str == start)
2131 goto onError;
2132 if (sign < 0)
2133 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002134 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 str++;
2136 if (*str != '\0')
2137 goto onError;
2138 if (pend)
2139 *pend = str;
2140 long_normalize(z);
2141 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002142
Mark Dickinson22b20182010-05-10 21:27:53 +00002143 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 Py_XDECREF(z);
2145 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2146 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2147 if (strobj == NULL)
2148 return NULL;
2149 PyErr_Format(PyExc_ValueError,
2150 "invalid literal for int() with base %d: %R",
2151 base, strobj);
2152 Py_DECREF(strobj);
2153 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002154}
2155
2156PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002157PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002160 PyObject *asciidig;
2161 char *buffer, *end;
2162 Py_ssize_t i, buflen;
2163 Py_UNICODE *ptr;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002164
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002165 asciidig = PyUnicode_TransformDecimalToASCII(u, length);
2166 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 return NULL;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002168 /* Replace non-ASCII whitespace with ' ' */
2169 ptr = PyUnicode_AS_UNICODE(asciidig);
2170 for (i = 0; i < length; i++) {
Mark Dickinsonc9fb3c62010-12-04 11:06:25 +00002171 Py_UNICODE ch = ptr[i];
2172 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
2173 ptr[i] = ' ';
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002174 }
2175 buffer = _PyUnicode_AsStringAndSize(asciidig, &buflen);
2176 if (buffer == NULL) {
2177 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 return NULL;
2179 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002180 result = PyLong_FromString(buffer, &end, base);
2181 if (result != NULL && end != buffer + buflen) {
2182 PyErr_SetString(PyExc_ValueError,
2183 "null byte in argument for int()");
2184 Py_DECREF(result);
2185 result = NULL;
2186 }
2187 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002189}
2190
Tim Peters9f688bf2000-07-07 15:53:28 +00002191/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002194static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002195
2196/* Long division with remainder, top-level routine */
2197
Guido van Rossume32e0141992-01-19 16:31:05 +00002198static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002199long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2203 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (size_b == 0) {
2206 PyErr_SetString(PyExc_ZeroDivisionError,
2207 "integer division or modulo by zero");
2208 return -1;
2209 }
2210 if (size_a < size_b ||
2211 (size_a == size_b &&
2212 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2213 /* |a| < |b|. */
2214 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2215 if (*pdiv == NULL)
2216 return -1;
2217 Py_INCREF(a);
2218 *prem = (PyLongObject *) a;
2219 return 0;
2220 }
2221 if (size_b == 1) {
2222 digit rem = 0;
2223 z = divrem1(a, b->ob_digit[0], &rem);
2224 if (z == NULL)
2225 return -1;
2226 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2227 if (*prem == NULL) {
2228 Py_DECREF(z);
2229 return -1;
2230 }
2231 }
2232 else {
2233 z = x_divrem(a, b, prem);
2234 if (z == NULL)
2235 return -1;
2236 }
2237 /* Set the signs.
2238 The quotient z has the sign of a*b;
2239 the remainder r has the sign of a,
2240 so a = b*z + r. */
2241 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2242 NEGATE(z);
2243 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2244 NEGATE(*prem);
2245 *pdiv = maybe_small_long(z);
2246 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002247}
2248
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002249/* Unsigned long division with remainder -- the algorithm. The arguments v1
2250 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002252static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002253x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 PyLongObject *v, *w, *a;
2256 Py_ssize_t i, k, size_v, size_w;
2257 int d;
2258 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2259 twodigits vv;
2260 sdigit zhi;
2261 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2264 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2265 handle the special case when the initial estimate q for a quotient
2266 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2267 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 /* allocate space; w will also be used to hold the final remainder */
2270 size_v = ABS(Py_SIZE(v1));
2271 size_w = ABS(Py_SIZE(w1));
2272 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2273 v = _PyLong_New(size_v+1);
2274 if (v == NULL) {
2275 *prem = NULL;
2276 return NULL;
2277 }
2278 w = _PyLong_New(size_w);
2279 if (w == NULL) {
2280 Py_DECREF(v);
2281 *prem = NULL;
2282 return NULL;
2283 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2286 shift v1 left by the same amount. Results go into w and v. */
2287 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2288 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2289 assert(carry == 0);
2290 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2291 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2292 v->ob_digit[size_v] = carry;
2293 size_v++;
2294 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2297 at most (and usually exactly) k = size_v - size_w digits. */
2298 k = size_v - size_w;
2299 assert(k >= 0);
2300 a = _PyLong_New(k);
2301 if (a == NULL) {
2302 Py_DECREF(w);
2303 Py_DECREF(v);
2304 *prem = NULL;
2305 return NULL;
2306 }
2307 v0 = v->ob_digit;
2308 w0 = w->ob_digit;
2309 wm1 = w0[size_w-1];
2310 wm2 = w0[size_w-2];
2311 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2312 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2313 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002316 Py_DECREF(a);
2317 Py_DECREF(w);
2318 Py_DECREF(v);
2319 *prem = NULL;
2320 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002321 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 /* estimate quotient digit q; may overestimate by 1 (rare) */
2324 vtop = vk[size_w];
2325 assert(vtop <= wm1);
2326 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2327 q = (digit)(vv / wm1);
2328 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2329 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2330 | vk[size_w-2])) {
2331 --q;
2332 r += wm1;
2333 if (r >= PyLong_BASE)
2334 break;
2335 }
2336 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2339 zhi = 0;
2340 for (i = 0; i < size_w; ++i) {
2341 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2342 -PyLong_BASE * q <= z < PyLong_BASE */
2343 z = (sdigit)vk[i] + zhi -
2344 (stwodigits)q * (stwodigits)w0[i];
2345 vk[i] = (digit)z & PyLong_MASK;
2346 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002347 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* add w back if q was too large (this branch taken rarely) */
2351 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2352 if ((sdigit)vtop + zhi < 0) {
2353 carry = 0;
2354 for (i = 0; i < size_w; ++i) {
2355 carry += vk[i] + w0[i];
2356 vk[i] = carry & PyLong_MASK;
2357 carry >>= PyLong_SHIFT;
2358 }
2359 --q;
2360 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 /* store quotient digit */
2363 assert(q < PyLong_BASE);
2364 *--ak = q;
2365 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* unshift remainder; we reuse w to store the result */
2368 carry = v_rshift(w0, v0, size_w, d);
2369 assert(carry==0);
2370 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 *prem = long_normalize(w);
2373 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374}
2375
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002376/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2377 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2378 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2379 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2380 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2381 -1.0. */
2382
2383/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2384#if DBL_MANT_DIG == 53
2385#define EXP2_DBL_MANT_DIG 9007199254740992.0
2386#else
2387#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2388#endif
2389
2390double
2391_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2394 /* See below for why x_digits is always large enough. */
2395 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2396 double dx;
2397 /* Correction term for round-half-to-even rounding. For a digit x,
2398 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2399 multiple of 4, rounding ties to a multiple of 8. */
2400 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 a_size = ABS(Py_SIZE(a));
2403 if (a_size == 0) {
2404 /* Special case for 0: significand 0.0, exponent 0. */
2405 *e = 0;
2406 return 0.0;
2407 }
2408 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2409 /* The following is an overflow-free version of the check
2410 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2411 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2412 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2413 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002414 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2418 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 Number of digits needed for result: write // for floor division.
2421 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2430 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2433 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2434 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 in both cases.
2441 */
2442 if (a_bits <= DBL_MANT_DIG + 2) {
2443 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2444 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2445 x_size = 0;
2446 while (x_size < shift_digits)
2447 x_digits[x_size++] = 0;
2448 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2449 (int)shift_bits);
2450 x_size += a_size;
2451 x_digits[x_size++] = rem;
2452 }
2453 else {
2454 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2455 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2456 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2457 a_size - shift_digits, (int)shift_bits);
2458 x_size = a_size - shift_digits;
2459 /* For correct rounding below, we need the least significant
2460 bit of x to be 'sticky' for this shift: if any of the bits
2461 shifted out was nonzero, we set the least significant bit
2462 of x. */
2463 if (rem)
2464 x_digits[0] |= 1;
2465 else
2466 while (shift_digits > 0)
2467 if (a->ob_digit[--shift_digits]) {
2468 x_digits[0] |= 1;
2469 break;
2470 }
2471 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002472 assert(1 <= x_size &&
2473 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 /* Round, and convert to double. */
2476 x_digits[0] += half_even_correction[x_digits[0] & 7];
2477 dx = x_digits[--x_size];
2478 while (x_size > 0)
2479 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 /* Rescale; make correction if result is 1.0. */
2482 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2483 if (dx == 1.0) {
2484 if (a_bits == PY_SSIZE_T_MAX)
2485 goto overflow;
2486 dx = 0.5;
2487 a_bits += 1;
2488 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 *e = a_bits;
2491 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002492
2493 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* exponent > PY_SSIZE_T_MAX */
2495 PyErr_SetString(PyExc_OverflowError,
2496 "huge integer: number of bits overflows a Py_ssize_t");
2497 *e = 0;
2498 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002499}
2500
2501/* Get a C double from a long int object. Rounds to the nearest double,
2502 using the round-half-to-even rule in the case of a tie. */
2503
2504double
2505PyLong_AsDouble(PyObject *v)
2506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 Py_ssize_t exponent;
2508 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (v == NULL || !PyLong_Check(v)) {
2511 PyErr_BadInternalCall();
2512 return -1.0;
2513 }
2514 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2515 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2516 PyErr_SetString(PyExc_OverflowError,
2517 "long int too large to convert to float");
2518 return -1.0;
2519 }
2520 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002521}
2522
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002523/* Methods */
2524
2525static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002526long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002529}
2530
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002531static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002532long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (Py_SIZE(a) != Py_SIZE(b)) {
2537 sign = Py_SIZE(a) - Py_SIZE(b);
2538 }
2539 else {
2540 Py_ssize_t i = ABS(Py_SIZE(a));
2541 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2542 ;
2543 if (i < 0)
2544 sign = 0;
2545 else {
2546 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2547 if (Py_SIZE(a) < 0)
2548 sign = -sign;
2549 }
2550 }
2551 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002552}
2553
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002554#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002556
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002557static PyObject *
2558long_richcompare(PyObject *self, PyObject *other, int op)
2559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 int result;
2561 PyObject *v;
2562 CHECK_BINOP(self, other);
2563 if (self == other)
2564 result = 0;
2565 else
2566 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2567 /* Convert the return value to a Boolean */
2568 switch (op) {
2569 case Py_EQ:
2570 v = TEST_COND(result == 0);
2571 break;
2572 case Py_NE:
2573 v = TEST_COND(result != 0);
2574 break;
2575 case Py_LE:
2576 v = TEST_COND(result <= 0);
2577 break;
2578 case Py_GE:
2579 v = TEST_COND(result >= 0);
2580 break;
2581 case Py_LT:
2582 v = TEST_COND(result == -1);
2583 break;
2584 case Py_GT:
2585 v = TEST_COND(result == 1);
2586 break;
2587 default:
2588 PyErr_BadArgument();
2589 return NULL;
2590 }
2591 Py_INCREF(v);
2592 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002593}
2594
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002595static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002596long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002597{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002598 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 Py_ssize_t i;
2600 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 i = Py_SIZE(v);
2603 switch(i) {
2604 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2605 case 0: return 0;
2606 case 1: return v->ob_digit[0];
2607 }
2608 sign = 1;
2609 x = 0;
2610 if (i < 0) {
2611 sign = -1;
2612 i = -(i);
2613 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002615 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2616 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2617 _PyHASH_MODULUS.
2618
2619 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2620 amounts to a rotation of the bits of x. To see this, write
2621
2622 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2623
2624 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2625 PyLong_SHIFT bits of x (those that are shifted out of the
2626 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2627 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2628 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2629 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2630 congruent to y modulo _PyHASH_MODULUS. So
2631
2632 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2633
2634 The right-hand side is just the result of rotating the
2635 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2636 not all _PyHASH_BITS bits of x are 1s, the same is true
2637 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2638 the reduction of x*2**PyLong_SHIFT modulo
2639 _PyHASH_MODULUS. */
2640 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2641 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002643 if (x >= _PyHASH_MODULUS)
2644 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 }
2646 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002647 if (x == (Py_uhash_t)-1)
2648 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002649 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002650}
2651
2652
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002653/* Add the absolute values of two long integers. */
2654
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002655static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002656x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2659 PyLongObject *z;
2660 Py_ssize_t i;
2661 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 /* Ensure a is the larger of the two: */
2664 if (size_a < size_b) {
2665 { PyLongObject *temp = a; a = b; b = temp; }
2666 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002667 size_a = size_b;
2668 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 }
2670 z = _PyLong_New(size_a+1);
2671 if (z == NULL)
2672 return NULL;
2673 for (i = 0; i < size_b; ++i) {
2674 carry += a->ob_digit[i] + b->ob_digit[i];
2675 z->ob_digit[i] = carry & PyLong_MASK;
2676 carry >>= PyLong_SHIFT;
2677 }
2678 for (; i < size_a; ++i) {
2679 carry += a->ob_digit[i];
2680 z->ob_digit[i] = carry & PyLong_MASK;
2681 carry >>= PyLong_SHIFT;
2682 }
2683 z->ob_digit[i] = carry;
2684 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002685}
2686
2687/* Subtract the absolute values of two integers. */
2688
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002689static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002690x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2693 PyLongObject *z;
2694 Py_ssize_t i;
2695 int sign = 1;
2696 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 /* Ensure a is the larger of the two: */
2699 if (size_a < size_b) {
2700 sign = -1;
2701 { PyLongObject *temp = a; a = b; b = temp; }
2702 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002703 size_a = size_b;
2704 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 }
2706 else if (size_a == size_b) {
2707 /* Find highest digit where a and b differ: */
2708 i = size_a;
2709 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2710 ;
2711 if (i < 0)
2712 return (PyLongObject *)PyLong_FromLong(0);
2713 if (a->ob_digit[i] < b->ob_digit[i]) {
2714 sign = -1;
2715 { PyLongObject *temp = a; a = b; b = temp; }
2716 }
2717 size_a = size_b = i+1;
2718 }
2719 z = _PyLong_New(size_a);
2720 if (z == NULL)
2721 return NULL;
2722 for (i = 0; i < size_b; ++i) {
2723 /* The following assumes unsigned arithmetic
2724 works module 2**N for some N>PyLong_SHIFT. */
2725 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2726 z->ob_digit[i] = borrow & PyLong_MASK;
2727 borrow >>= PyLong_SHIFT;
2728 borrow &= 1; /* Keep only one sign bit */
2729 }
2730 for (; i < size_a; ++i) {
2731 borrow = a->ob_digit[i] - borrow;
2732 z->ob_digit[i] = borrow & PyLong_MASK;
2733 borrow >>= PyLong_SHIFT;
2734 borrow &= 1; /* Keep only one sign bit */
2735 }
2736 assert(borrow == 0);
2737 if (sign < 0)
2738 NEGATE(z);
2739 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002740}
2741
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002742static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002743long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2750 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2751 MEDIUM_VALUE(b));
2752 return result;
2753 }
2754 if (Py_SIZE(a) < 0) {
2755 if (Py_SIZE(b) < 0) {
2756 z = x_add(a, b);
2757 if (z != NULL && Py_SIZE(z) != 0)
2758 Py_SIZE(z) = -(Py_SIZE(z));
2759 }
2760 else
2761 z = x_sub(b, a);
2762 }
2763 else {
2764 if (Py_SIZE(b) < 0)
2765 z = x_sub(a, b);
2766 else
2767 z = x_add(a, b);
2768 }
2769 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002770}
2771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002772static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002773long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2780 PyObject* r;
2781 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2782 return r;
2783 }
2784 if (Py_SIZE(a) < 0) {
2785 if (Py_SIZE(b) < 0)
2786 z = x_sub(a, b);
2787 else
2788 z = x_add(a, b);
2789 if (z != NULL && Py_SIZE(z) != 0)
2790 Py_SIZE(z) = -(Py_SIZE(z));
2791 }
2792 else {
2793 if (Py_SIZE(b) < 0)
2794 z = x_add(a, b);
2795 else
2796 z = x_sub(a, b);
2797 }
2798 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002799}
2800
Tim Peters5af4e6c2002-08-12 02:31:19 +00002801/* Grade school multiplication, ignoring the signs.
2802 * Returns the absolute value of the product, or NULL if error.
2803 */
2804static PyLongObject *
2805x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 PyLongObject *z;
2808 Py_ssize_t size_a = ABS(Py_SIZE(a));
2809 Py_ssize_t size_b = ABS(Py_SIZE(b));
2810 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 z = _PyLong_New(size_a + size_b);
2813 if (z == NULL)
2814 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2817 if (a == b) {
2818 /* Efficient squaring per HAC, Algorithm 14.16:
2819 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2820 * Gives slightly less than a 2x speedup when a == b,
2821 * via exploiting that each entry in the multiplication
2822 * pyramid appears twice (except for the size_a squares).
2823 */
2824 for (i = 0; i < size_a; ++i) {
2825 twodigits carry;
2826 twodigits f = a->ob_digit[i];
2827 digit *pz = z->ob_digit + (i << 1);
2828 digit *pa = a->ob_digit + i + 1;
2829 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002832 Py_DECREF(z);
2833 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002834 });
Tim Peters0973b992004-08-29 22:16:50 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 carry = *pz + f * f;
2837 *pz++ = (digit)(carry & PyLong_MASK);
2838 carry >>= PyLong_SHIFT;
2839 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 /* Now f is added in twice in each column of the
2842 * pyramid it appears. Same as adding f<<1 once.
2843 */
2844 f <<= 1;
2845 while (pa < paend) {
2846 carry += *pz + *pa++ * f;
2847 *pz++ = (digit)(carry & PyLong_MASK);
2848 carry >>= PyLong_SHIFT;
2849 assert(carry <= (PyLong_MASK << 1));
2850 }
2851 if (carry) {
2852 carry += *pz;
2853 *pz++ = (digit)(carry & PyLong_MASK);
2854 carry >>= PyLong_SHIFT;
2855 }
2856 if (carry)
2857 *pz += (digit)(carry & PyLong_MASK);
2858 assert((carry >> PyLong_SHIFT) == 0);
2859 }
2860 }
2861 else { /* a is not the same as b -- gradeschool long mult */
2862 for (i = 0; i < size_a; ++i) {
2863 twodigits carry = 0;
2864 twodigits f = a->ob_digit[i];
2865 digit *pz = z->ob_digit + i;
2866 digit *pb = b->ob_digit;
2867 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002870 Py_DECREF(z);
2871 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002872 });
Tim Peters0973b992004-08-29 22:16:50 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 while (pb < pbend) {
2875 carry += *pz + *pb++ * f;
2876 *pz++ = (digit)(carry & PyLong_MASK);
2877 carry >>= PyLong_SHIFT;
2878 assert(carry <= PyLong_MASK);
2879 }
2880 if (carry)
2881 *pz += (digit)(carry & PyLong_MASK);
2882 assert((carry >> PyLong_SHIFT) == 0);
2883 }
2884 }
2885 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002886}
2887
2888/* A helper for Karatsuba multiplication (k_mul).
2889 Takes a long "n" and an integer "size" representing the place to
2890 split, and sets low and high such that abs(n) == (high << size) + low,
2891 viewing the shift as being by digits. The sign bit is ignored, and
2892 the return values are >= 0.
2893 Returns 0 on success, -1 on failure.
2894*/
2895static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002896kmul_split(PyLongObject *n,
2897 Py_ssize_t size,
2898 PyLongObject **high,
2899 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 PyLongObject *hi, *lo;
2902 Py_ssize_t size_lo, size_hi;
2903 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 size_lo = MIN(size_n, size);
2906 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 if ((hi = _PyLong_New(size_hi)) == NULL)
2909 return -1;
2910 if ((lo = _PyLong_New(size_lo)) == NULL) {
2911 Py_DECREF(hi);
2912 return -1;
2913 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2916 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 *high = long_normalize(hi);
2919 *low = long_normalize(lo);
2920 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002921}
2922
Tim Peters60004642002-08-12 22:01:34 +00002923static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2924
Tim Peters5af4e6c2002-08-12 02:31:19 +00002925/* Karatsuba multiplication. Ignores the input signs, and returns the
2926 * absolute value of the product (or NULL if error).
2927 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2928 */
2929static PyLongObject *
2930k_mul(PyLongObject *a, PyLongObject *b)
2931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 Py_ssize_t asize = ABS(Py_SIZE(a));
2933 Py_ssize_t bsize = ABS(Py_SIZE(b));
2934 PyLongObject *ah = NULL;
2935 PyLongObject *al = NULL;
2936 PyLongObject *bh = NULL;
2937 PyLongObject *bl = NULL;
2938 PyLongObject *ret = NULL;
2939 PyLongObject *t1, *t2, *t3;
2940 Py_ssize_t shift; /* the number of digits we split off */
2941 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2944 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2945 * Then the original product is
2946 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2947 * By picking X to be a power of 2, "*X" is just shifting, and it's
2948 * been reduced to 3 multiplies on numbers half the size.
2949 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 /* We want to split based on the larger number; fiddle so that b
2952 * is largest.
2953 */
2954 if (asize > bsize) {
2955 t1 = a;
2956 a = b;
2957 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 i = asize;
2960 asize = bsize;
2961 bsize = i;
2962 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 /* Use gradeschool math when either number is too small. */
2965 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2966 if (asize <= i) {
2967 if (asize == 0)
2968 return (PyLongObject *)PyLong_FromLong(0);
2969 else
2970 return x_mul(a, b);
2971 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 /* If a is small compared to b, splitting on b gives a degenerate
2974 * case with ah==0, and Karatsuba may be (even much) less efficient
2975 * than "grade school" then. However, we can still win, by viewing
2976 * b as a string of "big digits", each of width a->ob_size. That
2977 * leads to a sequence of balanced calls to k_mul.
2978 */
2979 if (2 * asize <= bsize)
2980 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 /* Split a & b into hi & lo pieces. */
2983 shift = bsize >> 1;
2984 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2985 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 if (a == b) {
2988 bh = ah;
2989 bl = al;
2990 Py_INCREF(bh);
2991 Py_INCREF(bl);
2992 }
2993 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002995 /* The plan:
2996 * 1. Allocate result space (asize + bsize digits: that's always
2997 * enough).
2998 * 2. Compute ah*bh, and copy into result at 2*shift.
2999 * 3. Compute al*bl, and copy into result at 0. Note that this
3000 * can't overlap with #2.
3001 * 4. Subtract al*bl from the result, starting at shift. This may
3002 * underflow (borrow out of the high digit), but we don't care:
3003 * we're effectively doing unsigned arithmetic mod
3004 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3005 * borrows and carries out of the high digit can be ignored.
3006 * 5. Subtract ah*bh from the result, starting at shift.
3007 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3008 * at shift.
3009 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 /* 1. Allocate result space. */
3012 ret = _PyLong_New(asize + bsize);
3013 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003014#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 /* Fill with trash, to catch reference to uninitialized digits. */
3016 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003017#endif
Tim Peters44121a62002-08-12 06:17:58 +00003018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3020 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3021 assert(Py_SIZE(t1) >= 0);
3022 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3023 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3024 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 /* Zero-out the digits higher than the ah*bh copy. */
3027 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3028 if (i)
3029 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3030 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 /* 3. t2 <- al*bl, and copy into the low digits. */
3033 if ((t2 = k_mul(al, bl)) == NULL) {
3034 Py_DECREF(t1);
3035 goto fail;
3036 }
3037 assert(Py_SIZE(t2) >= 0);
3038 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3039 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003041 /* Zero out remaining digits. */
3042 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3043 if (i)
3044 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3047 * because it's fresher in cache.
3048 */
3049 i = Py_SIZE(ret) - shift; /* # digits after shift */
3050 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3051 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3054 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3057 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3058 Py_DECREF(ah);
3059 Py_DECREF(al);
3060 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 if (a == b) {
3063 t2 = t1;
3064 Py_INCREF(t2);
3065 }
3066 else if ((t2 = x_add(bh, bl)) == NULL) {
3067 Py_DECREF(t1);
3068 goto fail;
3069 }
3070 Py_DECREF(bh);
3071 Py_DECREF(bl);
3072 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 t3 = k_mul(t1, t2);
3075 Py_DECREF(t1);
3076 Py_DECREF(t2);
3077 if (t3 == NULL) goto fail;
3078 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 /* Add t3. It's not obvious why we can't run out of room here.
3081 * See the (*) comment after this function.
3082 */
3083 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3084 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003087
Mark Dickinson22b20182010-05-10 21:27:53 +00003088 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 Py_XDECREF(ret);
3090 Py_XDECREF(ah);
3091 Py_XDECREF(al);
3092 Py_XDECREF(bh);
3093 Py_XDECREF(bl);
3094 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003095}
3096
Tim Petersd6974a52002-08-13 20:37:51 +00003097/* (*) Why adding t3 can't "run out of room" above.
3098
Tim Petersab86c2b2002-08-15 20:06:00 +00003099Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3100to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003101
Tim Petersab86c2b2002-08-15 20:06:00 +000031021. For any integer i, i = c(i/2) + f(i/2). In particular,
3103 bsize = c(bsize/2) + f(bsize/2).
31042. shift = f(bsize/2)
31053. asize <= bsize
31064. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3107 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003108
Tim Petersab86c2b2002-08-15 20:06:00 +00003109We allocated asize + bsize result digits, and add t3 into them at an offset
3110of shift. This leaves asize+bsize-shift allocated digit positions for t3
3111to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3112asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003113
Tim Petersab86c2b2002-08-15 20:06:00 +00003114bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3115at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003116
Tim Petersab86c2b2002-08-15 20:06:00 +00003117If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3118digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3119most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003120
Tim Petersab86c2b2002-08-15 20:06:00 +00003121The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003122
Tim Petersab86c2b2002-08-15 20:06:00 +00003123 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003124
Tim Petersab86c2b2002-08-15 20:06:00 +00003125and we have asize + c(bsize/2) available digit positions. We need to show
3126this is always enough. An instance of c(bsize/2) cancels out in both, so
3127the question reduces to whether asize digits is enough to hold
3128(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3129then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3130asize 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 +00003131digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003132asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003133c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3134is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3135bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003136
Tim Peters48d52c02002-08-14 17:07:32 +00003137Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3138clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3139ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003140*/
3141
Tim Peters60004642002-08-12 22:01:34 +00003142/* b has at least twice the digits of a, and a is big enough that Karatsuba
3143 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3144 * of slices, each with a->ob_size digits, and multiply the slices by a,
3145 * one at a time. This gives k_mul balanced inputs to work with, and is
3146 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003147 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003148 * single-width slice overlap between successive partial sums).
3149 */
3150static PyLongObject *
3151k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 const Py_ssize_t asize = ABS(Py_SIZE(a));
3154 Py_ssize_t bsize = ABS(Py_SIZE(b));
3155 Py_ssize_t nbdone; /* # of b digits already multiplied */
3156 PyLongObject *ret;
3157 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 assert(asize > KARATSUBA_CUTOFF);
3160 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* Allocate result space, and zero it out. */
3163 ret = _PyLong_New(asize + bsize);
3164 if (ret == NULL)
3165 return NULL;
3166 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* Successive slices of b are copied into bslice. */
3169 bslice = _PyLong_New(asize);
3170 if (bslice == NULL)
3171 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 nbdone = 0;
3174 while (bsize > 0) {
3175 PyLongObject *product;
3176 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 /* Multiply the next slice of b by a. */
3179 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3180 nbtouse * sizeof(digit));
3181 Py_SIZE(bslice) = nbtouse;
3182 product = k_mul(a, bslice);
3183 if (product == NULL)
3184 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 /* Add into result. */
3187 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3188 product->ob_digit, Py_SIZE(product));
3189 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 bsize -= nbtouse;
3192 nbdone += nbtouse;
3193 }
Tim Peters60004642002-08-12 22:01:34 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 Py_DECREF(bslice);
3196 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003197
Mark Dickinson22b20182010-05-10 21:27:53 +00003198 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 Py_DECREF(ret);
3200 Py_XDECREF(bslice);
3201 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003202}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003203
3204static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003205long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 /* fast path for single-digit multiplication */
3212 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3213 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003214#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003216#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 /* if we don't have long long then we're almost certainly
3218 using 15-bit digits, so v will fit in a long. In the
3219 unlikely event that we're using 30-bit digits on a platform
3220 without long long, a large v will just cause us to fall
3221 through to the general multiplication code below. */
3222 if (v >= LONG_MIN && v <= LONG_MAX)
3223 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003224#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 z = k_mul(a, b);
3228 /* Negate if exactly one of the inputs is negative. */
3229 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3230 NEGATE(z);
3231 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003232}
3233
Guido van Rossume32e0141992-01-19 16:31:05 +00003234/* The / and % operators are now defined in terms of divmod().
3235 The expression a mod b has the value a - b*floor(a/b).
3236 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003237 |a| by |b|, with the sign of a. This is also expressed
3238 as a - b*trunc(a/b), if trunc truncates towards zero.
3239 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 a b a rem b a mod b
3241 13 10 3 3
3242 -13 10 -3 7
3243 13 -10 3 -7
3244 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003245 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003246 have different signs. We then subtract one from the 'div'
3247 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003248
Tim Peters47e52ee2004-08-30 02:44:38 +00003249/* Compute
3250 * *pdiv, *pmod = divmod(v, w)
3251 * NULL can be passed for pdiv or pmod, in which case that part of
3252 * the result is simply thrown away. The caller owns a reference to
3253 * each of these it requests (does not pass NULL for).
3254 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003255static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003256l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 if (long_divrem(v, w, &div, &mod) < 0)
3262 return -1;
3263 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3264 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3265 PyLongObject *temp;
3266 PyLongObject *one;
3267 temp = (PyLongObject *) long_add(mod, w);
3268 Py_DECREF(mod);
3269 mod = temp;
3270 if (mod == NULL) {
3271 Py_DECREF(div);
3272 return -1;
3273 }
3274 one = (PyLongObject *) PyLong_FromLong(1L);
3275 if (one == NULL ||
3276 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3277 Py_DECREF(mod);
3278 Py_DECREF(div);
3279 Py_XDECREF(one);
3280 return -1;
3281 }
3282 Py_DECREF(one);
3283 Py_DECREF(div);
3284 div = temp;
3285 }
3286 if (pdiv != NULL)
3287 *pdiv = div;
3288 else
3289 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 if (pmod != NULL)
3292 *pmod = mod;
3293 else
3294 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003297}
3298
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003299static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003300long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 CHECK_BINOP(a, b);
3305 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3306 div = NULL;
3307 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003308}
3309
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003310/* PyLong/PyLong -> float, with correctly rounded result. */
3311
3312#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3313#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3314
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003315static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003316long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 PyLongObject *a, *b, *x;
3319 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3320 digit mask, low;
3321 int inexact, negate, a_is_small, b_is_small;
3322 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 CHECK_BINOP(v, w);
3325 a = (PyLongObject *)v;
3326 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 /*
3329 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3332 1. choose a suitable integer 'shift'
3333 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3334 3. adjust x for correct rounding
3335 4. convert x to a double dx with the same value
3336 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3341 returns either 0.0 or -0.0, depending on the sign of b. For a and
3342 b both nonzero, ignore signs of a and b, and add the sign back in
3343 at the end. Now write a_bits and b_bits for the bit lengths of a
3344 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3345 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3350 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3351 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3352 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 1. The integer 'shift' is chosen so that x has the right number of
3357 bits for a double, plus two or three extra bits that will be used
3358 in the rounding decisions. Writing a_bits and b_bits for the
3359 number of significant bits in a and b respectively, a
3360 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 This is fine in the usual case, but if a/b is smaller than the
3365 smallest normal float then it can lead to double rounding on an
3366 IEEE 754 platform, giving incorrectly rounded results. So we
3367 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 2. The quantity x is computed by first shifting a (left -shift bits
3372 if shift <= 0, right shift bits if shift > 0) and then dividing by
3373 b. For both the shift and the division, we keep track of whether
3374 the result is inexact, in a flag 'inexact'; this information is
3375 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 With the choice of shift above, together with our assumption that
3378 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3379 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3382 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 For float representability, we need x/2**extra_bits <
3387 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3388 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 To round, we just modify the bottom digit of x in-place; this can
3393 end up giving a digit with value > PyLONG_MASK, but that's not a
3394 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 With the original choices for shift above, extra_bits will always
3397 be 2 or 3. Then rounding under the round-half-to-even rule, we
3398 round up iff the most significant of the extra bits is 1, and
3399 either: (a) the computation of x in step 2 had an inexact result,
3400 or (b) at least one other of the extra bits is 1, or (c) the least
3401 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 4. Conversion to a double is straightforward; all floating-point
3404 operations involved in the conversion are exact, so there's no
3405 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3408 The result will always be exactly representable as a double, except
3409 in the case that it overflows. To avoid dependence on the exact
3410 behaviour of ldexp on overflow, we check for overflow before
3411 applying ldexp. The result of ldexp is adjusted for sign before
3412 returning.
3413 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 /* Reduce to case where a and b are both positive. */
3416 a_size = ABS(Py_SIZE(a));
3417 b_size = ABS(Py_SIZE(b));
3418 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3419 if (b_size == 0) {
3420 PyErr_SetString(PyExc_ZeroDivisionError,
3421 "division by zero");
3422 goto error;
3423 }
3424 if (a_size == 0)
3425 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 /* Fast path for a and b small (exactly representable in a double).
3428 Relies on floating-point division being correctly rounded; results
3429 may be subject to double rounding on x86 machines that operate with
3430 the x87 FPU set to 64-bit precision. */
3431 a_is_small = a_size <= MANT_DIG_DIGITS ||
3432 (a_size == MANT_DIG_DIGITS+1 &&
3433 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3434 b_is_small = b_size <= MANT_DIG_DIGITS ||
3435 (b_size == MANT_DIG_DIGITS+1 &&
3436 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3437 if (a_is_small && b_is_small) {
3438 double da, db;
3439 da = a->ob_digit[--a_size];
3440 while (a_size > 0)
3441 da = da * PyLong_BASE + a->ob_digit[--a_size];
3442 db = b->ob_digit[--b_size];
3443 while (b_size > 0)
3444 db = db * PyLong_BASE + b->ob_digit[--b_size];
3445 result = da / db;
3446 goto success;
3447 }
Tim Peterse2a60002001-09-04 06:17:36 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* Catch obvious cases of underflow and overflow */
3450 diff = a_size - b_size;
3451 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3452 /* Extreme overflow */
3453 goto overflow;
3454 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3455 /* Extreme underflow */
3456 goto underflow_or_zero;
3457 /* Next line is now safe from overflowing a Py_ssize_t */
3458 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3459 bits_in_digit(b->ob_digit[b_size - 1]);
3460 /* Now diff = a_bits - b_bits. */
3461 if (diff > DBL_MAX_EXP)
3462 goto overflow;
3463 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3464 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /* Choose value for shift; see comments for step 1 above. */
3467 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003471 /* x = abs(a * 2**-shift) */
3472 if (shift <= 0) {
3473 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3474 digit rem;
3475 /* x = a << -shift */
3476 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3477 /* In practice, it's probably impossible to end up
3478 here. Both a and b would have to be enormous,
3479 using close to SIZE_T_MAX bytes of memory each. */
3480 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003481 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 goto error;
3483 }
3484 x = _PyLong_New(a_size + shift_digits + 1);
3485 if (x == NULL)
3486 goto error;
3487 for (i = 0; i < shift_digits; i++)
3488 x->ob_digit[i] = 0;
3489 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3490 a_size, -shift % PyLong_SHIFT);
3491 x->ob_digit[a_size + shift_digits] = rem;
3492 }
3493 else {
3494 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3495 digit rem;
3496 /* x = a >> shift */
3497 assert(a_size >= shift_digits);
3498 x = _PyLong_New(a_size - shift_digits);
3499 if (x == NULL)
3500 goto error;
3501 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3502 a_size - shift_digits, shift % PyLong_SHIFT);
3503 /* set inexact if any of the bits shifted out is nonzero */
3504 if (rem)
3505 inexact = 1;
3506 while (!inexact && shift_digits > 0)
3507 if (a->ob_digit[--shift_digits])
3508 inexact = 1;
3509 }
3510 long_normalize(x);
3511 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3514 reference to x, so it's safe to modify it in-place. */
3515 if (b_size == 1) {
3516 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3517 b->ob_digit[0]);
3518 long_normalize(x);
3519 if (rem)
3520 inexact = 1;
3521 }
3522 else {
3523 PyLongObject *div, *rem;
3524 div = x_divrem(x, b, &rem);
3525 Py_DECREF(x);
3526 x = div;
3527 if (x == NULL)
3528 goto error;
3529 if (Py_SIZE(rem))
3530 inexact = 1;
3531 Py_DECREF(rem);
3532 }
3533 x_size = ABS(Py_SIZE(x));
3534 assert(x_size > 0); /* result of division is never zero */
3535 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* The number of extra bits that have to be rounded away. */
3538 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3539 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 /* Round by directly modifying the low digit of x. */
3542 mask = (digit)1 << (extra_bits - 1);
3543 low = x->ob_digit[0] | inexact;
3544 if (low & mask && low & (3*mask-1))
3545 low += mask;
3546 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 /* Convert x to a double dx; the conversion is exact. */
3549 dx = x->ob_digit[--x_size];
3550 while (x_size > 0)
3551 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3552 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 /* Check whether ldexp result will overflow a double. */
3555 if (shift + x_bits >= DBL_MAX_EXP &&
3556 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3557 goto overflow;
3558 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003559
3560 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003562
3563 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003565
3566 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 PyErr_SetString(PyExc_OverflowError,
3568 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003569 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003571}
3572
3573static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003574long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 CHECK_BINOP(a, b);
3579
3580 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3581 mod = NULL;
3582 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003583}
3584
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003585static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003586long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 PyLongObject *div, *mod;
3589 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3594 return NULL;
3595 }
3596 z = PyTuple_New(2);
3597 if (z != NULL) {
3598 PyTuple_SetItem(z, 0, (PyObject *) div);
3599 PyTuple_SetItem(z, 1, (PyObject *) mod);
3600 }
3601 else {
3602 Py_DECREF(div);
3603 Py_DECREF(mod);
3604 }
3605 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003606}
3607
Tim Peters47e52ee2004-08-30 02:44:38 +00003608/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003609static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003610long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3613 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 PyLongObject *z = NULL; /* accumulated result */
3616 Py_ssize_t i, j, k; /* counters */
3617 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 /* 5-ary values. If the exponent is large enough, table is
3620 * precomputed so that table[i] == a**i % c for i in range(32).
3621 */
3622 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3623 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 /* a, b, c = v, w, x */
3626 CHECK_BINOP(v, w);
3627 a = (PyLongObject*)v; Py_INCREF(a);
3628 b = (PyLongObject*)w; Py_INCREF(b);
3629 if (PyLong_Check(x)) {
3630 c = (PyLongObject *)x;
3631 Py_INCREF(x);
3632 }
3633 else if (x == Py_None)
3634 c = NULL;
3635 else {
3636 Py_DECREF(a);
3637 Py_DECREF(b);
3638 Py_INCREF(Py_NotImplemented);
3639 return Py_NotImplemented;
3640 }
Tim Peters4c483c42001-09-05 06:24:58 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3643 if (c) {
3644 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003645 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003646 goto Error;
3647 }
3648 else {
3649 /* else return a float. This works because we know
3650 that this calls float_pow() which converts its
3651 arguments to double. */
3652 Py_DECREF(a);
3653 Py_DECREF(b);
3654 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3655 }
3656 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 if (c) {
3659 /* if modulus == 0:
3660 raise ValueError() */
3661 if (Py_SIZE(c) == 0) {
3662 PyErr_SetString(PyExc_ValueError,
3663 "pow() 3rd argument cannot be 0");
3664 goto Error;
3665 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 /* if modulus < 0:
3668 negativeOutput = True
3669 modulus = -modulus */
3670 if (Py_SIZE(c) < 0) {
3671 negativeOutput = 1;
3672 temp = (PyLongObject *)_PyLong_Copy(c);
3673 if (temp == NULL)
3674 goto Error;
3675 Py_DECREF(c);
3676 c = temp;
3677 temp = NULL;
3678 NEGATE(c);
3679 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 /* if modulus == 1:
3682 return 0 */
3683 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3684 z = (PyLongObject *)PyLong_FromLong(0L);
3685 goto Done;
3686 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 /* if base < 0:
3689 base = base % modulus
3690 Having the base positive just makes things easier. */
3691 if (Py_SIZE(a) < 0) {
3692 if (l_divmod(a, c, NULL, &temp) < 0)
3693 goto Error;
3694 Py_DECREF(a);
3695 a = temp;
3696 temp = NULL;
3697 }
3698 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003700 /* At this point a, b, and c are guaranteed non-negative UNLESS
3701 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 z = (PyLongObject *)PyLong_FromLong(1L);
3704 if (z == NULL)
3705 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 /* Perform a modular reduction, X = X % c, but leave X alone if c
3708 * is NULL.
3709 */
3710#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003711 do { \
3712 if (c != NULL) { \
3713 if (l_divmod(X, c, NULL, &temp) < 0) \
3714 goto Error; \
3715 Py_XDECREF(X); \
3716 X = temp; \
3717 temp = NULL; \
3718 } \
3719 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 /* Multiply two values, then reduce the result:
3722 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003723#define MULT(X, Y, result) \
3724 do { \
3725 temp = (PyLongObject *)long_mul(X, Y); \
3726 if (temp == NULL) \
3727 goto Error; \
3728 Py_XDECREF(result); \
3729 result = temp; \
3730 temp = NULL; \
3731 REDUCE(result); \
3732 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3735 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3736 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3737 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3738 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003741 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003743 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 }
3745 }
3746 }
3747 else {
3748 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3749 Py_INCREF(z); /* still holds 1L */
3750 table[0] = z;
3751 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003752 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3755 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3758 const int index = (bi >> j) & 0x1f;
3759 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003760 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003762 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 }
3764 }
3765 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 if (negativeOutput && (Py_SIZE(z) != 0)) {
3768 temp = (PyLongObject *)long_sub(z, c);
3769 if (temp == NULL)
3770 goto Error;
3771 Py_DECREF(z);
3772 z = temp;
3773 temp = NULL;
3774 }
3775 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003776
Mark Dickinson22b20182010-05-10 21:27:53 +00003777 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 if (z != NULL) {
3779 Py_DECREF(z);
3780 z = NULL;
3781 }
3782 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003783 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3785 for (i = 0; i < 32; ++i)
3786 Py_XDECREF(table[i]);
3787 }
3788 Py_DECREF(a);
3789 Py_DECREF(b);
3790 Py_XDECREF(c);
3791 Py_XDECREF(temp);
3792 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003793}
3794
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003795static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003796long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 /* Implement ~x as -(x+1) */
3799 PyLongObject *x;
3800 PyLongObject *w;
3801 if (ABS(Py_SIZE(v)) <=1)
3802 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3803 w = (PyLongObject *)PyLong_FromLong(1L);
3804 if (w == NULL)
3805 return NULL;
3806 x = (PyLongObject *) long_add(v, w);
3807 Py_DECREF(w);
3808 if (x == NULL)
3809 return NULL;
3810 Py_SIZE(x) = -(Py_SIZE(x));
3811 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003812}
3813
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003814static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003815long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 PyLongObject *z;
3818 if (ABS(Py_SIZE(v)) <= 1)
3819 return PyLong_FromLong(-MEDIUM_VALUE(v));
3820 z = (PyLongObject *)_PyLong_Copy(v);
3821 if (z != NULL)
3822 Py_SIZE(z) = -(Py_SIZE(v));
3823 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003824}
3825
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003826static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003827long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003828{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 if (Py_SIZE(v) < 0)
3830 return long_neg(v);
3831 else
3832 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003833}
3834
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003835static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003836long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003839}
3840
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003841static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003842long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 PyLongObject *z = NULL;
3845 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3846 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 if (Py_SIZE(a) < 0) {
3851 /* Right shifting negative numbers is harder */
3852 PyLongObject *a1, *a2;
3853 a1 = (PyLongObject *) long_invert(a);
3854 if (a1 == NULL)
3855 goto rshift_error;
3856 a2 = (PyLongObject *) long_rshift(a1, b);
3857 Py_DECREF(a1);
3858 if (a2 == NULL)
3859 goto rshift_error;
3860 z = (PyLongObject *) long_invert(a2);
3861 Py_DECREF(a2);
3862 }
3863 else {
3864 shiftby = PyLong_AsSsize_t((PyObject *)b);
3865 if (shiftby == -1L && PyErr_Occurred())
3866 goto rshift_error;
3867 if (shiftby < 0) {
3868 PyErr_SetString(PyExc_ValueError,
3869 "negative shift count");
3870 goto rshift_error;
3871 }
3872 wordshift = shiftby / PyLong_SHIFT;
3873 newsize = ABS(Py_SIZE(a)) - wordshift;
3874 if (newsize <= 0)
3875 return PyLong_FromLong(0);
3876 loshift = shiftby % PyLong_SHIFT;
3877 hishift = PyLong_SHIFT - loshift;
3878 lomask = ((digit)1 << hishift) - 1;
3879 himask = PyLong_MASK ^ lomask;
3880 z = _PyLong_New(newsize);
3881 if (z == NULL)
3882 goto rshift_error;
3883 if (Py_SIZE(a) < 0)
3884 Py_SIZE(z) = -(Py_SIZE(z));
3885 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3886 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3887 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003888 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 }
3890 z = long_normalize(z);
3891 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003892 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003894
Guido van Rossumc6913e71991-11-19 20:26:46 +00003895}
3896
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003897static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003898long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 /* This version due to Tim Peters */
3901 PyLongObject *a = (PyLongObject*)v;
3902 PyLongObject *b = (PyLongObject*)w;
3903 PyLongObject *z = NULL;
3904 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3905 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 shiftby = PyLong_AsSsize_t((PyObject *)b);
3910 if (shiftby == -1L && PyErr_Occurred())
3911 goto lshift_error;
3912 if (shiftby < 0) {
3913 PyErr_SetString(PyExc_ValueError, "negative shift count");
3914 goto lshift_error;
3915 }
3916 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3917 wordshift = shiftby / PyLong_SHIFT;
3918 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 oldsize = ABS(Py_SIZE(a));
3921 newsize = oldsize + wordshift;
3922 if (remshift)
3923 ++newsize;
3924 z = _PyLong_New(newsize);
3925 if (z == NULL)
3926 goto lshift_error;
3927 if (Py_SIZE(a) < 0)
3928 NEGATE(z);
3929 for (i = 0; i < wordshift; i++)
3930 z->ob_digit[i] = 0;
3931 accum = 0;
3932 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3933 accum |= (twodigits)a->ob_digit[j] << remshift;
3934 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3935 accum >>= PyLong_SHIFT;
3936 }
3937 if (remshift)
3938 z->ob_digit[newsize-1] = (digit)accum;
3939 else
3940 assert(!accum);
3941 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003942 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003944}
3945
Mark Dickinson27a87a22009-10-25 20:43:34 +00003946/* Compute two's complement of digit vector a[0:m], writing result to
3947 z[0:m]. The digit vector a need not be normalized, but should not
3948 be entirely zero. a and z may point to the same digit vector. */
3949
3950static void
3951v_complement(digit *z, digit *a, Py_ssize_t m)
3952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 Py_ssize_t i;
3954 digit carry = 1;
3955 for (i = 0; i < m; ++i) {
3956 carry += a[i] ^ PyLong_MASK;
3957 z[i] = carry & PyLong_MASK;
3958 carry >>= PyLong_SHIFT;
3959 }
3960 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003961}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003962
3963/* Bitwise and/xor/or operations */
3964
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003965static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003966long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003968 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 int nega, negb, negz;
3971 Py_ssize_t size_a, size_b, size_z, i;
3972 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* Bitwise operations for negative numbers operate as though
3975 on a two's complement representation. So convert arguments
3976 from sign-magnitude to two's complement, and convert the
3977 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003979 /* If a is negative, replace it by its two's complement. */
3980 size_a = ABS(Py_SIZE(a));
3981 nega = Py_SIZE(a) < 0;
3982 if (nega) {
3983 z = _PyLong_New(size_a);
3984 if (z == NULL)
3985 return NULL;
3986 v_complement(z->ob_digit, a->ob_digit, size_a);
3987 a = z;
3988 }
3989 else
3990 /* Keep reference count consistent. */
3991 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 /* Same for b. */
3994 size_b = ABS(Py_SIZE(b));
3995 negb = Py_SIZE(b) < 0;
3996 if (negb) {
3997 z = _PyLong_New(size_b);
3998 if (z == NULL) {
3999 Py_DECREF(a);
4000 return NULL;
4001 }
4002 v_complement(z->ob_digit, b->ob_digit, size_b);
4003 b = z;
4004 }
4005 else
4006 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004008 /* Swap a and b if necessary to ensure size_a >= size_b. */
4009 if (size_a < size_b) {
4010 z = a; a = b; b = z;
4011 size_z = size_a; size_a = size_b; size_b = size_z;
4012 negz = nega; nega = negb; negb = negz;
4013 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 /* JRH: The original logic here was to allocate the result value (z)
4016 as the longer of the two operands. However, there are some cases
4017 where the result is guaranteed to be shorter than that: AND of two
4018 positives, OR of two negatives: use the shorter number. AND with
4019 mixed signs: use the positive number. OR with mixed signs: use the
4020 negative number.
4021 */
4022 switch (op) {
4023 case '^':
4024 negz = nega ^ negb;
4025 size_z = size_a;
4026 break;
4027 case '&':
4028 negz = nega & negb;
4029 size_z = negb ? size_a : size_b;
4030 break;
4031 case '|':
4032 negz = nega | negb;
4033 size_z = negb ? size_b : size_a;
4034 break;
4035 default:
4036 PyErr_BadArgument();
4037 return NULL;
4038 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 /* We allow an extra digit if z is negative, to make sure that
4041 the final two's complement of z doesn't overflow. */
4042 z = _PyLong_New(size_z + negz);
4043 if (z == NULL) {
4044 Py_DECREF(a);
4045 Py_DECREF(b);
4046 return NULL;
4047 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 /* Compute digits for overlap of a and b. */
4050 switch(op) {
4051 case '&':
4052 for (i = 0; i < size_b; ++i)
4053 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4054 break;
4055 case '|':
4056 for (i = 0; i < size_b; ++i)
4057 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4058 break;
4059 case '^':
4060 for (i = 0; i < size_b; ++i)
4061 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4062 break;
4063 default:
4064 PyErr_BadArgument();
4065 return NULL;
4066 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004068 /* Copy any remaining digits of a, inverting if necessary. */
4069 if (op == '^' && negb)
4070 for (; i < size_z; ++i)
4071 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4072 else if (i < size_z)
4073 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4074 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 /* Complement result if negative. */
4077 if (negz) {
4078 Py_SIZE(z) = -(Py_SIZE(z));
4079 z->ob_digit[size_z] = PyLong_MASK;
4080 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4081 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 Py_DECREF(a);
4084 Py_DECREF(b);
4085 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004086}
4087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004088static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004089long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 PyObject *c;
4092 CHECK_BINOP(a, b);
4093 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4094 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004095}
4096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004097static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004098long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 PyObject *c;
4101 CHECK_BINOP(a, b);
4102 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4103 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004104}
4105
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004106static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004107long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 PyObject *c;
4110 CHECK_BINOP(a, b);
4111 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4112 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004113}
4114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004115static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004116long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 if (PyLong_CheckExact(v))
4119 Py_INCREF(v);
4120 else
4121 v = _PyLong_Copy((PyLongObject *)v);
4122 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004123}
4124
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004125static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004126long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 double result;
4129 result = PyLong_AsDouble(v);
4130 if (result == -1.0 && PyErr_Occurred())
4131 return NULL;
4132 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004133}
4134
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004135static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004136long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004137
Tim Peters6d6c1a32001-08-02 04:15:00 +00004138static PyObject *
4139long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4140{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004141 PyObject *obase = NULL, *x = NULL;
4142 long base;
4143 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004146 if (type != &PyLong_Type)
4147 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004148 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4149 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004150 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004151 if (x == NULL) {
4152 if (obase != NULL) {
4153 PyErr_SetString(PyExc_TypeError,
4154 "int() missing string argument");
4155 return NULL;
4156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004158 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004159 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004161
4162 base = PyLong_AsLongAndOverflow(obase, &overflow);
4163 if (base == -1 && PyErr_Occurred())
4164 return NULL;
4165 if (overflow || (base != 0 && base < 2) || base > 36) {
4166 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004167 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004168 return NULL;
4169 }
4170
4171 if (PyUnicode_Check(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4173 PyUnicode_GET_SIZE(x),
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004174 (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4176 /* Since PyLong_FromString doesn't have a length parameter,
4177 * check here for possible NULs in the string. */
4178 char *string;
4179 Py_ssize_t size = Py_SIZE(x);
4180 if (PyByteArray_Check(x))
4181 string = PyByteArray_AS_STRING(x);
4182 else
4183 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004184 if (strlen(string) != (size_t)size || !size) {
4185 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 x is a bytes or buffer, *and* a base is given. */
4187 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004188 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004189 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004190 return NULL;
4191 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004192 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004193 }
4194 else {
4195 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004196 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 return NULL;
4198 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004199}
4200
Guido van Rossumbef14172001-08-29 15:47:46 +00004201/* Wimpy, slow approach to tp_new calls for subtypes of long:
4202 first create a regular long from whatever arguments we got,
4203 then allocate a subtype instance and initialize it from
4204 the regular long. The regular long is then thrown away.
4205*/
4206static PyObject *
4207long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 PyLongObject *tmp, *newobj;
4210 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 assert(PyType_IsSubtype(type, &PyLong_Type));
4213 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4214 if (tmp == NULL)
4215 return NULL;
4216 assert(PyLong_CheckExact(tmp));
4217 n = Py_SIZE(tmp);
4218 if (n < 0)
4219 n = -n;
4220 newobj = (PyLongObject *)type->tp_alloc(type, n);
4221 if (newobj == NULL) {
4222 Py_DECREF(tmp);
4223 return NULL;
4224 }
4225 assert(PyLong_Check(newobj));
4226 Py_SIZE(newobj) = Py_SIZE(tmp);
4227 for (i = 0; i < n; i++)
4228 newobj->ob_digit[i] = tmp->ob_digit[i];
4229 Py_DECREF(tmp);
4230 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004231}
4232
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004233static PyObject *
4234long_getnewargs(PyLongObject *v)
4235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004237}
4238
Guido van Rossumb43daf72007-08-01 18:08:08 +00004239static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004240long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004241 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004242}
4243
4244static PyObject *
4245long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004247}
4248
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004249static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004250long__format__(PyObject *self, PyObject *args)
4251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004252 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4255 return NULL;
4256 return _PyLong_FormatAdvanced(self,
4257 PyUnicode_AS_UNICODE(format_spec),
4258 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004259}
4260
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004261/* Return a pair (q, r) such that a = b * q + r, and
4262 abs(r) <= abs(b)/2, with equality possible only if q is even.
4263 In other words, q == a / b, rounded to the nearest integer using
4264 round-half-to-even. */
4265
4266PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004267_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004268{
4269 PyLongObject *quo = NULL, *rem = NULL;
4270 PyObject *one = NULL, *twice_rem, *result, *temp;
4271 int cmp, quo_is_odd, quo_is_neg;
4272
4273 /* Equivalent Python code:
4274
4275 def divmod_near(a, b):
4276 q, r = divmod(a, b)
4277 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4278 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4279 # positive, 2 * r < b if b negative.
4280 greater_than_half = 2*r > b if b > 0 else 2*r < b
4281 exactly_half = 2*r == b
4282 if greater_than_half or exactly_half and q % 2 == 1:
4283 q += 1
4284 r -= b
4285 return q, r
4286
4287 */
4288 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4289 PyErr_SetString(PyExc_TypeError,
4290 "non-integer arguments in division");
4291 return NULL;
4292 }
4293
4294 /* Do a and b have different signs? If so, quotient is negative. */
4295 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4296
4297 one = PyLong_FromLong(1L);
4298 if (one == NULL)
4299 return NULL;
4300
4301 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4302 goto error;
4303
4304 /* compare twice the remainder with the divisor, to see
4305 if we need to adjust the quotient and remainder */
4306 twice_rem = long_lshift((PyObject *)rem, one);
4307 if (twice_rem == NULL)
4308 goto error;
4309 if (quo_is_neg) {
4310 temp = long_neg((PyLongObject*)twice_rem);
4311 Py_DECREF(twice_rem);
4312 twice_rem = temp;
4313 if (twice_rem == NULL)
4314 goto error;
4315 }
4316 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4317 Py_DECREF(twice_rem);
4318
4319 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4320 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4321 /* fix up quotient */
4322 if (quo_is_neg)
4323 temp = long_sub(quo, (PyLongObject *)one);
4324 else
4325 temp = long_add(quo, (PyLongObject *)one);
4326 Py_DECREF(quo);
4327 quo = (PyLongObject *)temp;
4328 if (quo == NULL)
4329 goto error;
4330 /* and remainder */
4331 if (quo_is_neg)
4332 temp = long_add(rem, (PyLongObject *)b);
4333 else
4334 temp = long_sub(rem, (PyLongObject *)b);
4335 Py_DECREF(rem);
4336 rem = (PyLongObject *)temp;
4337 if (rem == NULL)
4338 goto error;
4339 }
4340
4341 result = PyTuple_New(2);
4342 if (result == NULL)
4343 goto error;
4344
4345 /* PyTuple_SET_ITEM steals references */
4346 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4347 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4348 Py_DECREF(one);
4349 return result;
4350
4351 error:
4352 Py_XDECREF(quo);
4353 Py_XDECREF(rem);
4354 Py_XDECREF(one);
4355 return NULL;
4356}
4357
Eric Smith8c663262007-08-25 02:26:07 +00004358static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004359long_round(PyObject *self, PyObject *args)
4360{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004361 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004362
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004363 /* To round an integer m to the nearest 10**n (n positive), we make use of
4364 * the divmod_near operation, defined by:
4365 *
4366 * divmod_near(a, b) = (q, r)
4367 *
4368 * where q is the nearest integer to the quotient a / b (the
4369 * nearest even integer in the case of a tie) and r == a - q * b.
4370 * Hence q * b = a - r is the nearest multiple of b to a,
4371 * preferring even multiples in the case of a tie.
4372 *
4373 * So the nearest multiple of 10**n to m is:
4374 *
4375 * m - divmod_near(m, 10**n)[1].
4376 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4378 return NULL;
4379 if (o_ndigits == NULL)
4380 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004381
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004382 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 if (ndigits == NULL)
4384 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004385
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004386 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 if (Py_SIZE(ndigits) >= 0) {
4388 Py_DECREF(ndigits);
4389 return long_long(self);
4390 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004391
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004392 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4393 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004395 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004397 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004398
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004399 result = PyLong_FromLong(10L);
4400 if (result == NULL) {
4401 Py_DECREF(ndigits);
4402 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004404
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004405 temp = long_pow(result, ndigits, Py_None);
4406 Py_DECREF(ndigits);
4407 Py_DECREF(result);
4408 result = temp;
4409 if (result == NULL)
4410 return NULL;
4411
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004412 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004413 Py_DECREF(result);
4414 result = temp;
4415 if (result == NULL)
4416 return NULL;
4417
4418 temp = long_sub((PyLongObject *)self,
4419 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4420 Py_DECREF(result);
4421 result = temp;
4422
4423 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004424}
4425
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004426static PyObject *
4427long_sizeof(PyLongObject *v)
4428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4432 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004433}
4434
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004435static PyObject *
4436long_bit_length(PyLongObject *v)
4437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 PyLongObject *result, *x, *y;
4439 Py_ssize_t ndigits, msd_bits = 0;
4440 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 assert(v != NULL);
4443 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 ndigits = ABS(Py_SIZE(v));
4446 if (ndigits == 0)
4447 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004449 msd = v->ob_digit[ndigits-1];
4450 while (msd >= 32) {
4451 msd_bits += 6;
4452 msd >>= 6;
4453 }
4454 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4457 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 /* expression above may overflow; use Python integers instead */
4460 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4461 if (result == NULL)
4462 return NULL;
4463 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4464 if (x == NULL)
4465 goto error;
4466 y = (PyLongObject *)long_mul(result, x);
4467 Py_DECREF(x);
4468 if (y == NULL)
4469 goto error;
4470 Py_DECREF(result);
4471 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4474 if (x == NULL)
4475 goto error;
4476 y = (PyLongObject *)long_add(result, x);
4477 Py_DECREF(x);
4478 if (y == NULL)
4479 goto error;
4480 Py_DECREF(result);
4481 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004484
Mark Dickinson22b20182010-05-10 21:27:53 +00004485 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 Py_DECREF(result);
4487 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004488}
4489
4490PyDoc_STRVAR(long_bit_length_doc,
4491"int.bit_length() -> int\n\
4492\n\
4493Number of bits necessary to represent self in binary.\n\
4494>>> bin(37)\n\
4495'0b100101'\n\
4496>>> (37).bit_length()\n\
44976");
4498
Christian Heimes53876d92008-04-19 00:31:39 +00004499#if 0
4500static PyObject *
4501long_is_finite(PyObject *v)
4502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004504}
4505#endif
4506
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004507
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004508static PyObject *
4509long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004511 PyObject *byteorder_str;
4512 PyObject *is_signed_obj = NULL;
4513 Py_ssize_t length;
4514 int little_endian;
4515 int is_signed;
4516 PyObject *bytes;
4517 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004519 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4520 &length, &byteorder_str,
4521 &is_signed_obj))
4522 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 if (args != NULL && Py_SIZE(args) > 2) {
4525 PyErr_SetString(PyExc_TypeError,
4526 "'signed' is a keyword-only argument");
4527 return NULL;
4528 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4531 little_endian = 1;
4532 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4533 little_endian = 0;
4534 else {
4535 PyErr_SetString(PyExc_ValueError,
4536 "byteorder must be either 'little' or 'big'");
4537 return NULL;
4538 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 if (is_signed_obj != NULL) {
4541 int cmp = PyObject_IsTrue(is_signed_obj);
4542 if (cmp < 0)
4543 return NULL;
4544 is_signed = cmp ? 1 : 0;
4545 }
4546 else {
4547 /* If the signed argument was omitted, use False as the
4548 default. */
4549 is_signed = 0;
4550 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 if (length < 0) {
4553 PyErr_SetString(PyExc_ValueError,
4554 "length argument must be non-negative");
4555 return NULL;
4556 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558 bytes = PyBytes_FromStringAndSize(NULL, length);
4559 if (bytes == NULL)
4560 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4563 length, little_endian, is_signed) < 0) {
4564 Py_DECREF(bytes);
4565 return NULL;
4566 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004568 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004569}
4570
Mark Dickinson078c2532010-01-30 18:06:17 +00004571PyDoc_STRVAR(long_to_bytes_doc,
4572"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004573\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004574Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004575\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004577raised if the integer is not representable with the given number of\n\
4578bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004579\n\
4580The byteorder argument determines the byte order used to represent the\n\
4581integer. If byteorder is 'big', the most significant byte is at the\n\
4582beginning of the byte array. If byteorder is 'little', the most\n\
4583significant byte is at the end of the byte array. To request the native\n\
4584byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4585\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004586The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004588is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004589
4590static PyObject *
4591long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004593 PyObject *byteorder_str;
4594 PyObject *is_signed_obj = NULL;
4595 int little_endian;
4596 int is_signed;
4597 PyObject *obj;
4598 PyObject *bytes;
4599 PyObject *long_obj;
4600 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004602 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4603 &obj, &byteorder_str,
4604 &is_signed_obj))
4605 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 if (args != NULL && Py_SIZE(args) > 2) {
4608 PyErr_SetString(PyExc_TypeError,
4609 "'signed' is a keyword-only argument");
4610 return NULL;
4611 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4614 little_endian = 1;
4615 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4616 little_endian = 0;
4617 else {
4618 PyErr_SetString(PyExc_ValueError,
4619 "byteorder must be either 'little' or 'big'");
4620 return NULL;
4621 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004623 if (is_signed_obj != NULL) {
4624 int cmp = PyObject_IsTrue(is_signed_obj);
4625 if (cmp < 0)
4626 return NULL;
4627 is_signed = cmp ? 1 : 0;
4628 }
4629 else {
4630 /* If the signed argument was omitted, use False as the
4631 default. */
4632 is_signed = 0;
4633 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 bytes = PyObject_Bytes(obj);
4636 if (bytes == NULL)
4637 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 long_obj = _PyLong_FromByteArray(
4640 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4641 little_endian, is_signed);
4642 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 /* If from_bytes() was used on subclass, allocate new subclass
4645 * instance, initialize it with decoded long value and return it.
4646 */
4647 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4648 PyLongObject *newobj;
4649 int i;
4650 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 newobj = (PyLongObject *)type->tp_alloc(type, n);
4653 if (newobj == NULL) {
4654 Py_DECREF(long_obj);
4655 return NULL;
4656 }
4657 assert(PyLong_Check(newobj));
4658 Py_SIZE(newobj) = Py_SIZE(long_obj);
4659 for (i = 0; i < n; i++) {
4660 newobj->ob_digit[i] =
4661 ((PyLongObject *)long_obj)->ob_digit[i];
4662 }
4663 Py_DECREF(long_obj);
4664 return (PyObject *)newobj;
4665 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004668}
4669
Mark Dickinson078c2532010-01-30 18:06:17 +00004670PyDoc_STRVAR(long_from_bytes_doc,
4671"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4672\n\
4673Return the integer represented by the given array of bytes.\n\
4674\n\
4675The bytes argument must either support the buffer protocol or be an\n\
4676iterable object producing bytes. Bytes and bytearray are examples of\n\
4677built-in objects that support the buffer protocol.\n\
4678\n\
4679The byteorder argument determines the byte order used to represent the\n\
4680integer. If byteorder is 'big', the most significant byte is at the\n\
4681beginning of the byte array. If byteorder is 'little', the most\n\
4682significant byte is at the end of the byte array. To request the native\n\
4683byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4684\n\
4685The signed keyword-only argument indicates whether two's complement is\n\
4686used to represent the integer.");
4687
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004688static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4690 "Returns self, the complex conjugate of any int."},
4691 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4692 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004693#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4695 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004696#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 {"to_bytes", (PyCFunction)long_to_bytes,
4698 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4699 {"from_bytes", (PyCFunction)long_from_bytes,
4700 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4701 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4702 "Truncating an Integral returns itself."},
4703 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4704 "Flooring an Integral returns itself."},
4705 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4706 "Ceiling of an Integral returns itself."},
4707 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4708 "Rounding an Integral returns itself.\n"
4709 "Rounding with an ndigits argument also returns an integer."},
4710 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4711 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4712 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4713 "Returns size in memory, in bytes"},
4714 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004715};
4716
Guido van Rossumb43daf72007-08-01 18:08:08 +00004717static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004718 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004719 (getter)long_long, (setter)NULL,
4720 "the real part of a complex number",
4721 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004722 {"imag",
4723 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004724 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004725 NULL},
4726 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004727 (getter)long_long, (setter)NULL,
4728 "the numerator of a rational number in lowest terms",
4729 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004730 {"denominator",
4731 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004732 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004733 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004734 {NULL} /* Sentinel */
4735};
4736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004737PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004738"int(x=0) -> integer\n\
4739int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004740\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004741Convert a number or string to an integer, or return 0 if no arguments\n\
4742are given. If x is a number, return x.__int__(). For floating point\n\
4743numbers, this truncates towards zero.\n\
4744\n\
4745If x is not a number or if base is given, then x must be a string,\n\
4746bytes, or bytearray instance representing an integer literal in the\n\
4747given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4748by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4749Base 0 means to interpret the base from the string as an integer literal.\n\
4750>>> int('0b100', base=0)\n\
47514");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004752
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004753static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004754 (binaryfunc)long_add, /*nb_add*/
4755 (binaryfunc)long_sub, /*nb_subtract*/
4756 (binaryfunc)long_mul, /*nb_multiply*/
4757 long_mod, /*nb_remainder*/
4758 long_divmod, /*nb_divmod*/
4759 long_pow, /*nb_power*/
4760 (unaryfunc)long_neg, /*nb_negative*/
4761 (unaryfunc)long_long, /*tp_positive*/
4762 (unaryfunc)long_abs, /*tp_absolute*/
4763 (inquiry)long_bool, /*tp_bool*/
4764 (unaryfunc)long_invert, /*nb_invert*/
4765 long_lshift, /*nb_lshift*/
4766 (binaryfunc)long_rshift, /*nb_rshift*/
4767 long_and, /*nb_and*/
4768 long_xor, /*nb_xor*/
4769 long_or, /*nb_or*/
4770 long_long, /*nb_int*/
4771 0, /*nb_reserved*/
4772 long_float, /*nb_float*/
4773 0, /* nb_inplace_add */
4774 0, /* nb_inplace_subtract */
4775 0, /* nb_inplace_multiply */
4776 0, /* nb_inplace_remainder */
4777 0, /* nb_inplace_power */
4778 0, /* nb_inplace_lshift */
4779 0, /* nb_inplace_rshift */
4780 0, /* nb_inplace_and */
4781 0, /* nb_inplace_xor */
4782 0, /* nb_inplace_or */
4783 long_div, /* nb_floor_divide */
4784 long_true_divide, /* nb_true_divide */
4785 0, /* nb_inplace_floor_divide */
4786 0, /* nb_inplace_true_divide */
4787 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004788};
4789
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004790PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4792 "int", /* tp_name */
4793 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4794 sizeof(digit), /* tp_itemsize */
4795 long_dealloc, /* tp_dealloc */
4796 0, /* tp_print */
4797 0, /* tp_getattr */
4798 0, /* tp_setattr */
4799 0, /* tp_reserved */
4800 long_to_decimal_string, /* tp_repr */
4801 &long_as_number, /* tp_as_number */
4802 0, /* tp_as_sequence */
4803 0, /* tp_as_mapping */
4804 (hashfunc)long_hash, /* tp_hash */
4805 0, /* tp_call */
4806 long_to_decimal_string, /* tp_str */
4807 PyObject_GenericGetAttr, /* tp_getattro */
4808 0, /* tp_setattro */
4809 0, /* tp_as_buffer */
4810 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4811 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4812 long_doc, /* tp_doc */
4813 0, /* tp_traverse */
4814 0, /* tp_clear */
4815 long_richcompare, /* tp_richcompare */
4816 0, /* tp_weaklistoffset */
4817 0, /* tp_iter */
4818 0, /* tp_iternext */
4819 long_methods, /* tp_methods */
4820 0, /* tp_members */
4821 long_getset, /* tp_getset */
4822 0, /* tp_base */
4823 0, /* tp_dict */
4824 0, /* tp_descr_get */
4825 0, /* tp_descr_set */
4826 0, /* tp_dictoffset */
4827 0, /* tp_init */
4828 0, /* tp_alloc */
4829 long_new, /* tp_new */
4830 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004831};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004832
Mark Dickinsonbd792642009-03-18 20:06:12 +00004833static PyTypeObject Int_InfoType;
4834
4835PyDoc_STRVAR(int_info__doc__,
4836"sys.int_info\n\
4837\n\
4838A struct sequence that holds information about Python's\n\
4839internal representation of integers. The attributes are read only.");
4840
4841static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004843 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004845};
4846
4847static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 "sys.int_info", /* name */
4849 int_info__doc__, /* doc */
4850 int_info_fields, /* fields */
4851 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004852};
4853
4854PyObject *
4855PyLong_GetInfo(void)
4856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004857 PyObject* int_info;
4858 int field = 0;
4859 int_info = PyStructSequence_New(&Int_InfoType);
4860 if (int_info == NULL)
4861 return NULL;
4862 PyStructSequence_SET_ITEM(int_info, field++,
4863 PyLong_FromLong(PyLong_SHIFT));
4864 PyStructSequence_SET_ITEM(int_info, field++,
4865 PyLong_FromLong(sizeof(digit)));
4866 if (PyErr_Occurred()) {
4867 Py_CLEAR(int_info);
4868 return NULL;
4869 }
4870 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004871}
4872
Guido van Rossumddefaf32007-01-14 03:31:43 +00004873int
4874_PyLong_Init(void)
4875{
4876#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 int ival, size;
4878 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004880 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4881 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4882 if (Py_TYPE(v) == &PyLong_Type) {
4883 /* The element is already initialized, most likely
4884 * the Python interpreter was initialized before.
4885 */
4886 Py_ssize_t refcnt;
4887 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4890 _Py_NewReference(op);
4891 /* _Py_NewReference sets the ref count to 1 but
4892 * the ref count might be larger. Set the refcnt
4893 * to the original refcnt + 1 */
4894 Py_REFCNT(op) = refcnt + 1;
4895 assert(Py_SIZE(op) == size);
4896 assert(v->ob_digit[0] == abs(ival));
4897 }
4898 else {
4899 PyObject_INIT(v, &PyLong_Type);
4900 }
4901 Py_SIZE(v) = size;
4902 v->ob_digit[0] = abs(ival);
4903 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004904#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004905 /* initialize int_info */
4906 if (Int_InfoType.tp_name == 0)
4907 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004910}
4911
4912void
4913PyLong_Fini(void)
4914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 /* Integers are currently statically allocated. Py_DECREF is not
4916 needed, but Python must forget about the reference or multiple
4917 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004918#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004919 int i;
4920 PyLongObject *v = small_ints;
4921 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4922 _Py_DEC_REFTOTAL;
4923 _Py_ForgetReference((PyObject*)v);
4924 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004925#endif
4926}