blob: 51da32955e60db1da50fa8fc357a5f03a1f40a67 [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
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000427/* Get a Py_ssize_t from a long int object.
428 Returns -1 and sets an error condition if overflow occurs. */
429
430Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000431PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 register PyLongObject *v;
433 size_t x, prev;
434 Py_ssize_t i;
435 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (vv == NULL) {
438 PyErr_BadInternalCall();
439 return -1;
440 }
441 if (!PyLong_Check(vv)) {
442 PyErr_SetString(PyExc_TypeError, "an integer is required");
443 return -1;
444 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 v = (PyLongObject *)vv;
447 i = Py_SIZE(v);
448 switch (i) {
449 case -1: return -(sdigit)v->ob_digit[0];
450 case 0: return 0;
451 case 1: return v->ob_digit[0];
452 }
453 sign = 1;
454 x = 0;
455 if (i < 0) {
456 sign = -1;
457 i = -(i);
458 }
459 while (--i >= 0) {
460 prev = x;
461 x = (x << PyLong_SHIFT) | v->ob_digit[i];
462 if ((x >> PyLong_SHIFT) != prev)
463 goto overflow;
464 }
465 /* Haven't lost any bits, but casting to a signed type requires
466 * extra care (see comment above).
467 */
468 if (x <= (size_t)PY_SSIZE_T_MAX) {
469 return (Py_ssize_t)x * sign;
470 }
471 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
472 return PY_SSIZE_T_MIN;
473 }
474 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000475
Mark Dickinson22b20182010-05-10 21:27:53 +0000476 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyErr_SetString(PyExc_OverflowError,
478 "Python int too large to convert to C ssize_t");
479 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000480}
481
Guido van Rossumd8c80482002-08-13 00:24:58 +0000482/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000483 Returns -1 and sets an error condition if overflow occurs. */
484
485unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000486PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 register PyLongObject *v;
489 unsigned long x, prev;
490 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (vv == NULL) {
493 PyErr_BadInternalCall();
494 return (unsigned long)-1;
495 }
496 if (!PyLong_Check(vv)) {
497 PyErr_SetString(PyExc_TypeError, "an integer is required");
498 return (unsigned long)-1;
499 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 v = (PyLongObject *)vv;
502 i = Py_SIZE(v);
503 x = 0;
504 if (i < 0) {
505 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000506 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 return (unsigned long) -1;
508 }
509 switch (i) {
510 case 0: return 0;
511 case 1: return v->ob_digit[0];
512 }
513 while (--i >= 0) {
514 prev = x;
515 x = (x << PyLong_SHIFT) | v->ob_digit[i];
516 if ((x >> PyLong_SHIFT) != prev) {
517 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000518 "python int too large to convert "
519 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return (unsigned long) -1;
521 }
522 }
523 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000524}
525
Stefan Krahb77c6c62011-09-12 16:22:47 +0200526/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
527 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000528
529size_t
530PyLong_AsSize_t(PyObject *vv)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 register PyLongObject *v;
533 size_t x, prev;
534 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (vv == NULL) {
537 PyErr_BadInternalCall();
538 return (size_t) -1;
539 }
540 if (!PyLong_Check(vv)) {
541 PyErr_SetString(PyExc_TypeError, "an integer is required");
542 return (size_t)-1;
543 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 v = (PyLongObject *)vv;
546 i = Py_SIZE(v);
547 x = 0;
548 if (i < 0) {
549 PyErr_SetString(PyExc_OverflowError,
550 "can't convert negative value to size_t");
551 return (size_t) -1;
552 }
553 switch (i) {
554 case 0: return 0;
555 case 1: return v->ob_digit[0];
556 }
557 while (--i >= 0) {
558 prev = x;
559 x = (x << PyLong_SHIFT) | v->ob_digit[i];
560 if ((x >> PyLong_SHIFT) != prev) {
561 PyErr_SetString(PyExc_OverflowError,
562 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200563 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
565 }
566 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000567}
568
Thomas Hellera4ea6032003-04-17 18:55:45 +0000569/* Get a C unsigned long int from a long int object, ignoring the high bits.
570 Returns -1 and sets an error condition if an error occurs. */
571
Guido van Rossumddefaf32007-01-14 03:31:43 +0000572static unsigned long
573_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 register PyLongObject *v;
576 unsigned long x;
577 Py_ssize_t i;
578 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (vv == NULL || !PyLong_Check(vv)) {
581 PyErr_BadInternalCall();
582 return (unsigned long) -1;
583 }
584 v = (PyLongObject *)vv;
585 i = Py_SIZE(v);
586 switch (i) {
587 case 0: return 0;
588 case 1: return v->ob_digit[0];
589 }
590 sign = 1;
591 x = 0;
592 if (i < 0) {
593 sign = -1;
594 i = -i;
595 }
596 while (--i >= 0) {
597 x = (x << PyLong_SHIFT) | v->ob_digit[i];
598 }
599 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000600}
601
Guido van Rossumddefaf32007-01-14 03:31:43 +0000602unsigned long
603PyLong_AsUnsignedLongMask(register PyObject *op)
604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 PyNumberMethods *nb;
606 PyLongObject *lo;
607 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (op && PyLong_Check(op))
610 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
613 nb->nb_int == NULL) {
614 PyErr_SetString(PyExc_TypeError, "an integer is required");
615 return (unsigned long)-1;
616 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 lo = (PyLongObject*) (*nb->nb_int) (op);
619 if (lo == NULL)
620 return (unsigned long)-1;
621 if (PyLong_Check(lo)) {
622 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
623 Py_DECREF(lo);
624 if (PyErr_Occurred())
625 return (unsigned long)-1;
626 return val;
627 }
628 else
629 {
630 Py_DECREF(lo);
631 PyErr_SetString(PyExc_TypeError,
632 "nb_int should return int object");
633 return (unsigned long)-1;
634 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000635}
636
Tim Peters5b8132f2003-01-31 15:52:05 +0000637int
638_PyLong_Sign(PyObject *vv)
639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 assert(v != NULL);
643 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000646}
647
Tim Petersbaefd9e2003-01-28 20:37:45 +0000648size_t
649_PyLong_NumBits(PyObject *vv)
650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyLongObject *v = (PyLongObject *)vv;
652 size_t result = 0;
653 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 assert(v != NULL);
656 assert(PyLong_Check(v));
657 ndigits = ABS(Py_SIZE(v));
658 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
659 if (ndigits > 0) {
660 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 result = (ndigits - 1) * PyLong_SHIFT;
663 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
664 goto Overflow;
665 do {
666 ++result;
667 if (result == 0)
668 goto Overflow;
669 msd >>= 1;
670 } while (msd);
671 }
672 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000673
Mark Dickinson22b20182010-05-10 21:27:53 +0000674 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
676 "to express in a platform size_t");
677 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000678}
679
Tim Peters2a9b3672001-06-11 21:23:58 +0000680PyObject *
681_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000683{
Mark Dickinson22b20182010-05-10 21:27:53 +0000684 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 int incr; /* direction to move pstartbyte */
686 const unsigned char* pendbyte; /* MSB of bytes */
687 size_t numsignificantbytes; /* number of bytes that matter */
688 Py_ssize_t ndigits; /* number of Python long digits */
689 PyLongObject* v; /* result */
690 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (n == 0)
693 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (little_endian) {
696 pstartbyte = bytes;
697 pendbyte = bytes + n - 1;
698 incr = 1;
699 }
700 else {
701 pstartbyte = bytes + n - 1;
702 pendbyte = bytes;
703 incr = -1;
704 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (is_signed)
707 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200710 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 is positive, and leading 0xff bytes if negative. */
712 {
713 size_t i;
714 const unsigned char* p = pendbyte;
715 const int pincr = -incr; /* search MSB to LSB */
716 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 for (i = 0; i < n; ++i, p += pincr) {
719 if (*p != insignficant)
720 break;
721 }
722 numsignificantbytes = n - i;
723 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
724 actually has 2 significant bytes. OTOH, 0xff0001 ==
725 -0x00ffff, so we wouldn't *need* to bump it there; but we
726 do for 0xffff = -0x0001. To be safe without bothering to
727 check every case, bump it regardless. */
728 if (is_signed && numsignificantbytes < n)
729 ++numsignificantbytes;
730 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 /* How many Python long digits do we need? We have
733 8*numsignificantbytes bits, and each Python long digit has
734 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
735 /* catch overflow before it happens */
736 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
737 PyErr_SetString(PyExc_OverflowError,
738 "byte array too long to convert to int");
739 return NULL;
740 }
741 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
742 v = _PyLong_New(ndigits);
743 if (v == NULL)
744 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 /* Copy the bits over. The tricky parts are computing 2's-comp on
747 the fly for signed numbers, and dealing with the mismatch between
748 8-bit bytes and (probably) 15-bit Python digits.*/
749 {
750 size_t i;
751 twodigits carry = 1; /* for 2's-comp calculation */
752 twodigits accum = 0; /* sliding register */
753 unsigned int accumbits = 0; /* number of bits in accum */
754 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
757 twodigits thisbyte = *p;
758 /* Compute correction for 2's comp, if needed. */
759 if (is_signed) {
760 thisbyte = (0xff ^ thisbyte) + carry;
761 carry = thisbyte >> 8;
762 thisbyte &= 0xff;
763 }
764 /* Because we're going LSB to MSB, thisbyte is
765 more significant than what's already in accum,
766 so needs to be prepended to accum. */
767 accum |= (twodigits)thisbyte << accumbits;
768 accumbits += 8;
769 if (accumbits >= PyLong_SHIFT) {
770 /* There's enough to fill a Python digit. */
771 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000772 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 ++idigit;
774 accum >>= PyLong_SHIFT;
775 accumbits -= PyLong_SHIFT;
776 assert(accumbits < PyLong_SHIFT);
777 }
778 }
779 assert(accumbits < PyLong_SHIFT);
780 if (accumbits) {
781 assert(idigit < ndigits);
782 v->ob_digit[idigit] = (digit)accum;
783 ++idigit;
784 }
785 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_SIZE(v) = is_signed ? -idigit : idigit;
788 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000789}
790
791int
792_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 unsigned char* bytes, size_t n,
794 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000797 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000799 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
801 digit carry; /* for computing 2's-comp */
802 size_t j; /* # bytes filled */
803 unsigned char* p; /* pointer to next byte in bytes */
804 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 if (Py_SIZE(v) < 0) {
809 ndigits = -(Py_SIZE(v));
810 if (!is_signed) {
811 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000812 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return -1;
814 }
815 do_twos_comp = 1;
816 }
817 else {
818 ndigits = Py_SIZE(v);
819 do_twos_comp = 0;
820 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 if (little_endian) {
823 p = bytes;
824 pincr = 1;
825 }
826 else {
827 p = bytes + n - 1;
828 pincr = -1;
829 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Copy over all the Python digits.
832 It's crucial that every Python digit except for the MSD contribute
833 exactly PyLong_SHIFT bits to the total, so first assert that the long is
834 normalized. */
835 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
836 j = 0;
837 accum = 0;
838 accumbits = 0;
839 carry = do_twos_comp ? 1 : 0;
840 for (i = 0; i < ndigits; ++i) {
841 digit thisdigit = v->ob_digit[i];
842 if (do_twos_comp) {
843 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
844 carry = thisdigit >> PyLong_SHIFT;
845 thisdigit &= PyLong_MASK;
846 }
847 /* Because we're going LSB to MSB, thisdigit is more
848 significant than what's already in accum, so needs to be
849 prepended to accum. */
850 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 /* The most-significant digit may be (probably is) at least
853 partly empty. */
854 if (i == ndigits - 1) {
855 /* Count # of sign bits -- they needn't be stored,
856 * although for signed conversion we need later to
857 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000858 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 while (s != 0) {
860 s >>= 1;
861 accumbits++;
862 }
863 }
864 else
865 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Store as many bytes as possible. */
868 while (accumbits >= 8) {
869 if (j >= n)
870 goto Overflow;
871 ++j;
872 *p = (unsigned char)(accum & 0xff);
873 p += pincr;
874 accumbits -= 8;
875 accum >>= 8;
876 }
877 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Store the straggler (if any). */
880 assert(accumbits < 8);
881 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
882 if (accumbits > 0) {
883 if (j >= n)
884 goto Overflow;
885 ++j;
886 if (do_twos_comp) {
887 /* Fill leading bits of the byte with sign bits
888 (appropriately pretending that the long had an
889 infinite supply of sign bits). */
890 accum |= (~(twodigits)0) << accumbits;
891 }
892 *p = (unsigned char)(accum & 0xff);
893 p += pincr;
894 }
895 else if (j == n && n > 0 && is_signed) {
896 /* The main loop filled the byte array exactly, so the code
897 just above didn't get to ensure there's a sign bit, and the
898 loop below wouldn't add one either. Make sure a sign bit
899 exists. */
900 unsigned char msb = *(p - pincr);
901 int sign_bit_set = msb >= 0x80;
902 assert(accumbits == 0);
903 if (sign_bit_set == do_twos_comp)
904 return 0;
905 else
906 goto Overflow;
907 }
Tim Peters05607ad2001-06-13 21:01:27 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* Fill remaining bytes with copies of the sign bit. */
910 {
911 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
912 for ( ; j < n; ++j, p += pincr)
913 *p = signbyte;
914 }
Tim Peters05607ad2001-06-13 21:01:27 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000917
Mark Dickinson22b20182010-05-10 21:27:53 +0000918 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
920 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000921
Tim Peters2a9b3672001-06-11 21:23:58 +0000922}
923
Guido van Rossum78694d91998-09-18 14:14:13 +0000924/* Create a new long (or int) object from a C pointer */
925
926PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000927PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000928{
Mark Dickinson91044792012-10-18 19:21:43 +0100929#if SIZEOF_VOID_P <= SIZEOF_LONG
930 /* special-case null pointer */
931 if (!p)
932 return PyLong_FromLong(0);
933 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
934#else
935
Tim Peters70128a12001-06-16 08:48:40 +0000936#ifndef HAVE_LONG_LONG
937# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
938#endif
939#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000940# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000941#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* special-case null pointer */
943 if (!p)
944 return PyLong_FromLong(0);
945 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100946#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000947
Guido van Rossum78694d91998-09-18 14:14:13 +0000948}
949
950/* Get a C pointer from a long object (or an int object in some cases) */
951
952void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000953PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* This function will allow int or long objects. If vv is neither,
956 then the PyLong_AsLong*() functions will raise the exception:
957 PyExc_SystemError, "bad argument to internal function"
958 */
Tim Peters70128a12001-06-16 08:48:40 +0000959#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
963 x = PyLong_AsLong(vv);
964 else
965 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000966#else
Tim Peters70128a12001-06-16 08:48:40 +0000967
968#ifndef HAVE_LONG_LONG
969# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
970#endif
971#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000972# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
977 x = PyLong_AsLongLong(vv);
978 else
979 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000980
981#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (x == -1 && PyErr_Occurred())
984 return NULL;
985 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000986}
987
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000988#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000989
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000990/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000991 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000992 */
993
Tim Peterscf37dfc2001-06-14 18:42:50 +0000994#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000995#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000996
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000997/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000998
999PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001000PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyLongObject *v;
1003 unsigned PY_LONG_LONG abs_ival;
1004 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1005 int ndigits = 0;
1006 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 CHECK_SMALL_INT(ival);
1009 if (ival < 0) {
1010 /* avoid signed overflow on negation; see comments
1011 in PyLong_FromLong above. */
1012 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1013 negative = 1;
1014 }
1015 else {
1016 abs_ival = (unsigned PY_LONG_LONG)ival;
1017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 /* Count the number of Python digits.
1020 We used to pick 5 ("big enough for anything"), but that's a
1021 waste of time and space given that 5*15 = 75 bits are rarely
1022 needed. */
1023 t = abs_ival;
1024 while (t) {
1025 ++ndigits;
1026 t >>= PyLong_SHIFT;
1027 }
1028 v = _PyLong_New(ndigits);
1029 if (v != NULL) {
1030 digit *p = v->ob_digit;
1031 Py_SIZE(v) = negative ? -ndigits : ndigits;
1032 t = abs_ival;
1033 while (t) {
1034 *p++ = (digit)(t & PyLong_MASK);
1035 t >>= PyLong_SHIFT;
1036 }
1037 }
1038 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039}
1040
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001042
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001044PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 PyLongObject *v;
1047 unsigned PY_LONG_LONG t;
1048 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (ival < PyLong_BASE)
1051 return PyLong_FromLong((long)ival);
1052 /* Count the number of Python digits. */
1053 t = (unsigned PY_LONG_LONG)ival;
1054 while (t) {
1055 ++ndigits;
1056 t >>= PyLong_SHIFT;
1057 }
1058 v = _PyLong_New(ndigits);
1059 if (v != NULL) {
1060 digit *p = v->ob_digit;
1061 Py_SIZE(v) = ndigits;
1062 while (ival) {
1063 *p++ = (digit)(ival & PyLong_MASK);
1064 ival >>= PyLong_SHIFT;
1065 }
1066 }
1067 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001068}
1069
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070/* Create a new long int object from a C Py_ssize_t. */
1071
1072PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001073PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyLongObject *v;
1076 size_t abs_ival;
1077 size_t t; /* unsigned so >> doesn't propagate sign bit */
1078 int ndigits = 0;
1079 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 CHECK_SMALL_INT(ival);
1082 if (ival < 0) {
1083 /* avoid signed overflow when ival = SIZE_T_MIN */
1084 abs_ival = (size_t)(-1-ival)+1;
1085 negative = 1;
1086 }
1087 else {
1088 abs_ival = (size_t)ival;
1089 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 /* Count the number of Python digits. */
1092 t = abs_ival;
1093 while (t) {
1094 ++ndigits;
1095 t >>= PyLong_SHIFT;
1096 }
1097 v = _PyLong_New(ndigits);
1098 if (v != NULL) {
1099 digit *p = v->ob_digit;
1100 Py_SIZE(v) = negative ? -ndigits : ndigits;
1101 t = abs_ival;
1102 while (t) {
1103 *p++ = (digit)(t & PyLong_MASK);
1104 t >>= PyLong_SHIFT;
1105 }
1106 }
1107 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001108}
1109
1110/* Create a new long int object from a C size_t. */
1111
1112PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001113PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyLongObject *v;
1116 size_t t;
1117 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 if (ival < PyLong_BASE)
1120 return PyLong_FromLong((long)ival);
1121 /* Count the number of Python digits. */
1122 t = ival;
1123 while (t) {
1124 ++ndigits;
1125 t >>= PyLong_SHIFT;
1126 }
1127 v = _PyLong_New(ndigits);
1128 if (v != NULL) {
1129 digit *p = v->ob_digit;
1130 Py_SIZE(v) = ndigits;
1131 while (ival) {
1132 *p++ = (digit)(ival & PyLong_MASK);
1133 ival >>= PyLong_SHIFT;
1134 }
1135 }
1136 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137}
1138
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001139/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001140 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001142PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001143PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyLongObject *v;
1146 PY_LONG_LONG bytes;
1147 int one = 1;
1148 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (vv == NULL) {
1151 PyErr_BadInternalCall();
1152 return -1;
1153 }
1154 if (!PyLong_Check(vv)) {
1155 PyNumberMethods *nb;
1156 PyObject *io;
1157 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1158 nb->nb_int == NULL) {
1159 PyErr_SetString(PyExc_TypeError, "an integer is required");
1160 return -1;
1161 }
1162 io = (*nb->nb_int) (vv);
1163 if (io == NULL)
1164 return -1;
1165 if (PyLong_Check(io)) {
1166 bytes = PyLong_AsLongLong(io);
1167 Py_DECREF(io);
1168 return bytes;
1169 }
1170 Py_DECREF(io);
1171 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1172 return -1;
1173 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 v = (PyLongObject*)vv;
1176 switch(Py_SIZE(v)) {
1177 case -1: return -(sdigit)v->ob_digit[0];
1178 case 0: return 0;
1179 case 1: return v->ob_digit[0];
1180 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001181 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1182 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1185 if (res < 0)
1186 return (PY_LONG_LONG)-1;
1187 else
1188 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001189}
1190
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001191/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001192 Return -1 and set an error if overflow occurs. */
1193
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001194unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001195PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyLongObject *v;
1198 unsigned PY_LONG_LONG bytes;
1199 int one = 1;
1200 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (vv == NULL || !PyLong_Check(vv)) {
1203 PyErr_BadInternalCall();
1204 return (unsigned PY_LONG_LONG)-1;
1205 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 v = (PyLongObject*)vv;
1208 switch(Py_SIZE(v)) {
1209 case 0: return 0;
1210 case 1: return v->ob_digit[0];
1211 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001212
Mark Dickinson22b20182010-05-10 21:27:53 +00001213 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1214 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1217 if (res < 0)
1218 return (unsigned PY_LONG_LONG)res;
1219 else
1220 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001221}
Tim Petersd1a7da62001-06-13 00:35:57 +00001222
Thomas Hellera4ea6032003-04-17 18:55:45 +00001223/* Get a C unsigned long int from a long int object, ignoring the high bits.
1224 Returns -1 and sets an error condition if an error occurs. */
1225
Guido van Rossumddefaf32007-01-14 03:31:43 +00001226static unsigned PY_LONG_LONG
1227_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 register PyLongObject *v;
1230 unsigned PY_LONG_LONG x;
1231 Py_ssize_t i;
1232 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (vv == NULL || !PyLong_Check(vv)) {
1235 PyErr_BadInternalCall();
1236 return (unsigned long) -1;
1237 }
1238 v = (PyLongObject *)vv;
1239 switch(Py_SIZE(v)) {
1240 case 0: return 0;
1241 case 1: return v->ob_digit[0];
1242 }
1243 i = Py_SIZE(v);
1244 sign = 1;
1245 x = 0;
1246 if (i < 0) {
1247 sign = -1;
1248 i = -i;
1249 }
1250 while (--i >= 0) {
1251 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1252 }
1253 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001254}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001255
1256unsigned PY_LONG_LONG
1257PyLong_AsUnsignedLongLongMask(register PyObject *op)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 PyNumberMethods *nb;
1260 PyLongObject *lo;
1261 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (op && PyLong_Check(op))
1264 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1267 nb->nb_int == NULL) {
1268 PyErr_SetString(PyExc_TypeError, "an integer is required");
1269 return (unsigned PY_LONG_LONG)-1;
1270 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 lo = (PyLongObject*) (*nb->nb_int) (op);
1273 if (lo == NULL)
1274 return (unsigned PY_LONG_LONG)-1;
1275 if (PyLong_Check(lo)) {
1276 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1277 Py_DECREF(lo);
1278 if (PyErr_Occurred())
1279 return (unsigned PY_LONG_LONG)-1;
1280 return val;
1281 }
1282 else
1283 {
1284 Py_DECREF(lo);
1285 PyErr_SetString(PyExc_TypeError,
1286 "nb_int should return int object");
1287 return (unsigned PY_LONG_LONG)-1;
1288 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289}
Tim Petersd1a7da62001-06-13 00:35:57 +00001290#undef IS_LITTLE_ENDIAN
1291
Mark Dickinson93f562c2010-01-30 10:30:15 +00001292/* Get a C long long int from a Python long or Python int object.
1293 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1294 on the sign of the result. Otherwise *overflow is 0.
1295
1296 For other errors (e.g., type error), returns -1 and sets an error
1297 condition.
1298*/
1299
1300PY_LONG_LONG
1301PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 /* This version by Tim Peters */
1304 register PyLongObject *v;
1305 unsigned PY_LONG_LONG x, prev;
1306 PY_LONG_LONG res;
1307 Py_ssize_t i;
1308 int sign;
1309 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 *overflow = 0;
1312 if (vv == NULL) {
1313 PyErr_BadInternalCall();
1314 return -1;
1315 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (!PyLong_Check(vv)) {
1318 PyNumberMethods *nb;
1319 nb = vv->ob_type->tp_as_number;
1320 if (nb == NULL || nb->nb_int == NULL) {
1321 PyErr_SetString(PyExc_TypeError,
1322 "an integer is required");
1323 return -1;
1324 }
1325 vv = (*nb->nb_int) (vv);
1326 if (vv == NULL)
1327 return -1;
1328 do_decref = 1;
1329 if (!PyLong_Check(vv)) {
1330 Py_DECREF(vv);
1331 PyErr_SetString(PyExc_TypeError,
1332 "nb_int should return int object");
1333 return -1;
1334 }
1335 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 res = -1;
1338 v = (PyLongObject *)vv;
1339 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 switch (i) {
1342 case -1:
1343 res = -(sdigit)v->ob_digit[0];
1344 break;
1345 case 0:
1346 res = 0;
1347 break;
1348 case 1:
1349 res = v->ob_digit[0];
1350 break;
1351 default:
1352 sign = 1;
1353 x = 0;
1354 if (i < 0) {
1355 sign = -1;
1356 i = -(i);
1357 }
1358 while (--i >= 0) {
1359 prev = x;
1360 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1361 if ((x >> PyLong_SHIFT) != prev) {
1362 *overflow = sign;
1363 goto exit;
1364 }
1365 }
1366 /* Haven't lost any bits, but casting to long requires extra
1367 * care (see comment above).
1368 */
1369 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1370 res = (PY_LONG_LONG)x * sign;
1371 }
1372 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1373 res = PY_LLONG_MIN;
1374 }
1375 else {
1376 *overflow = sign;
1377 /* res is already set to -1 */
1378 }
1379 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001380 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (do_decref) {
1382 Py_DECREF(vv);
1383 }
1384 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001385}
1386
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001387#endif /* HAVE_LONG_LONG */
1388
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001389#define CHECK_BINOP(v,w) \
1390 do { \
1391 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1392 Py_INCREF(Py_NotImplemented); \
1393 return Py_NotImplemented; \
1394 } \
1395 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001396
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001397/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1398 2**k if d is nonzero, else 0. */
1399
1400static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1402 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001403};
1404
1405static int
1406bits_in_digit(digit d)
1407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 int d_bits = 0;
1409 while (d >= 32) {
1410 d_bits += 6;
1411 d >>= 6;
1412 }
1413 d_bits += (int)BitLengthTable[d];
1414 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001415}
1416
Tim Peters877a2122002-08-12 05:09:36 +00001417/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1418 * is modified in place, by adding y to it. Carries are propagated as far as
1419 * x[m-1], and the remaining carry (0 or 1) is returned.
1420 */
1421static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001422v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_ssize_t i;
1425 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 assert(m >= n);
1428 for (i = 0; i < n; ++i) {
1429 carry += x[i] + y[i];
1430 x[i] = carry & PyLong_MASK;
1431 carry >>= PyLong_SHIFT;
1432 assert((carry & 1) == carry);
1433 }
1434 for (; carry && i < m; ++i) {
1435 carry += x[i];
1436 x[i] = carry & PyLong_MASK;
1437 carry >>= PyLong_SHIFT;
1438 assert((carry & 1) == carry);
1439 }
1440 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001441}
1442
1443/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1444 * is modified in place, by subtracting y from it. Borrows are propagated as
1445 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1446 */
1447static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001448v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 Py_ssize_t i;
1451 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 assert(m >= n);
1454 for (i = 0; i < n; ++i) {
1455 borrow = x[i] - y[i] - borrow;
1456 x[i] = borrow & PyLong_MASK;
1457 borrow >>= PyLong_SHIFT;
1458 borrow &= 1; /* keep only 1 sign bit */
1459 }
1460 for (; borrow && i < m; ++i) {
1461 borrow = x[i] - borrow;
1462 x[i] = borrow & PyLong_MASK;
1463 borrow >>= PyLong_SHIFT;
1464 borrow &= 1;
1465 }
1466 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001467}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001468
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001469/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1470 * result in z[0:m], and return the d bits shifted out of the top.
1471 */
1472static digit
1473v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 Py_ssize_t i;
1476 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 assert(0 <= d && d < PyLong_SHIFT);
1479 for (i=0; i < m; i++) {
1480 twodigits acc = (twodigits)a[i] << d | carry;
1481 z[i] = (digit)acc & PyLong_MASK;
1482 carry = (digit)(acc >> PyLong_SHIFT);
1483 }
1484 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001485}
1486
1487/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1488 * result in z[0:m], and return the d bits shifted out of the bottom.
1489 */
1490static digit
1491v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 Py_ssize_t i;
1494 digit carry = 0;
1495 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 assert(0 <= d && d < PyLong_SHIFT);
1498 for (i=m; i-- > 0;) {
1499 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1500 carry = (digit)acc & mask;
1501 z[i] = (digit)(acc >> d);
1502 }
1503 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504}
1505
Tim Peters212e6142001-07-14 12:23:19 +00001506/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1507 in pout, and returning the remainder. pin and pout point at the LSD.
1508 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001509 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001510 immutable. */
1511
1512static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001513inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 assert(n > 0 && n <= PyLong_MASK);
1518 pin += size;
1519 pout += size;
1520 while (--size >= 0) {
1521 digit hi;
1522 rem = (rem << PyLong_SHIFT) | *--pin;
1523 *--pout = hi = (digit)(rem / n);
1524 rem -= (twodigits)hi * n;
1525 }
1526 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001527}
1528
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001529/* Divide a long integer by a digit, returning both the quotient
1530 (as function result) and the remainder (through *prem).
1531 The sign of a is ignored; n should not be zero. */
1532
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001533static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001534divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 const Py_ssize_t size = ABS(Py_SIZE(a));
1537 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 assert(n > 0 && n <= PyLong_MASK);
1540 z = _PyLong_New(size);
1541 if (z == NULL)
1542 return NULL;
1543 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1544 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001545}
1546
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001547/* Convert a long integer to a base 10 string. Returns a new non-shared
1548 string. (Return value is non-shared so that callers can modify the
1549 returned value if necessary.) */
1550
1551static PyObject *
1552long_to_decimal_string(PyObject *aa)
1553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PyLongObject *scratch, *a;
1555 PyObject *str;
1556 Py_ssize_t size, strlen, size_a, i, j;
1557 digit *pout, *pin, rem, tenpow;
1558 Py_UNICODE *p;
1559 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 a = (PyLongObject *)aa;
1562 if (a == NULL || !PyLong_Check(a)) {
1563 PyErr_BadInternalCall();
1564 return NULL;
1565 }
1566 size_a = ABS(Py_SIZE(a));
1567 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 /* quick and dirty upper bound for the number of digits
1570 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 But log2(a) < size_a * PyLong_SHIFT, and
1575 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1576 > 3 * _PyLong_DECIMAL_SHIFT
1577 */
1578 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1579 PyErr_SetString(PyExc_OverflowError,
1580 "long is too large to format");
1581 return NULL;
1582 }
1583 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1584 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1585 scratch = _PyLong_New(size);
1586 if (scratch == NULL)
1587 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 /* convert array of base _PyLong_BASE digits in pin to an array of
1590 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1591 Volume 2 (3rd edn), section 4.4, Method 1b). */
1592 pin = a->ob_digit;
1593 pout = scratch->ob_digit;
1594 size = 0;
1595 for (i = size_a; --i >= 0; ) {
1596 digit hi = pin[i];
1597 for (j = 0; j < size; j++) {
1598 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1599 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1600 pout[j] = (digit)(z - (twodigits)hi *
1601 _PyLong_DECIMAL_BASE);
1602 }
1603 while (hi) {
1604 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1605 hi /= _PyLong_DECIMAL_BASE;
1606 }
1607 /* check for keyboard interrupt */
1608 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001609 Py_DECREF(scratch);
1610 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001611 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 }
1613 /* pout should have at least one digit, so that the case when a = 0
1614 works correctly */
1615 if (size == 0)
1616 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* calculate exact length of output string, and allocate */
1619 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1620 tenpow = 10;
1621 rem = pout[size-1];
1622 while (rem >= tenpow) {
1623 tenpow *= 10;
1624 strlen++;
1625 }
1626 str = PyUnicode_FromUnicode(NULL, strlen);
1627 if (str == NULL) {
1628 Py_DECREF(scratch);
1629 return NULL;
1630 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 /* fill the string right-to-left */
1633 p = PyUnicode_AS_UNICODE(str) + strlen;
1634 *p = '\0';
1635 /* pout[0] through pout[size-2] contribute exactly
1636 _PyLong_DECIMAL_SHIFT digits each */
1637 for (i=0; i < size - 1; i++) {
1638 rem = pout[i];
1639 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1640 *--p = '0' + rem % 10;
1641 rem /= 10;
1642 }
1643 }
1644 /* pout[size-1]: always produce at least one decimal digit */
1645 rem = pout[i];
1646 do {
1647 *--p = '0' + rem % 10;
1648 rem /= 10;
1649 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 /* and sign */
1652 if (negative)
1653 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* check we've counted correctly */
1656 assert(p == PyUnicode_AS_UNICODE(str));
1657 Py_DECREF(scratch);
1658 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001659}
1660
Mark Dickinsoncd068122009-09-18 14:53:08 +00001661/* Convert a long int object to a string, using a given conversion base,
1662 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001663 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001664
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001665PyObject *
1666_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 register PyLongObject *a = (PyLongObject *)aa;
1669 PyObject *str;
1670 Py_ssize_t i, sz;
1671 Py_ssize_t size_a;
1672 Py_UNICODE *p, sign = '\0';
1673 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 assert(base == 2 || base == 8 || base == 10 || base == 16);
1676 if (base == 10)
1677 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 if (a == NULL || !PyLong_Check(a)) {
1680 PyErr_BadInternalCall();
1681 return NULL;
1682 }
1683 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 /* Compute a rough upper bound for the length of the string */
1686 switch (base) {
1687 case 16:
1688 bits = 4;
1689 break;
1690 case 8:
1691 bits = 3;
1692 break;
1693 case 2:
1694 bits = 1;
1695 break;
1696 default:
1697 assert(0); /* shouldn't ever get here */
1698 bits = 0; /* to silence gcc warning */
1699 }
1700 /* compute length of output string: allow 2 characters for prefix and
1701 1 for possible '-' sign. */
1702 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1703 PyErr_SetString(PyExc_OverflowError,
1704 "int is too large to format");
1705 return NULL;
1706 }
1707 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1708 is safe from overflow */
1709 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1710 assert(sz >= 0);
1711 str = PyUnicode_FromUnicode(NULL, sz);
1712 if (str == NULL)
1713 return NULL;
1714 p = PyUnicode_AS_UNICODE(str) + sz;
1715 *p = '\0';
1716 if (Py_SIZE(a) < 0)
1717 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (Py_SIZE(a) == 0) {
1720 *--p = '0';
1721 }
1722 else {
1723 /* JRH: special case for power-of-2 bases */
1724 twodigits accum = 0;
1725 int accumbits = 0; /* # of bits in accum */
1726 for (i = 0; i < size_a; ++i) {
1727 accum |= (twodigits)a->ob_digit[i] << accumbits;
1728 accumbits += PyLong_SHIFT;
1729 assert(accumbits >= bits);
1730 do {
1731 Py_UNICODE cdigit;
1732 cdigit = (Py_UNICODE)(accum & (base - 1));
1733 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1734 assert(p > PyUnicode_AS_UNICODE(str));
1735 *--p = cdigit;
1736 accumbits -= bits;
1737 accum >>= bits;
1738 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1739 }
1740 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 if (base == 16)
1743 *--p = 'x';
1744 else if (base == 8)
1745 *--p = 'o';
1746 else /* (base == 2) */
1747 *--p = 'b';
1748 *--p = '0';
1749 if (sign)
1750 *--p = sign;
1751 if (p != PyUnicode_AS_UNICODE(str)) {
1752 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1753 assert(p > q);
1754 do {
1755 } while ((*q++ = *p++) != '\0');
1756 q--;
1757 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1758 PyUnicode_AS_UNICODE(str)))) {
1759 Py_DECREF(str);
1760 return NULL;
1761 }
1762 }
1763 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001764}
1765
Thomas Wouters477c8d52006-05-27 19:21:47 +00001766/* Table of digit values for 8-bit string -> integer conversion.
1767 * '0' maps to 0, ..., '9' maps to 9.
1768 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1769 * All other indices map to 37.
1770 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001771 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001772 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001773unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1775 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1776 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1777 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1778 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1779 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1780 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1781 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1782 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1783 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1784 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1785 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1786 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1787 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1788 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1789 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001790};
1791
1792/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001793 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1794 * non-digit (which may be *str!). A normalized long is returned.
1795 * The point to this routine is that it takes time linear in the number of
1796 * string characters.
1797 */
1798static PyLongObject *
1799long_from_binary_base(char **str, int base)
1800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 char *p = *str;
1802 char *start = p;
1803 int bits_per_char;
1804 Py_ssize_t n;
1805 PyLongObject *z;
1806 twodigits accum;
1807 int bits_in_accum;
1808 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1811 n = base;
1812 for (bits_per_char = -1; n; ++bits_per_char)
1813 n >>= 1;
1814 /* n <- total # of bits needed, while setting p to end-of-string */
1815 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1816 ++p;
1817 *str = p;
1818 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1819 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1820 if (n / bits_per_char < p - start) {
1821 PyErr_SetString(PyExc_ValueError,
1822 "int string too large to convert");
1823 return NULL;
1824 }
1825 n = n / PyLong_SHIFT;
1826 z = _PyLong_New(n);
1827 if (z == NULL)
1828 return NULL;
1829 /* Read string from right, and fill in long from left; i.e.,
1830 * from least to most significant in both.
1831 */
1832 accum = 0;
1833 bits_in_accum = 0;
1834 pdigit = z->ob_digit;
1835 while (--p >= start) {
1836 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1837 assert(k >= 0 && k < base);
1838 accum |= (twodigits)k << bits_in_accum;
1839 bits_in_accum += bits_per_char;
1840 if (bits_in_accum >= PyLong_SHIFT) {
1841 *pdigit++ = (digit)(accum & PyLong_MASK);
1842 assert(pdigit - z->ob_digit <= n);
1843 accum >>= PyLong_SHIFT;
1844 bits_in_accum -= PyLong_SHIFT;
1845 assert(bits_in_accum < PyLong_SHIFT);
1846 }
1847 }
1848 if (bits_in_accum) {
1849 assert(bits_in_accum <= PyLong_SHIFT);
1850 *pdigit++ = (digit)accum;
1851 assert(pdigit - z->ob_digit <= n);
1852 }
1853 while (pdigit - z->ob_digit < n)
1854 *pdigit++ = 0;
1855 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001856}
1857
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001858PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001859PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 int sign = 1, error_if_nonzero = 0;
1862 char *start, *orig_str = str;
1863 PyLongObject *z = NULL;
1864 PyObject *strobj;
1865 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if ((base != 0 && base < 2) || base > 36) {
1868 PyErr_SetString(PyExc_ValueError,
1869 "int() arg 2 must be >= 2 and <= 36");
1870 return NULL;
1871 }
1872 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1873 str++;
1874 if (*str == '+')
1875 ++str;
1876 else if (*str == '-') {
1877 ++str;
1878 sign = -1;
1879 }
1880 if (base == 0) {
1881 if (str[0] != '0')
1882 base = 10;
1883 else if (str[1] == 'x' || str[1] == 'X')
1884 base = 16;
1885 else if (str[1] == 'o' || str[1] == 'O')
1886 base = 8;
1887 else if (str[1] == 'b' || str[1] == 'B')
1888 base = 2;
1889 else {
1890 /* "old" (C-style) octal literal, now invalid.
1891 it might still be zero though */
1892 error_if_nonzero = 1;
1893 base = 10;
1894 }
1895 }
1896 if (str[0] == '0' &&
1897 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1898 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1899 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1900 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 start = str;
1903 if ((base & (base - 1)) == 0)
1904 z = long_from_binary_base(&str, base);
1905 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906/***
1907Binary bases can be converted in time linear in the number of digits, because
1908Python's representation base is binary. Other bases (including decimal!) use
1909the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001910
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911First some math: the largest integer that can be expressed in N base-B digits
1912is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1913case number of Python digits needed to hold it is the smallest integer n s.t.
1914
1915 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1916 BASE**n >= B**N [taking logs to base BASE]
1917 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1918
1919The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1920this quickly. A Python long with that much space is reserved near the start,
1921and the result is computed into it.
1922
1923The input string is actually treated as being in base base**i (i.e., i digits
1924are processed at a time), where two more static arrays hold:
1925
1926 convwidth_base[base] = the largest integer i such that base**i <= BASE
1927 convmultmax_base[base] = base ** convwidth_base[base]
1928
1929The first of these is the largest i such that i consecutive input digits
1930must fit in a single Python digit. The second is effectively the input
1931base we're really using.
1932
1933Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1934convmultmax_base[base], the result is "simply"
1935
1936 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1937
1938where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001939
1940Error analysis: as above, the number of Python digits `n` needed is worst-
1941case
1942
1943 n >= N * log(B)/log(BASE)
1944
1945where `N` is the number of input digits in base `B`. This is computed via
1946
1947 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1948
1949below. Two numeric concerns are how much space this can waste, and whether
1950the computed result can be too small. To be concrete, assume BASE = 2**15,
1951which is the default (and it's unlikely anyone changes that).
1952
1953Waste isn't a problem: provided the first input digit isn't 0, the difference
1954between the worst-case input with N digits and the smallest input with N
1955digits is about a factor of B, but B is small compared to BASE so at most
1956one allocated Python digit can remain unused on that count. If
1957N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1958and adding 1 returns a result 1 larger than necessary. However, that can't
1959happen: whenever B is a power of 2, long_from_binary_base() is called
1960instead, and it's impossible for B**i to be an integer power of 2**15 when
1961B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1962an exact integer when B is not a power of 2, since B**i has a prime factor
1963other than 2 in that case, but (2**15)**j's only prime factor is 2).
1964
1965The computed result can be too small if the true value of N*log(B)/log(BASE)
1966is a little bit larger than an exact integer, but due to roundoff errors (in
1967computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1968yields a numeric result a little less than that integer. Unfortunately, "how
1969close can a transcendental function get to an integer over some range?"
1970questions are generally theoretically intractable. Computer analysis via
1971continued fractions is practical: expand log(B)/log(BASE) via continued
1972fractions, giving a sequence i/j of "the best" rational approximations. Then
1973j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1974we can get very close to being in trouble, but very rarely. For example,
197576573 is a denominator in one of the continued-fraction approximations to
1976log(10)/log(2**15), and indeed:
1977
1978 >>> log(10)/log(2**15)*76573
1979 16958.000000654003
1980
1981is very close to an integer. If we were working with IEEE single-precision,
1982rounding errors could kill us. Finding worst cases in IEEE double-precision
1983requires better-than-double-precision log() functions, and Tim didn't bother.
1984Instead the code checks to see whether the allocated space is enough as each
1985new Python digit is added, and copies the whole thing to a larger long if not.
1986This should happen extremely rarely, and in fact I don't have a test case
1987that triggers it(!). Instead the code was tested by artificially allocating
1988just 1 digit at the start, so that the copying code was exercised for every
1989digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001990***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 register twodigits c; /* current input character */
1992 Py_ssize_t size_z;
1993 int i;
1994 int convwidth;
1995 twodigits convmultmax, convmult;
1996 digit *pz, *pzstop;
1997 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 static double log_base_BASE[37] = {0.0e0,};
2000 static int convwidth_base[37] = {0,};
2001 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 if (log_base_BASE[base] == 0.0) {
2004 twodigits convmax = base;
2005 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002006
Mark Dickinson22b20182010-05-10 21:27:53 +00002007 log_base_BASE[base] = (log((double)base) /
2008 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 for (;;) {
2010 twodigits next = convmax * base;
2011 if (next > PyLong_BASE)
2012 break;
2013 convmax = next;
2014 ++i;
2015 }
2016 convmultmax_base[base] = convmax;
2017 assert(i > 0);
2018 convwidth_base[base] = i;
2019 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* Find length of the string of numeric characters. */
2022 scan = str;
2023 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2024 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 /* Create a long object that can contain the largest possible
2027 * integer with this base and length. Note that there's no
2028 * need to initialize z->ob_digit -- no slot is read up before
2029 * being stored into.
2030 */
2031 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2032 /* Uncomment next line to test exceedingly rare copy code */
2033 /* size_z = 1; */
2034 assert(size_z > 0);
2035 z = _PyLong_New(size_z);
2036 if (z == NULL)
2037 return NULL;
2038 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* `convwidth` consecutive input digits are treated as a single
2041 * digit in base `convmultmax`.
2042 */
2043 convwidth = convwidth_base[base];
2044 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* Work ;-) */
2047 while (str < scan) {
2048 /* grab up to convwidth digits from the input string */
2049 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2050 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2051 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002052 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 assert(c < PyLong_BASE);
2054 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 convmult = convmultmax;
2057 /* Calculate the shift only if we couldn't get
2058 * convwidth digits.
2059 */
2060 if (i != convwidth) {
2061 convmult = base;
2062 for ( ; i > 1; --i)
2063 convmult *= base;
2064 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 /* Multiply z by convmult, and add c. */
2067 pz = z->ob_digit;
2068 pzstop = pz + Py_SIZE(z);
2069 for (; pz < pzstop; ++pz) {
2070 c += (twodigits)*pz * convmult;
2071 *pz = (digit)(c & PyLong_MASK);
2072 c >>= PyLong_SHIFT;
2073 }
2074 /* carry off the current end? */
2075 if (c) {
2076 assert(c < PyLong_BASE);
2077 if (Py_SIZE(z) < size_z) {
2078 *pz = (digit)c;
2079 ++Py_SIZE(z);
2080 }
2081 else {
2082 PyLongObject *tmp;
2083 /* Extremely rare. Get more space. */
2084 assert(Py_SIZE(z) == size_z);
2085 tmp = _PyLong_New(size_z + 1);
2086 if (tmp == NULL) {
2087 Py_DECREF(z);
2088 return NULL;
2089 }
2090 memcpy(tmp->ob_digit,
2091 z->ob_digit,
2092 sizeof(digit) * size_z);
2093 Py_DECREF(z);
2094 z = tmp;
2095 z->ob_digit[size_z] = (digit)c;
2096 ++size_z;
2097 }
2098 }
2099 }
2100 }
2101 if (z == NULL)
2102 return NULL;
2103 if (error_if_nonzero) {
2104 /* reset the base to 0, else the exception message
2105 doesn't make too much sense */
2106 base = 0;
2107 if (Py_SIZE(z) != 0)
2108 goto onError;
2109 /* there might still be other problems, therefore base
2110 remains zero here for the same reason */
2111 }
2112 if (str == start)
2113 goto onError;
2114 if (sign < 0)
2115 Py_SIZE(z) = -(Py_SIZE(z));
2116 while (*str && isspace(Py_CHARMASK(*str)))
2117 str++;
2118 if (*str != '\0')
2119 goto onError;
2120 if (pend)
2121 *pend = str;
2122 long_normalize(z);
2123 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002124
Mark Dickinson22b20182010-05-10 21:27:53 +00002125 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 Py_XDECREF(z);
2127 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2128 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2129 if (strobj == NULL)
2130 return NULL;
2131 PyErr_Format(PyExc_ValueError,
2132 "invalid literal for int() with base %d: %R",
2133 base, strobj);
2134 Py_DECREF(strobj);
2135 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002136}
2137
2138PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002139PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002142 PyObject *asciidig;
2143 char *buffer, *end;
2144 Py_ssize_t i, buflen;
2145 Py_UNICODE *ptr;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002146
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002147 asciidig = PyUnicode_TransformDecimalToASCII(u, length);
2148 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 return NULL;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002150 /* Replace non-ASCII whitespace with ' ' */
2151 ptr = PyUnicode_AS_UNICODE(asciidig);
2152 for (i = 0; i < length; i++) {
Mark Dickinsonc9fb3c62010-12-04 11:06:25 +00002153 Py_UNICODE ch = ptr[i];
2154 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
2155 ptr[i] = ' ';
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002156 }
2157 buffer = _PyUnicode_AsStringAndSize(asciidig, &buflen);
2158 if (buffer == NULL) {
2159 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 return NULL;
2161 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002162 result = PyLong_FromString(buffer, &end, base);
2163 if (result != NULL && end != buffer + buflen) {
2164 PyErr_SetString(PyExc_ValueError,
2165 "null byte in argument for int()");
2166 Py_DECREF(result);
2167 result = NULL;
2168 }
2169 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002171}
2172
Tim Peters9f688bf2000-07-07 15:53:28 +00002173/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002176static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002177
2178/* Long division with remainder, top-level routine */
2179
Guido van Rossume32e0141992-01-19 16:31:05 +00002180static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002181long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2185 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 if (size_b == 0) {
2188 PyErr_SetString(PyExc_ZeroDivisionError,
2189 "integer division or modulo by zero");
2190 return -1;
2191 }
2192 if (size_a < size_b ||
2193 (size_a == size_b &&
2194 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2195 /* |a| < |b|. */
2196 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2197 if (*pdiv == NULL)
2198 return -1;
2199 Py_INCREF(a);
2200 *prem = (PyLongObject *) a;
2201 return 0;
2202 }
2203 if (size_b == 1) {
2204 digit rem = 0;
2205 z = divrem1(a, b->ob_digit[0], &rem);
2206 if (z == NULL)
2207 return -1;
2208 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2209 if (*prem == NULL) {
2210 Py_DECREF(z);
2211 return -1;
2212 }
2213 }
2214 else {
2215 z = x_divrem(a, b, prem);
2216 if (z == NULL)
2217 return -1;
2218 }
2219 /* Set the signs.
2220 The quotient z has the sign of a*b;
2221 the remainder r has the sign of a,
2222 so a = b*z + r. */
2223 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2224 NEGATE(z);
2225 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2226 NEGATE(*prem);
2227 *pdiv = maybe_small_long(z);
2228 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002229}
2230
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002231/* Unsigned long division with remainder -- the algorithm. The arguments v1
2232 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002233
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002234static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002235x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyLongObject *v, *w, *a;
2238 Py_ssize_t i, k, size_v, size_w;
2239 int d;
2240 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2241 twodigits vv;
2242 sdigit zhi;
2243 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2246 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2247 handle the special case when the initial estimate q for a quotient
2248 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2249 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 /* allocate space; w will also be used to hold the final remainder */
2252 size_v = ABS(Py_SIZE(v1));
2253 size_w = ABS(Py_SIZE(w1));
2254 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2255 v = _PyLong_New(size_v+1);
2256 if (v == NULL) {
2257 *prem = NULL;
2258 return NULL;
2259 }
2260 w = _PyLong_New(size_w);
2261 if (w == NULL) {
2262 Py_DECREF(v);
2263 *prem = NULL;
2264 return NULL;
2265 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2268 shift v1 left by the same amount. Results go into w and v. */
2269 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2270 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2271 assert(carry == 0);
2272 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2273 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2274 v->ob_digit[size_v] = carry;
2275 size_v++;
2276 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2279 at most (and usually exactly) k = size_v - size_w digits. */
2280 k = size_v - size_w;
2281 assert(k >= 0);
2282 a = _PyLong_New(k);
2283 if (a == NULL) {
2284 Py_DECREF(w);
2285 Py_DECREF(v);
2286 *prem = NULL;
2287 return NULL;
2288 }
2289 v0 = v->ob_digit;
2290 w0 = w->ob_digit;
2291 wm1 = w0[size_w-1];
2292 wm2 = w0[size_w-2];
2293 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2294 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2295 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002298 Py_DECREF(a);
2299 Py_DECREF(w);
2300 Py_DECREF(v);
2301 *prem = NULL;
2302 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002303 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* estimate quotient digit q; may overestimate by 1 (rare) */
2306 vtop = vk[size_w];
2307 assert(vtop <= wm1);
2308 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2309 q = (digit)(vv / wm1);
2310 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2311 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2312 | vk[size_w-2])) {
2313 --q;
2314 r += wm1;
2315 if (r >= PyLong_BASE)
2316 break;
2317 }
2318 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2321 zhi = 0;
2322 for (i = 0; i < size_w; ++i) {
2323 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2324 -PyLong_BASE * q <= z < PyLong_BASE */
2325 z = (sdigit)vk[i] + zhi -
2326 (stwodigits)q * (stwodigits)w0[i];
2327 vk[i] = (digit)z & PyLong_MASK;
2328 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002329 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 /* add w back if q was too large (this branch taken rarely) */
2333 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2334 if ((sdigit)vtop + zhi < 0) {
2335 carry = 0;
2336 for (i = 0; i < size_w; ++i) {
2337 carry += vk[i] + w0[i];
2338 vk[i] = carry & PyLong_MASK;
2339 carry >>= PyLong_SHIFT;
2340 }
2341 --q;
2342 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 /* store quotient digit */
2345 assert(q < PyLong_BASE);
2346 *--ak = q;
2347 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* unshift remainder; we reuse w to store the result */
2350 carry = v_rshift(w0, v0, size_w, d);
2351 assert(carry==0);
2352 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 *prem = long_normalize(w);
2355 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002356}
2357
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002358/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2359 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2360 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2361 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2362 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2363 -1.0. */
2364
2365/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2366#if DBL_MANT_DIG == 53
2367#define EXP2_DBL_MANT_DIG 9007199254740992.0
2368#else
2369#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2370#endif
2371
2372double
2373_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2376 /* See below for why x_digits is always large enough. */
2377 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2378 double dx;
2379 /* Correction term for round-half-to-even rounding. For a digit x,
2380 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2381 multiple of 4, rounding ties to a multiple of 8. */
2382 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 a_size = ABS(Py_SIZE(a));
2385 if (a_size == 0) {
2386 /* Special case for 0: significand 0.0, exponent 0. */
2387 *e = 0;
2388 return 0.0;
2389 }
2390 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2391 /* The following is an overflow-free version of the check
2392 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2393 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2394 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2395 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002396 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2400 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 Number of digits needed for result: write // for floor division.
2403 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2412 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2415 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2416 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 in both cases.
2423 */
2424 if (a_bits <= DBL_MANT_DIG + 2) {
2425 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2426 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2427 x_size = 0;
2428 while (x_size < shift_digits)
2429 x_digits[x_size++] = 0;
2430 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2431 (int)shift_bits);
2432 x_size += a_size;
2433 x_digits[x_size++] = rem;
2434 }
2435 else {
2436 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2437 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2438 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2439 a_size - shift_digits, (int)shift_bits);
2440 x_size = a_size - shift_digits;
2441 /* For correct rounding below, we need the least significant
2442 bit of x to be 'sticky' for this shift: if any of the bits
2443 shifted out was nonzero, we set the least significant bit
2444 of x. */
2445 if (rem)
2446 x_digits[0] |= 1;
2447 else
2448 while (shift_digits > 0)
2449 if (a->ob_digit[--shift_digits]) {
2450 x_digits[0] |= 1;
2451 break;
2452 }
2453 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002454 assert(1 <= x_size &&
2455 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* Round, and convert to double. */
2458 x_digits[0] += half_even_correction[x_digits[0] & 7];
2459 dx = x_digits[--x_size];
2460 while (x_size > 0)
2461 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 /* Rescale; make correction if result is 1.0. */
2464 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2465 if (dx == 1.0) {
2466 if (a_bits == PY_SSIZE_T_MAX)
2467 goto overflow;
2468 dx = 0.5;
2469 a_bits += 1;
2470 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 *e = a_bits;
2473 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002474
2475 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* exponent > PY_SSIZE_T_MAX */
2477 PyErr_SetString(PyExc_OverflowError,
2478 "huge integer: number of bits overflows a Py_ssize_t");
2479 *e = 0;
2480 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002481}
2482
2483/* Get a C double from a long int object. Rounds to the nearest double,
2484 using the round-half-to-even rule in the case of a tie. */
2485
2486double
2487PyLong_AsDouble(PyObject *v)
2488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 Py_ssize_t exponent;
2490 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (v == NULL || !PyLong_Check(v)) {
2493 PyErr_BadInternalCall();
2494 return -1.0;
2495 }
2496 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2497 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2498 PyErr_SetString(PyExc_OverflowError,
2499 "long int too large to convert to float");
2500 return -1.0;
2501 }
2502 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002503}
2504
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002505/* Methods */
2506
2507static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002508long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002511}
2512
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002513static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002514long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 if (Py_SIZE(a) != Py_SIZE(b)) {
2519 sign = Py_SIZE(a) - Py_SIZE(b);
2520 }
2521 else {
2522 Py_ssize_t i = ABS(Py_SIZE(a));
2523 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2524 ;
2525 if (i < 0)
2526 sign = 0;
2527 else {
2528 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2529 if (Py_SIZE(a) < 0)
2530 sign = -sign;
2531 }
2532 }
2533 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002534}
2535
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002536#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002538
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002539static PyObject *
2540long_richcompare(PyObject *self, PyObject *other, int op)
2541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 int result;
2543 PyObject *v;
2544 CHECK_BINOP(self, other);
2545 if (self == other)
2546 result = 0;
2547 else
2548 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2549 /* Convert the return value to a Boolean */
2550 switch (op) {
2551 case Py_EQ:
2552 v = TEST_COND(result == 0);
2553 break;
2554 case Py_NE:
2555 v = TEST_COND(result != 0);
2556 break;
2557 case Py_LE:
2558 v = TEST_COND(result <= 0);
2559 break;
2560 case Py_GE:
2561 v = TEST_COND(result >= 0);
2562 break;
2563 case Py_LT:
2564 v = TEST_COND(result == -1);
2565 break;
2566 case Py_GT:
2567 v = TEST_COND(result == 1);
2568 break;
2569 default:
2570 PyErr_BadArgument();
2571 return NULL;
2572 }
2573 Py_INCREF(v);
2574 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002575}
2576
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002577static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002578long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002579{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002580 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 Py_ssize_t i;
2582 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 i = Py_SIZE(v);
2585 switch(i) {
2586 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2587 case 0: return 0;
2588 case 1: return v->ob_digit[0];
2589 }
2590 sign = 1;
2591 x = 0;
2592 if (i < 0) {
2593 sign = -1;
2594 i = -(i);
2595 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002597 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2598 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2599 _PyHASH_MODULUS.
2600
2601 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2602 amounts to a rotation of the bits of x. To see this, write
2603
2604 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2605
2606 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2607 PyLong_SHIFT bits of x (those that are shifted out of the
2608 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2609 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2610 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2611 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2612 congruent to y modulo _PyHASH_MODULUS. So
2613
2614 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2615
2616 The right-hand side is just the result of rotating the
2617 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2618 not all _PyHASH_BITS bits of x are 1s, the same is true
2619 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2620 the reduction of x*2**PyLong_SHIFT modulo
2621 _PyHASH_MODULUS. */
2622 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2623 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002625 if (x >= _PyHASH_MODULUS)
2626 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 }
2628 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002629 if (x == (Py_uhash_t)-1)
2630 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002631 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002632}
2633
2634
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002635/* Add the absolute values of two long integers. */
2636
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002637static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002638x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2641 PyLongObject *z;
2642 Py_ssize_t i;
2643 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 /* Ensure a is the larger of the two: */
2646 if (size_a < size_b) {
2647 { PyLongObject *temp = a; a = b; b = temp; }
2648 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002649 size_a = size_b;
2650 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 }
2652 z = _PyLong_New(size_a+1);
2653 if (z == NULL)
2654 return NULL;
2655 for (i = 0; i < size_b; ++i) {
2656 carry += a->ob_digit[i] + b->ob_digit[i];
2657 z->ob_digit[i] = carry & PyLong_MASK;
2658 carry >>= PyLong_SHIFT;
2659 }
2660 for (; i < size_a; ++i) {
2661 carry += a->ob_digit[i];
2662 z->ob_digit[i] = carry & PyLong_MASK;
2663 carry >>= PyLong_SHIFT;
2664 }
2665 z->ob_digit[i] = carry;
2666 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002667}
2668
2669/* Subtract the absolute values of two integers. */
2670
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002671static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002672x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2675 PyLongObject *z;
2676 Py_ssize_t i;
2677 int sign = 1;
2678 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 /* Ensure a is the larger of the two: */
2681 if (size_a < size_b) {
2682 sign = -1;
2683 { PyLongObject *temp = a; a = b; b = temp; }
2684 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002685 size_a = size_b;
2686 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 }
2688 else if (size_a == size_b) {
2689 /* Find highest digit where a and b differ: */
2690 i = size_a;
2691 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2692 ;
2693 if (i < 0)
2694 return (PyLongObject *)PyLong_FromLong(0);
2695 if (a->ob_digit[i] < b->ob_digit[i]) {
2696 sign = -1;
2697 { PyLongObject *temp = a; a = b; b = temp; }
2698 }
2699 size_a = size_b = i+1;
2700 }
2701 z = _PyLong_New(size_a);
2702 if (z == NULL)
2703 return NULL;
2704 for (i = 0; i < size_b; ++i) {
2705 /* The following assumes unsigned arithmetic
2706 works module 2**N for some N>PyLong_SHIFT. */
2707 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2708 z->ob_digit[i] = borrow & PyLong_MASK;
2709 borrow >>= PyLong_SHIFT;
2710 borrow &= 1; /* Keep only one sign bit */
2711 }
2712 for (; i < size_a; ++i) {
2713 borrow = a->ob_digit[i] - borrow;
2714 z->ob_digit[i] = borrow & PyLong_MASK;
2715 borrow >>= PyLong_SHIFT;
2716 borrow &= 1; /* Keep only one sign bit */
2717 }
2718 assert(borrow == 0);
2719 if (sign < 0)
2720 NEGATE(z);
2721 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002722}
2723
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002724static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002725long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2732 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2733 MEDIUM_VALUE(b));
2734 return result;
2735 }
2736 if (Py_SIZE(a) < 0) {
2737 if (Py_SIZE(b) < 0) {
2738 z = x_add(a, b);
2739 if (z != NULL && Py_SIZE(z) != 0)
2740 Py_SIZE(z) = -(Py_SIZE(z));
2741 }
2742 else
2743 z = x_sub(b, a);
2744 }
2745 else {
2746 if (Py_SIZE(b) < 0)
2747 z = x_sub(a, b);
2748 else
2749 z = x_add(a, b);
2750 }
2751 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002752}
2753
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002754static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002755long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2762 PyObject* r;
2763 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2764 return r;
2765 }
2766 if (Py_SIZE(a) < 0) {
2767 if (Py_SIZE(b) < 0)
2768 z = x_sub(a, b);
2769 else
2770 z = x_add(a, b);
2771 if (z != NULL && Py_SIZE(z) != 0)
2772 Py_SIZE(z) = -(Py_SIZE(z));
2773 }
2774 else {
2775 if (Py_SIZE(b) < 0)
2776 z = x_add(a, b);
2777 else
2778 z = x_sub(a, b);
2779 }
2780 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002781}
2782
Tim Peters5af4e6c2002-08-12 02:31:19 +00002783/* Grade school multiplication, ignoring the signs.
2784 * Returns the absolute value of the product, or NULL if error.
2785 */
2786static PyLongObject *
2787x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 PyLongObject *z;
2790 Py_ssize_t size_a = ABS(Py_SIZE(a));
2791 Py_ssize_t size_b = ABS(Py_SIZE(b));
2792 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 z = _PyLong_New(size_a + size_b);
2795 if (z == NULL)
2796 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2799 if (a == b) {
2800 /* Efficient squaring per HAC, Algorithm 14.16:
2801 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2802 * Gives slightly less than a 2x speedup when a == b,
2803 * via exploiting that each entry in the multiplication
2804 * pyramid appears twice (except for the size_a squares).
2805 */
2806 for (i = 0; i < size_a; ++i) {
2807 twodigits carry;
2808 twodigits f = a->ob_digit[i];
2809 digit *pz = z->ob_digit + (i << 1);
2810 digit *pa = a->ob_digit + i + 1;
2811 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002814 Py_DECREF(z);
2815 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002816 });
Tim Peters0973b992004-08-29 22:16:50 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 carry = *pz + f * f;
2819 *pz++ = (digit)(carry & PyLong_MASK);
2820 carry >>= PyLong_SHIFT;
2821 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* Now f is added in twice in each column of the
2824 * pyramid it appears. Same as adding f<<1 once.
2825 */
2826 f <<= 1;
2827 while (pa < paend) {
2828 carry += *pz + *pa++ * f;
2829 *pz++ = (digit)(carry & PyLong_MASK);
2830 carry >>= PyLong_SHIFT;
2831 assert(carry <= (PyLong_MASK << 1));
2832 }
2833 if (carry) {
2834 carry += *pz;
2835 *pz++ = (digit)(carry & PyLong_MASK);
2836 carry >>= PyLong_SHIFT;
2837 }
2838 if (carry)
2839 *pz += (digit)(carry & PyLong_MASK);
2840 assert((carry >> PyLong_SHIFT) == 0);
2841 }
2842 }
2843 else { /* a is not the same as b -- gradeschool long mult */
2844 for (i = 0; i < size_a; ++i) {
2845 twodigits carry = 0;
2846 twodigits f = a->ob_digit[i];
2847 digit *pz = z->ob_digit + i;
2848 digit *pb = b->ob_digit;
2849 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002852 Py_DECREF(z);
2853 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002854 });
Tim Peters0973b992004-08-29 22:16:50 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 while (pb < pbend) {
2857 carry += *pz + *pb++ * f;
2858 *pz++ = (digit)(carry & PyLong_MASK);
2859 carry >>= PyLong_SHIFT;
2860 assert(carry <= PyLong_MASK);
2861 }
2862 if (carry)
2863 *pz += (digit)(carry & PyLong_MASK);
2864 assert((carry >> PyLong_SHIFT) == 0);
2865 }
2866 }
2867 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002868}
2869
2870/* A helper for Karatsuba multiplication (k_mul).
2871 Takes a long "n" and an integer "size" representing the place to
2872 split, and sets low and high such that abs(n) == (high << size) + low,
2873 viewing the shift as being by digits. The sign bit is ignored, and
2874 the return values are >= 0.
2875 Returns 0 on success, -1 on failure.
2876*/
2877static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002878kmul_split(PyLongObject *n,
2879 Py_ssize_t size,
2880 PyLongObject **high,
2881 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 PyLongObject *hi, *lo;
2884 Py_ssize_t size_lo, size_hi;
2885 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 size_lo = MIN(size_n, size);
2888 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 if ((hi = _PyLong_New(size_hi)) == NULL)
2891 return -1;
2892 if ((lo = _PyLong_New(size_lo)) == NULL) {
2893 Py_DECREF(hi);
2894 return -1;
2895 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2898 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 *high = long_normalize(hi);
2901 *low = long_normalize(lo);
2902 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002903}
2904
Tim Peters60004642002-08-12 22:01:34 +00002905static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2906
Tim Peters5af4e6c2002-08-12 02:31:19 +00002907/* Karatsuba multiplication. Ignores the input signs, and returns the
2908 * absolute value of the product (or NULL if error).
2909 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2910 */
2911static PyLongObject *
2912k_mul(PyLongObject *a, PyLongObject *b)
2913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 Py_ssize_t asize = ABS(Py_SIZE(a));
2915 Py_ssize_t bsize = ABS(Py_SIZE(b));
2916 PyLongObject *ah = NULL;
2917 PyLongObject *al = NULL;
2918 PyLongObject *bh = NULL;
2919 PyLongObject *bl = NULL;
2920 PyLongObject *ret = NULL;
2921 PyLongObject *t1, *t2, *t3;
2922 Py_ssize_t shift; /* the number of digits we split off */
2923 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2926 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2927 * Then the original product is
2928 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2929 * By picking X to be a power of 2, "*X" is just shifting, and it's
2930 * been reduced to 3 multiplies on numbers half the size.
2931 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 /* We want to split based on the larger number; fiddle so that b
2934 * is largest.
2935 */
2936 if (asize > bsize) {
2937 t1 = a;
2938 a = b;
2939 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 i = asize;
2942 asize = bsize;
2943 bsize = i;
2944 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 /* Use gradeschool math when either number is too small. */
2947 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2948 if (asize <= i) {
2949 if (asize == 0)
2950 return (PyLongObject *)PyLong_FromLong(0);
2951 else
2952 return x_mul(a, b);
2953 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 /* If a is small compared to b, splitting on b gives a degenerate
2956 * case with ah==0, and Karatsuba may be (even much) less efficient
2957 * than "grade school" then. However, we can still win, by viewing
2958 * b as a string of "big digits", each of width a->ob_size. That
2959 * leads to a sequence of balanced calls to k_mul.
2960 */
2961 if (2 * asize <= bsize)
2962 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 /* Split a & b into hi & lo pieces. */
2965 shift = bsize >> 1;
2966 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2967 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 if (a == b) {
2970 bh = ah;
2971 bl = al;
2972 Py_INCREF(bh);
2973 Py_INCREF(bl);
2974 }
2975 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 /* The plan:
2978 * 1. Allocate result space (asize + bsize digits: that's always
2979 * enough).
2980 * 2. Compute ah*bh, and copy into result at 2*shift.
2981 * 3. Compute al*bl, and copy into result at 0. Note that this
2982 * can't overlap with #2.
2983 * 4. Subtract al*bl from the result, starting at shift. This may
2984 * underflow (borrow out of the high digit), but we don't care:
2985 * we're effectively doing unsigned arithmetic mod
2986 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2987 * borrows and carries out of the high digit can be ignored.
2988 * 5. Subtract ah*bh from the result, starting at shift.
2989 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2990 * at shift.
2991 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 /* 1. Allocate result space. */
2994 ret = _PyLong_New(asize + bsize);
2995 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002996#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 /* Fill with trash, to catch reference to uninitialized digits. */
2998 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999#endif
Tim Peters44121a62002-08-12 06:17:58 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3002 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3003 assert(Py_SIZE(t1) >= 0);
3004 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3005 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3006 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 /* Zero-out the digits higher than the ah*bh copy. */
3009 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3010 if (i)
3011 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3012 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 /* 3. t2 <- al*bl, and copy into the low digits. */
3015 if ((t2 = k_mul(al, bl)) == NULL) {
3016 Py_DECREF(t1);
3017 goto fail;
3018 }
3019 assert(Py_SIZE(t2) >= 0);
3020 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3021 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 /* Zero out remaining digits. */
3024 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3025 if (i)
3026 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3029 * because it's fresher in cache.
3030 */
3031 i = Py_SIZE(ret) - shift; /* # digits after shift */
3032 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3033 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3036 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3039 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3040 Py_DECREF(ah);
3041 Py_DECREF(al);
3042 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 if (a == b) {
3045 t2 = t1;
3046 Py_INCREF(t2);
3047 }
3048 else if ((t2 = x_add(bh, bl)) == NULL) {
3049 Py_DECREF(t1);
3050 goto fail;
3051 }
3052 Py_DECREF(bh);
3053 Py_DECREF(bl);
3054 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 t3 = k_mul(t1, t2);
3057 Py_DECREF(t1);
3058 Py_DECREF(t2);
3059 if (t3 == NULL) goto fail;
3060 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* Add t3. It's not obvious why we can't run out of room here.
3063 * See the (*) comment after this function.
3064 */
3065 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3066 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003069
Mark Dickinson22b20182010-05-10 21:27:53 +00003070 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 Py_XDECREF(ret);
3072 Py_XDECREF(ah);
3073 Py_XDECREF(al);
3074 Py_XDECREF(bh);
3075 Py_XDECREF(bl);
3076 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003077}
3078
Tim Petersd6974a52002-08-13 20:37:51 +00003079/* (*) Why adding t3 can't "run out of room" above.
3080
Tim Petersab86c2b2002-08-15 20:06:00 +00003081Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3082to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003083
Tim Petersab86c2b2002-08-15 20:06:00 +000030841. For any integer i, i = c(i/2) + f(i/2). In particular,
3085 bsize = c(bsize/2) + f(bsize/2).
30862. shift = f(bsize/2)
30873. asize <= bsize
30884. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3089 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003090
Tim Petersab86c2b2002-08-15 20:06:00 +00003091We allocated asize + bsize result digits, and add t3 into them at an offset
3092of shift. This leaves asize+bsize-shift allocated digit positions for t3
3093to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3094asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003095
Tim Petersab86c2b2002-08-15 20:06:00 +00003096bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3097at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003098
Tim Petersab86c2b2002-08-15 20:06:00 +00003099If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3100digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3101most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003102
Tim Petersab86c2b2002-08-15 20:06:00 +00003103The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003104
Tim Petersab86c2b2002-08-15 20:06:00 +00003105 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003106
Tim Petersab86c2b2002-08-15 20:06:00 +00003107and we have asize + c(bsize/2) available digit positions. We need to show
3108this is always enough. An instance of c(bsize/2) cancels out in both, so
3109the question reduces to whether asize digits is enough to hold
3110(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3111then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3112asize 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 +00003113digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003114asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003115c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3116is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3117bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003118
Tim Peters48d52c02002-08-14 17:07:32 +00003119Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3120clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3121ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003122*/
3123
Tim Peters60004642002-08-12 22:01:34 +00003124/* b has at least twice the digits of a, and a is big enough that Karatsuba
3125 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3126 * of slices, each with a->ob_size digits, and multiply the slices by a,
3127 * one at a time. This gives k_mul balanced inputs to work with, and is
3128 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003129 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003130 * single-width slice overlap between successive partial sums).
3131 */
3132static PyLongObject *
3133k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 const Py_ssize_t asize = ABS(Py_SIZE(a));
3136 Py_ssize_t bsize = ABS(Py_SIZE(b));
3137 Py_ssize_t nbdone; /* # of b digits already multiplied */
3138 PyLongObject *ret;
3139 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 assert(asize > KARATSUBA_CUTOFF);
3142 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 /* Allocate result space, and zero it out. */
3145 ret = _PyLong_New(asize + bsize);
3146 if (ret == NULL)
3147 return NULL;
3148 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 /* Successive slices of b are copied into bslice. */
3151 bslice = _PyLong_New(asize);
3152 if (bslice == NULL)
3153 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 nbdone = 0;
3156 while (bsize > 0) {
3157 PyLongObject *product;
3158 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 /* Multiply the next slice of b by a. */
3161 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3162 nbtouse * sizeof(digit));
3163 Py_SIZE(bslice) = nbtouse;
3164 product = k_mul(a, bslice);
3165 if (product == NULL)
3166 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* Add into result. */
3169 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3170 product->ob_digit, Py_SIZE(product));
3171 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 bsize -= nbtouse;
3174 nbdone += nbtouse;
3175 }
Tim Peters60004642002-08-12 22:01:34 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 Py_DECREF(bslice);
3178 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003179
Mark Dickinson22b20182010-05-10 21:27:53 +00003180 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 Py_DECREF(ret);
3182 Py_XDECREF(bslice);
3183 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003184}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003185
3186static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003187long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* fast path for single-digit multiplication */
3194 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3195 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003196#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003198#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 /* if we don't have long long then we're almost certainly
3200 using 15-bit digits, so v will fit in a long. In the
3201 unlikely event that we're using 30-bit digits on a platform
3202 without long long, a large v will just cause us to fall
3203 through to the general multiplication code below. */
3204 if (v >= LONG_MIN && v <= LONG_MAX)
3205 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003206#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 z = k_mul(a, b);
3210 /* Negate if exactly one of the inputs is negative. */
3211 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3212 NEGATE(z);
3213 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003214}
3215
Guido van Rossume32e0141992-01-19 16:31:05 +00003216/* The / and % operators are now defined in terms of divmod().
3217 The expression a mod b has the value a - b*floor(a/b).
3218 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003219 |a| by |b|, with the sign of a. This is also expressed
3220 as a - b*trunc(a/b), if trunc truncates towards zero.
3221 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 a b a rem b a mod b
3223 13 10 3 3
3224 -13 10 -3 7
3225 13 -10 3 -7
3226 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003227 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003228 have different signs. We then subtract one from the 'div'
3229 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003230
Tim Peters47e52ee2004-08-30 02:44:38 +00003231/* Compute
3232 * *pdiv, *pmod = divmod(v, w)
3233 * NULL can be passed for pdiv or pmod, in which case that part of
3234 * the result is simply thrown away. The caller owns a reference to
3235 * each of these it requests (does not pass NULL for).
3236 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003237static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003238l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 if (long_divrem(v, w, &div, &mod) < 0)
3244 return -1;
3245 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3246 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3247 PyLongObject *temp;
3248 PyLongObject *one;
3249 temp = (PyLongObject *) long_add(mod, w);
3250 Py_DECREF(mod);
3251 mod = temp;
3252 if (mod == NULL) {
3253 Py_DECREF(div);
3254 return -1;
3255 }
3256 one = (PyLongObject *) PyLong_FromLong(1L);
3257 if (one == NULL ||
3258 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3259 Py_DECREF(mod);
3260 Py_DECREF(div);
3261 Py_XDECREF(one);
3262 return -1;
3263 }
3264 Py_DECREF(one);
3265 Py_DECREF(div);
3266 div = temp;
3267 }
3268 if (pdiv != NULL)
3269 *pdiv = div;
3270 else
3271 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 if (pmod != NULL)
3274 *pmod = mod;
3275 else
3276 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003279}
3280
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003281static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003282long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 CHECK_BINOP(a, b);
3287 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3288 div = NULL;
3289 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003290}
3291
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003292/* PyLong/PyLong -> float, with correctly rounded result. */
3293
3294#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3295#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3296
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003297static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003298long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 PyLongObject *a, *b, *x;
3301 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3302 digit mask, low;
3303 int inexact, negate, a_is_small, b_is_small;
3304 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 CHECK_BINOP(v, w);
3307 a = (PyLongObject *)v;
3308 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 /*
3311 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3314 1. choose a suitable integer 'shift'
3315 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3316 3. adjust x for correct rounding
3317 4. convert x to a double dx with the same value
3318 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3323 returns either 0.0 or -0.0, depending on the sign of b. For a and
3324 b both nonzero, ignore signs of a and b, and add the sign back in
3325 at the end. Now write a_bits and b_bits for the bit lengths of a
3326 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3327 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3332 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3333 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3334 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 1. The integer 'shift' is chosen so that x has the right number of
3339 bits for a double, plus two or three extra bits that will be used
3340 in the rounding decisions. Writing a_bits and b_bits for the
3341 number of significant bits in a and b respectively, a
3342 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 This is fine in the usual case, but if a/b is smaller than the
3347 smallest normal float then it can lead to double rounding on an
3348 IEEE 754 platform, giving incorrectly rounded results. So we
3349 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 2. The quantity x is computed by first shifting a (left -shift bits
3354 if shift <= 0, right shift bits if shift > 0) and then dividing by
3355 b. For both the shift and the division, we keep track of whether
3356 the result is inexact, in a flag 'inexact'; this information is
3357 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 With the choice of shift above, together with our assumption that
3360 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3361 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3364 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 For float representability, we need x/2**extra_bits <
3369 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3370 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 To round, we just modify the bottom digit of x in-place; this can
3375 end up giving a digit with value > PyLONG_MASK, but that's not a
3376 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 With the original choices for shift above, extra_bits will always
3379 be 2 or 3. Then rounding under the round-half-to-even rule, we
3380 round up iff the most significant of the extra bits is 1, and
3381 either: (a) the computation of x in step 2 had an inexact result,
3382 or (b) at least one other of the extra bits is 1, or (c) the least
3383 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 4. Conversion to a double is straightforward; all floating-point
3386 operations involved in the conversion are exact, so there's no
3387 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3390 The result will always be exactly representable as a double, except
3391 in the case that it overflows. To avoid dependence on the exact
3392 behaviour of ldexp on overflow, we check for overflow before
3393 applying ldexp. The result of ldexp is adjusted for sign before
3394 returning.
3395 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 /* Reduce to case where a and b are both positive. */
3398 a_size = ABS(Py_SIZE(a));
3399 b_size = ABS(Py_SIZE(b));
3400 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3401 if (b_size == 0) {
3402 PyErr_SetString(PyExc_ZeroDivisionError,
3403 "division by zero");
3404 goto error;
3405 }
3406 if (a_size == 0)
3407 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 /* Fast path for a and b small (exactly representable in a double).
3410 Relies on floating-point division being correctly rounded; results
3411 may be subject to double rounding on x86 machines that operate with
3412 the x87 FPU set to 64-bit precision. */
3413 a_is_small = a_size <= MANT_DIG_DIGITS ||
3414 (a_size == MANT_DIG_DIGITS+1 &&
3415 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3416 b_is_small = b_size <= MANT_DIG_DIGITS ||
3417 (b_size == MANT_DIG_DIGITS+1 &&
3418 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3419 if (a_is_small && b_is_small) {
3420 double da, db;
3421 da = a->ob_digit[--a_size];
3422 while (a_size > 0)
3423 da = da * PyLong_BASE + a->ob_digit[--a_size];
3424 db = b->ob_digit[--b_size];
3425 while (b_size > 0)
3426 db = db * PyLong_BASE + b->ob_digit[--b_size];
3427 result = da / db;
3428 goto success;
3429 }
Tim Peterse2a60002001-09-04 06:17:36 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 /* Catch obvious cases of underflow and overflow */
3432 diff = a_size - b_size;
3433 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3434 /* Extreme overflow */
3435 goto overflow;
3436 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3437 /* Extreme underflow */
3438 goto underflow_or_zero;
3439 /* Next line is now safe from overflowing a Py_ssize_t */
3440 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3441 bits_in_digit(b->ob_digit[b_size - 1]);
3442 /* Now diff = a_bits - b_bits. */
3443 if (diff > DBL_MAX_EXP)
3444 goto overflow;
3445 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3446 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 /* Choose value for shift; see comments for step 1 above. */
3449 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 /* x = abs(a * 2**-shift) */
3454 if (shift <= 0) {
3455 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3456 digit rem;
3457 /* x = a << -shift */
3458 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3459 /* In practice, it's probably impossible to end up
3460 here. Both a and b would have to be enormous,
3461 using close to SIZE_T_MAX bytes of memory each. */
3462 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003463 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 goto error;
3465 }
3466 x = _PyLong_New(a_size + shift_digits + 1);
3467 if (x == NULL)
3468 goto error;
3469 for (i = 0; i < shift_digits; i++)
3470 x->ob_digit[i] = 0;
3471 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3472 a_size, -shift % PyLong_SHIFT);
3473 x->ob_digit[a_size + shift_digits] = rem;
3474 }
3475 else {
3476 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3477 digit rem;
3478 /* x = a >> shift */
3479 assert(a_size >= shift_digits);
3480 x = _PyLong_New(a_size - shift_digits);
3481 if (x == NULL)
3482 goto error;
3483 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3484 a_size - shift_digits, shift % PyLong_SHIFT);
3485 /* set inexact if any of the bits shifted out is nonzero */
3486 if (rem)
3487 inexact = 1;
3488 while (!inexact && shift_digits > 0)
3489 if (a->ob_digit[--shift_digits])
3490 inexact = 1;
3491 }
3492 long_normalize(x);
3493 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3496 reference to x, so it's safe to modify it in-place. */
3497 if (b_size == 1) {
3498 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3499 b->ob_digit[0]);
3500 long_normalize(x);
3501 if (rem)
3502 inexact = 1;
3503 }
3504 else {
3505 PyLongObject *div, *rem;
3506 div = x_divrem(x, b, &rem);
3507 Py_DECREF(x);
3508 x = div;
3509 if (x == NULL)
3510 goto error;
3511 if (Py_SIZE(rem))
3512 inexact = 1;
3513 Py_DECREF(rem);
3514 }
3515 x_size = ABS(Py_SIZE(x));
3516 assert(x_size > 0); /* result of division is never zero */
3517 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 /* The number of extra bits that have to be rounded away. */
3520 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3521 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 /* Round by directly modifying the low digit of x. */
3524 mask = (digit)1 << (extra_bits - 1);
3525 low = x->ob_digit[0] | inexact;
3526 if (low & mask && low & (3*mask-1))
3527 low += mask;
3528 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 /* Convert x to a double dx; the conversion is exact. */
3531 dx = x->ob_digit[--x_size];
3532 while (x_size > 0)
3533 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3534 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 /* Check whether ldexp result will overflow a double. */
3537 if (shift + x_bits >= DBL_MAX_EXP &&
3538 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3539 goto overflow;
3540 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003541
3542 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003544
3545 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003547
3548 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 PyErr_SetString(PyExc_OverflowError,
3550 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003551 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003553}
3554
3555static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003556long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 CHECK_BINOP(a, b);
3561
3562 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3563 mod = NULL;
3564 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003565}
3566
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003567static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003568long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 PyLongObject *div, *mod;
3571 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3576 return NULL;
3577 }
3578 z = PyTuple_New(2);
3579 if (z != NULL) {
3580 PyTuple_SetItem(z, 0, (PyObject *) div);
3581 PyTuple_SetItem(z, 1, (PyObject *) mod);
3582 }
3583 else {
3584 Py_DECREF(div);
3585 Py_DECREF(mod);
3586 }
3587 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003588}
3589
Tim Peters47e52ee2004-08-30 02:44:38 +00003590/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003591static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003592long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3595 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 PyLongObject *z = NULL; /* accumulated result */
3598 Py_ssize_t i, j, k; /* counters */
3599 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 /* 5-ary values. If the exponent is large enough, table is
3602 * precomputed so that table[i] == a**i % c for i in range(32).
3603 */
3604 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3605 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 /* a, b, c = v, w, x */
3608 CHECK_BINOP(v, w);
3609 a = (PyLongObject*)v; Py_INCREF(a);
3610 b = (PyLongObject*)w; Py_INCREF(b);
3611 if (PyLong_Check(x)) {
3612 c = (PyLongObject *)x;
3613 Py_INCREF(x);
3614 }
3615 else if (x == Py_None)
3616 c = NULL;
3617 else {
3618 Py_DECREF(a);
3619 Py_DECREF(b);
3620 Py_INCREF(Py_NotImplemented);
3621 return Py_NotImplemented;
3622 }
Tim Peters4c483c42001-09-05 06:24:58 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3625 if (c) {
3626 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003627 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 goto Error;
3629 }
3630 else {
3631 /* else return a float. This works because we know
3632 that this calls float_pow() which converts its
3633 arguments to double. */
3634 Py_DECREF(a);
3635 Py_DECREF(b);
3636 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3637 }
3638 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 if (c) {
3641 /* if modulus == 0:
3642 raise ValueError() */
3643 if (Py_SIZE(c) == 0) {
3644 PyErr_SetString(PyExc_ValueError,
3645 "pow() 3rd argument cannot be 0");
3646 goto Error;
3647 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 /* if modulus < 0:
3650 negativeOutput = True
3651 modulus = -modulus */
3652 if (Py_SIZE(c) < 0) {
3653 negativeOutput = 1;
3654 temp = (PyLongObject *)_PyLong_Copy(c);
3655 if (temp == NULL)
3656 goto Error;
3657 Py_DECREF(c);
3658 c = temp;
3659 temp = NULL;
3660 NEGATE(c);
3661 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003663 /* if modulus == 1:
3664 return 0 */
3665 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3666 z = (PyLongObject *)PyLong_FromLong(0L);
3667 goto Done;
3668 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 /* if base < 0:
3671 base = base % modulus
3672 Having the base positive just makes things easier. */
3673 if (Py_SIZE(a) < 0) {
3674 if (l_divmod(a, c, NULL, &temp) < 0)
3675 goto Error;
3676 Py_DECREF(a);
3677 a = temp;
3678 temp = NULL;
3679 }
3680 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 /* At this point a, b, and c are guaranteed non-negative UNLESS
3683 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003685 z = (PyLongObject *)PyLong_FromLong(1L);
3686 if (z == NULL)
3687 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 /* Perform a modular reduction, X = X % c, but leave X alone if c
3690 * is NULL.
3691 */
3692#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003693 do { \
3694 if (c != NULL) { \
3695 if (l_divmod(X, c, NULL, &temp) < 0) \
3696 goto Error; \
3697 Py_XDECREF(X); \
3698 X = temp; \
3699 temp = NULL; \
3700 } \
3701 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 /* Multiply two values, then reduce the result:
3704 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003705#define MULT(X, Y, result) \
3706 do { \
3707 temp = (PyLongObject *)long_mul(X, Y); \
3708 if (temp == NULL) \
3709 goto Error; \
3710 Py_XDECREF(result); \
3711 result = temp; \
3712 temp = NULL; \
3713 REDUCE(result); \
3714 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3717 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3718 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3719 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3720 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003722 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003723 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003725 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 }
3727 }
3728 }
3729 else {
3730 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3731 Py_INCREF(z); /* still holds 1L */
3732 table[0] = z;
3733 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003734 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3737 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3740 const int index = (bi >> j) & 0x1f;
3741 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003742 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003744 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 }
3746 }
3747 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 if (negativeOutput && (Py_SIZE(z) != 0)) {
3750 temp = (PyLongObject *)long_sub(z, c);
3751 if (temp == NULL)
3752 goto Error;
3753 Py_DECREF(z);
3754 z = temp;
3755 temp = NULL;
3756 }
3757 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003758
Mark Dickinson22b20182010-05-10 21:27:53 +00003759 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 if (z != NULL) {
3761 Py_DECREF(z);
3762 z = NULL;
3763 }
3764 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003765 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3767 for (i = 0; i < 32; ++i)
3768 Py_XDECREF(table[i]);
3769 }
3770 Py_DECREF(a);
3771 Py_DECREF(b);
3772 Py_XDECREF(c);
3773 Py_XDECREF(temp);
3774 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003775}
3776
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003777static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003778long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 /* Implement ~x as -(x+1) */
3781 PyLongObject *x;
3782 PyLongObject *w;
3783 if (ABS(Py_SIZE(v)) <=1)
3784 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3785 w = (PyLongObject *)PyLong_FromLong(1L);
3786 if (w == NULL)
3787 return NULL;
3788 x = (PyLongObject *) long_add(v, w);
3789 Py_DECREF(w);
3790 if (x == NULL)
3791 return NULL;
3792 Py_SIZE(x) = -(Py_SIZE(x));
3793 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003794}
3795
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003796static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003797long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 PyLongObject *z;
3800 if (ABS(Py_SIZE(v)) <= 1)
3801 return PyLong_FromLong(-MEDIUM_VALUE(v));
3802 z = (PyLongObject *)_PyLong_Copy(v);
3803 if (z != NULL)
3804 Py_SIZE(z) = -(Py_SIZE(v));
3805 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003806}
3807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003808static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003809long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 if (Py_SIZE(v) < 0)
3812 return long_neg(v);
3813 else
3814 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003815}
3816
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003817static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003818long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003821}
3822
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003823static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003824long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 PyLongObject *z = NULL;
3827 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3828 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 if (Py_SIZE(a) < 0) {
3833 /* Right shifting negative numbers is harder */
3834 PyLongObject *a1, *a2;
3835 a1 = (PyLongObject *) long_invert(a);
3836 if (a1 == NULL)
3837 goto rshift_error;
3838 a2 = (PyLongObject *) long_rshift(a1, b);
3839 Py_DECREF(a1);
3840 if (a2 == NULL)
3841 goto rshift_error;
3842 z = (PyLongObject *) long_invert(a2);
3843 Py_DECREF(a2);
3844 }
3845 else {
3846 shiftby = PyLong_AsSsize_t((PyObject *)b);
3847 if (shiftby == -1L && PyErr_Occurred())
3848 goto rshift_error;
3849 if (shiftby < 0) {
3850 PyErr_SetString(PyExc_ValueError,
3851 "negative shift count");
3852 goto rshift_error;
3853 }
3854 wordshift = shiftby / PyLong_SHIFT;
3855 newsize = ABS(Py_SIZE(a)) - wordshift;
3856 if (newsize <= 0)
3857 return PyLong_FromLong(0);
3858 loshift = shiftby % PyLong_SHIFT;
3859 hishift = PyLong_SHIFT - loshift;
3860 lomask = ((digit)1 << hishift) - 1;
3861 himask = PyLong_MASK ^ lomask;
3862 z = _PyLong_New(newsize);
3863 if (z == NULL)
3864 goto rshift_error;
3865 if (Py_SIZE(a) < 0)
3866 Py_SIZE(z) = -(Py_SIZE(z));
3867 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3868 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3869 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003870 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 }
3872 z = long_normalize(z);
3873 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003874 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003876
Guido van Rossumc6913e71991-11-19 20:26:46 +00003877}
3878
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003879static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003880long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* This version due to Tim Peters */
3883 PyLongObject *a = (PyLongObject*)v;
3884 PyLongObject *b = (PyLongObject*)w;
3885 PyLongObject *z = NULL;
3886 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3887 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 shiftby = PyLong_AsSsize_t((PyObject *)b);
3892 if (shiftby == -1L && PyErr_Occurred())
3893 goto lshift_error;
3894 if (shiftby < 0) {
3895 PyErr_SetString(PyExc_ValueError, "negative shift count");
3896 goto lshift_error;
3897 }
3898 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3899 wordshift = shiftby / PyLong_SHIFT;
3900 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 oldsize = ABS(Py_SIZE(a));
3903 newsize = oldsize + wordshift;
3904 if (remshift)
3905 ++newsize;
3906 z = _PyLong_New(newsize);
3907 if (z == NULL)
3908 goto lshift_error;
3909 if (Py_SIZE(a) < 0)
3910 NEGATE(z);
3911 for (i = 0; i < wordshift; i++)
3912 z->ob_digit[i] = 0;
3913 accum = 0;
3914 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3915 accum |= (twodigits)a->ob_digit[j] << remshift;
3916 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3917 accum >>= PyLong_SHIFT;
3918 }
3919 if (remshift)
3920 z->ob_digit[newsize-1] = (digit)accum;
3921 else
3922 assert(!accum);
3923 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003924 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003925 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003926}
3927
Mark Dickinson27a87a22009-10-25 20:43:34 +00003928/* Compute two's complement of digit vector a[0:m], writing result to
3929 z[0:m]. The digit vector a need not be normalized, but should not
3930 be entirely zero. a and z may point to the same digit vector. */
3931
3932static void
3933v_complement(digit *z, digit *a, Py_ssize_t m)
3934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 Py_ssize_t i;
3936 digit carry = 1;
3937 for (i = 0; i < m; ++i) {
3938 carry += a[i] ^ PyLong_MASK;
3939 z[i] = carry & PyLong_MASK;
3940 carry >>= PyLong_SHIFT;
3941 }
3942 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003943}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003944
3945/* Bitwise and/xor/or operations */
3946
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003947static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003948long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003950 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 int nega, negb, negz;
3953 Py_ssize_t size_a, size_b, size_z, i;
3954 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 /* Bitwise operations for negative numbers operate as though
3957 on a two's complement representation. So convert arguments
3958 from sign-magnitude to two's complement, and convert the
3959 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 /* If a is negative, replace it by its two's complement. */
3962 size_a = ABS(Py_SIZE(a));
3963 nega = Py_SIZE(a) < 0;
3964 if (nega) {
3965 z = _PyLong_New(size_a);
3966 if (z == NULL)
3967 return NULL;
3968 v_complement(z->ob_digit, a->ob_digit, size_a);
3969 a = z;
3970 }
3971 else
3972 /* Keep reference count consistent. */
3973 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 /* Same for b. */
3976 size_b = ABS(Py_SIZE(b));
3977 negb = Py_SIZE(b) < 0;
3978 if (negb) {
3979 z = _PyLong_New(size_b);
3980 if (z == NULL) {
3981 Py_DECREF(a);
3982 return NULL;
3983 }
3984 v_complement(z->ob_digit, b->ob_digit, size_b);
3985 b = z;
3986 }
3987 else
3988 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003990 /* Swap a and b if necessary to ensure size_a >= size_b. */
3991 if (size_a < size_b) {
3992 z = a; a = b; b = z;
3993 size_z = size_a; size_a = size_b; size_b = size_z;
3994 negz = nega; nega = negb; negb = negz;
3995 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 /* JRH: The original logic here was to allocate the result value (z)
3998 as the longer of the two operands. However, there are some cases
3999 where the result is guaranteed to be shorter than that: AND of two
4000 positives, OR of two negatives: use the shorter number. AND with
4001 mixed signs: use the positive number. OR with mixed signs: use the
4002 negative number.
4003 */
4004 switch (op) {
4005 case '^':
4006 negz = nega ^ negb;
4007 size_z = size_a;
4008 break;
4009 case '&':
4010 negz = nega & negb;
4011 size_z = negb ? size_a : size_b;
4012 break;
4013 case '|':
4014 negz = nega | negb;
4015 size_z = negb ? size_b : size_a;
4016 break;
4017 default:
4018 PyErr_BadArgument();
4019 return NULL;
4020 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 /* We allow an extra digit if z is negative, to make sure that
4023 the final two's complement of z doesn't overflow. */
4024 z = _PyLong_New(size_z + negz);
4025 if (z == NULL) {
4026 Py_DECREF(a);
4027 Py_DECREF(b);
4028 return NULL;
4029 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 /* Compute digits for overlap of a and b. */
4032 switch(op) {
4033 case '&':
4034 for (i = 0; i < size_b; ++i)
4035 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4036 break;
4037 case '|':
4038 for (i = 0; i < size_b; ++i)
4039 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4040 break;
4041 case '^':
4042 for (i = 0; i < size_b; ++i)
4043 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4044 break;
4045 default:
4046 PyErr_BadArgument();
4047 return NULL;
4048 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 /* Copy any remaining digits of a, inverting if necessary. */
4051 if (op == '^' && negb)
4052 for (; i < size_z; ++i)
4053 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4054 else if (i < size_z)
4055 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4056 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004058 /* Complement result if negative. */
4059 if (negz) {
4060 Py_SIZE(z) = -(Py_SIZE(z));
4061 z->ob_digit[size_z] = PyLong_MASK;
4062 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4063 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 Py_DECREF(a);
4066 Py_DECREF(b);
4067 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004068}
4069
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004070static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004071long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004073 PyObject *c;
4074 CHECK_BINOP(a, b);
4075 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4076 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004077}
4078
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004079static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004080long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 PyObject *c;
4083 CHECK_BINOP(a, b);
4084 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4085 return c;
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_or(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 Rossum23d6f0e1991-05-14 12:06:49 +00004095}
4096
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004097static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004098long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 if (PyLong_CheckExact(v))
4101 Py_INCREF(v);
4102 else
4103 v = _PyLong_Copy((PyLongObject *)v);
4104 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004105}
4106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004107static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004108long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 double result;
4111 result = PyLong_AsDouble(v);
4112 if (result == -1.0 && PyErr_Occurred())
4113 return NULL;
4114 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004115}
4116
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004117static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004118long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004119
Tim Peters6d6c1a32001-08-02 04:15:00 +00004120static PyObject *
4121long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4122{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004123 PyObject *obase = NULL, *x = NULL;
4124 long base;
4125 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004126 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 if (type != &PyLong_Type)
4129 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004130 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4131 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004133 if (x == NULL) {
4134 if (obase != NULL) {
4135 PyErr_SetString(PyExc_TypeError,
4136 "int() missing string argument");
4137 return NULL;
4138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004140 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004141 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004143
4144 base = PyLong_AsLongAndOverflow(obase, &overflow);
4145 if (base == -1 && PyErr_Occurred())
4146 return NULL;
4147 if (overflow || (base != 0 && base < 2) || base > 36) {
4148 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004149 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004150 return NULL;
4151 }
4152
4153 if (PyUnicode_Check(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4155 PyUnicode_GET_SIZE(x),
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004156 (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4158 /* Since PyLong_FromString doesn't have a length parameter,
4159 * check here for possible NULs in the string. */
4160 char *string;
4161 Py_ssize_t size = Py_SIZE(x);
4162 if (PyByteArray_Check(x))
4163 string = PyByteArray_AS_STRING(x);
4164 else
4165 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004166 if (strlen(string) != (size_t)size || !size) {
4167 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 x is a bytes or buffer, *and* a base is given. */
4169 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004170 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004171 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004172 return NULL;
4173 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004174 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 }
4176 else {
4177 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004178 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 return NULL;
4180 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004181}
4182
Guido van Rossumbef14172001-08-29 15:47:46 +00004183/* Wimpy, slow approach to tp_new calls for subtypes of long:
4184 first create a regular long from whatever arguments we got,
4185 then allocate a subtype instance and initialize it from
4186 the regular long. The regular long is then thrown away.
4187*/
4188static PyObject *
4189long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004191 PyLongObject *tmp, *newobj;
4192 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 assert(PyType_IsSubtype(type, &PyLong_Type));
4195 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4196 if (tmp == NULL)
4197 return NULL;
4198 assert(PyLong_CheckExact(tmp));
4199 n = Py_SIZE(tmp);
4200 if (n < 0)
4201 n = -n;
4202 newobj = (PyLongObject *)type->tp_alloc(type, n);
4203 if (newobj == NULL) {
4204 Py_DECREF(tmp);
4205 return NULL;
4206 }
4207 assert(PyLong_Check(newobj));
4208 Py_SIZE(newobj) = Py_SIZE(tmp);
4209 for (i = 0; i < n; i++)
4210 newobj->ob_digit[i] = tmp->ob_digit[i];
4211 Py_DECREF(tmp);
4212 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004213}
4214
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004215static PyObject *
4216long_getnewargs(PyLongObject *v)
4217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004218 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004219}
4220
Guido van Rossumb43daf72007-08-01 18:08:08 +00004221static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004222long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004224}
4225
4226static PyObject *
4227long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004229}
4230
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004231static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004232long__format__(PyObject *self, PyObject *args)
4233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004234 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4237 return NULL;
4238 return _PyLong_FormatAdvanced(self,
4239 PyUnicode_AS_UNICODE(format_spec),
4240 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004241}
4242
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004243/* Return a pair (q, r) such that a = b * q + r, and
4244 abs(r) <= abs(b)/2, with equality possible only if q is even.
4245 In other words, q == a / b, rounded to the nearest integer using
4246 round-half-to-even. */
4247
4248PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004249_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004250{
4251 PyLongObject *quo = NULL, *rem = NULL;
4252 PyObject *one = NULL, *twice_rem, *result, *temp;
4253 int cmp, quo_is_odd, quo_is_neg;
4254
4255 /* Equivalent Python code:
4256
4257 def divmod_near(a, b):
4258 q, r = divmod(a, b)
4259 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4260 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4261 # positive, 2 * r < b if b negative.
4262 greater_than_half = 2*r > b if b > 0 else 2*r < b
4263 exactly_half = 2*r == b
4264 if greater_than_half or exactly_half and q % 2 == 1:
4265 q += 1
4266 r -= b
4267 return q, r
4268
4269 */
4270 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4271 PyErr_SetString(PyExc_TypeError,
4272 "non-integer arguments in division");
4273 return NULL;
4274 }
4275
4276 /* Do a and b have different signs? If so, quotient is negative. */
4277 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4278
4279 one = PyLong_FromLong(1L);
4280 if (one == NULL)
4281 return NULL;
4282
4283 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4284 goto error;
4285
4286 /* compare twice the remainder with the divisor, to see
4287 if we need to adjust the quotient and remainder */
4288 twice_rem = long_lshift((PyObject *)rem, one);
4289 if (twice_rem == NULL)
4290 goto error;
4291 if (quo_is_neg) {
4292 temp = long_neg((PyLongObject*)twice_rem);
4293 Py_DECREF(twice_rem);
4294 twice_rem = temp;
4295 if (twice_rem == NULL)
4296 goto error;
4297 }
4298 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4299 Py_DECREF(twice_rem);
4300
4301 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4302 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4303 /* fix up quotient */
4304 if (quo_is_neg)
4305 temp = long_sub(quo, (PyLongObject *)one);
4306 else
4307 temp = long_add(quo, (PyLongObject *)one);
4308 Py_DECREF(quo);
4309 quo = (PyLongObject *)temp;
4310 if (quo == NULL)
4311 goto error;
4312 /* and remainder */
4313 if (quo_is_neg)
4314 temp = long_add(rem, (PyLongObject *)b);
4315 else
4316 temp = long_sub(rem, (PyLongObject *)b);
4317 Py_DECREF(rem);
4318 rem = (PyLongObject *)temp;
4319 if (rem == NULL)
4320 goto error;
4321 }
4322
4323 result = PyTuple_New(2);
4324 if (result == NULL)
4325 goto error;
4326
4327 /* PyTuple_SET_ITEM steals references */
4328 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4329 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4330 Py_DECREF(one);
4331 return result;
4332
4333 error:
4334 Py_XDECREF(quo);
4335 Py_XDECREF(rem);
4336 Py_XDECREF(one);
4337 return NULL;
4338}
4339
Eric Smith8c663262007-08-25 02:26:07 +00004340static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004341long_round(PyObject *self, PyObject *args)
4342{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004343 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004344
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004345 /* To round an integer m to the nearest 10**n (n positive), we make use of
4346 * the divmod_near operation, defined by:
4347 *
4348 * divmod_near(a, b) = (q, r)
4349 *
4350 * where q is the nearest integer to the quotient a / b (the
4351 * nearest even integer in the case of a tie) and r == a - q * b.
4352 * Hence q * b = a - r is the nearest multiple of b to a,
4353 * preferring even multiples in the case of a tie.
4354 *
4355 * So the nearest multiple of 10**n to m is:
4356 *
4357 * m - divmod_near(m, 10**n)[1].
4358 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4360 return NULL;
4361 if (o_ndigits == NULL)
4362 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004363
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004364 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 if (ndigits == NULL)
4366 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004367
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004368 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 if (Py_SIZE(ndigits) >= 0) {
4370 Py_DECREF(ndigits);
4371 return long_long(self);
4372 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004373
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004374 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4375 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004377 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004379 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004380
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004381 result = PyLong_FromLong(10L);
4382 if (result == NULL) {
4383 Py_DECREF(ndigits);
4384 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004386
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004387 temp = long_pow(result, ndigits, Py_None);
4388 Py_DECREF(ndigits);
4389 Py_DECREF(result);
4390 result = temp;
4391 if (result == NULL)
4392 return NULL;
4393
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004394 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004395 Py_DECREF(result);
4396 result = temp;
4397 if (result == NULL)
4398 return NULL;
4399
4400 temp = long_sub((PyLongObject *)self,
4401 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4402 Py_DECREF(result);
4403 result = temp;
4404
4405 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004406}
4407
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004408static PyObject *
4409long_sizeof(PyLongObject *v)
4410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4414 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004415}
4416
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004417static PyObject *
4418long_bit_length(PyLongObject *v)
4419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 PyLongObject *result, *x, *y;
4421 Py_ssize_t ndigits, msd_bits = 0;
4422 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 assert(v != NULL);
4425 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 ndigits = ABS(Py_SIZE(v));
4428 if (ndigits == 0)
4429 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 msd = v->ob_digit[ndigits-1];
4432 while (msd >= 32) {
4433 msd_bits += 6;
4434 msd >>= 6;
4435 }
4436 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4439 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 /* expression above may overflow; use Python integers instead */
4442 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4443 if (result == NULL)
4444 return NULL;
4445 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4446 if (x == NULL)
4447 goto error;
4448 y = (PyLongObject *)long_mul(result, x);
4449 Py_DECREF(x);
4450 if (y == NULL)
4451 goto error;
4452 Py_DECREF(result);
4453 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4456 if (x == NULL)
4457 goto error;
4458 y = (PyLongObject *)long_add(result, x);
4459 Py_DECREF(x);
4460 if (y == NULL)
4461 goto error;
4462 Py_DECREF(result);
4463 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004466
Mark Dickinson22b20182010-05-10 21:27:53 +00004467 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004468 Py_DECREF(result);
4469 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004470}
4471
4472PyDoc_STRVAR(long_bit_length_doc,
4473"int.bit_length() -> int\n\
4474\n\
4475Number of bits necessary to represent self in binary.\n\
4476>>> bin(37)\n\
4477'0b100101'\n\
4478>>> (37).bit_length()\n\
44796");
4480
Christian Heimes53876d92008-04-19 00:31:39 +00004481#if 0
4482static PyObject *
4483long_is_finite(PyObject *v)
4484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004486}
4487#endif
4488
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004489
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004490static PyObject *
4491long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 PyObject *byteorder_str;
4494 PyObject *is_signed_obj = NULL;
4495 Py_ssize_t length;
4496 int little_endian;
4497 int is_signed;
4498 PyObject *bytes;
4499 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4502 &length, &byteorder_str,
4503 &is_signed_obj))
4504 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 if (args != NULL && Py_SIZE(args) > 2) {
4507 PyErr_SetString(PyExc_TypeError,
4508 "'signed' is a keyword-only argument");
4509 return NULL;
4510 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004512 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4513 little_endian = 1;
4514 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4515 little_endian = 0;
4516 else {
4517 PyErr_SetString(PyExc_ValueError,
4518 "byteorder must be either 'little' or 'big'");
4519 return NULL;
4520 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 if (is_signed_obj != NULL) {
4523 int cmp = PyObject_IsTrue(is_signed_obj);
4524 if (cmp < 0)
4525 return NULL;
4526 is_signed = cmp ? 1 : 0;
4527 }
4528 else {
4529 /* If the signed argument was omitted, use False as the
4530 default. */
4531 is_signed = 0;
4532 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 if (length < 0) {
4535 PyErr_SetString(PyExc_ValueError,
4536 "length argument must be non-negative");
4537 return NULL;
4538 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004540 bytes = PyBytes_FromStringAndSize(NULL, length);
4541 if (bytes == NULL)
4542 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4545 length, little_endian, is_signed) < 0) {
4546 Py_DECREF(bytes);
4547 return NULL;
4548 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004550 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004551}
4552
Mark Dickinson078c2532010-01-30 18:06:17 +00004553PyDoc_STRVAR(long_to_bytes_doc,
4554"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004555\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004556Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004557\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004558The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004559raised if the integer is not representable with the given number of\n\
4560bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004561\n\
4562The byteorder argument determines the byte order used to represent the\n\
4563integer. If byteorder is 'big', the most significant byte is at the\n\
4564beginning of the byte array. If byteorder is 'little', the most\n\
4565significant byte is at the end of the byte array. To request the native\n\
4566byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4567\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004568The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004570is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004571
4572static PyObject *
4573long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 PyObject *byteorder_str;
4576 PyObject *is_signed_obj = NULL;
4577 int little_endian;
4578 int is_signed;
4579 PyObject *obj;
4580 PyObject *bytes;
4581 PyObject *long_obj;
4582 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4585 &obj, &byteorder_str,
4586 &is_signed_obj))
4587 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (args != NULL && Py_SIZE(args) > 2) {
4590 PyErr_SetString(PyExc_TypeError,
4591 "'signed' is a keyword-only argument");
4592 return NULL;
4593 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4596 little_endian = 1;
4597 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4598 little_endian = 0;
4599 else {
4600 PyErr_SetString(PyExc_ValueError,
4601 "byteorder must be either 'little' or 'big'");
4602 return NULL;
4603 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 if (is_signed_obj != NULL) {
4606 int cmp = PyObject_IsTrue(is_signed_obj);
4607 if (cmp < 0)
4608 return NULL;
4609 is_signed = cmp ? 1 : 0;
4610 }
4611 else {
4612 /* If the signed argument was omitted, use False as the
4613 default. */
4614 is_signed = 0;
4615 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 bytes = PyObject_Bytes(obj);
4618 if (bytes == NULL)
4619 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 long_obj = _PyLong_FromByteArray(
4622 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4623 little_endian, is_signed);
4624 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 /* If from_bytes() was used on subclass, allocate new subclass
4627 * instance, initialize it with decoded long value and return it.
4628 */
4629 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4630 PyLongObject *newobj;
4631 int i;
4632 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 newobj = (PyLongObject *)type->tp_alloc(type, n);
4635 if (newobj == NULL) {
4636 Py_DECREF(long_obj);
4637 return NULL;
4638 }
4639 assert(PyLong_Check(newobj));
4640 Py_SIZE(newobj) = Py_SIZE(long_obj);
4641 for (i = 0; i < n; i++) {
4642 newobj->ob_digit[i] =
4643 ((PyLongObject *)long_obj)->ob_digit[i];
4644 }
4645 Py_DECREF(long_obj);
4646 return (PyObject *)newobj;
4647 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004650}
4651
Mark Dickinson078c2532010-01-30 18:06:17 +00004652PyDoc_STRVAR(long_from_bytes_doc,
4653"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4654\n\
4655Return the integer represented by the given array of bytes.\n\
4656\n\
4657The bytes argument must either support the buffer protocol or be an\n\
4658iterable object producing bytes. Bytes and bytearray are examples of\n\
4659built-in objects that support the buffer protocol.\n\
4660\n\
4661The byteorder argument determines the byte order used to represent the\n\
4662integer. If byteorder is 'big', the most significant byte is at the\n\
4663beginning of the byte array. If byteorder is 'little', the most\n\
4664significant byte is at the end of the byte array. To request the native\n\
4665byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4666\n\
4667The signed keyword-only argument indicates whether two's complement is\n\
4668used to represent the integer.");
4669
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004670static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4672 "Returns self, the complex conjugate of any int."},
4673 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4674 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004675#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4677 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004678#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 {"to_bytes", (PyCFunction)long_to_bytes,
4680 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4681 {"from_bytes", (PyCFunction)long_from_bytes,
4682 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4683 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4684 "Truncating an Integral returns itself."},
4685 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4686 "Flooring an Integral returns itself."},
4687 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4688 "Ceiling of an Integral returns itself."},
4689 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4690 "Rounding an Integral returns itself.\n"
4691 "Rounding with an ndigits argument also returns an integer."},
4692 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4693 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4694 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4695 "Returns size in memory, in bytes"},
4696 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004697};
4698
Guido van Rossumb43daf72007-08-01 18:08:08 +00004699static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004700 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004701 (getter)long_long, (setter)NULL,
4702 "the real part of a complex number",
4703 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004704 {"imag",
4705 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004706 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004707 NULL},
4708 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004709 (getter)long_long, (setter)NULL,
4710 "the numerator of a rational number in lowest terms",
4711 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004712 {"denominator",
4713 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004714 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004715 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004716 {NULL} /* Sentinel */
4717};
4718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004719PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004720"int(x=0) -> integer\n\
4721int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004722\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004723Convert a number or string to an integer, or return 0 if no arguments\n\
4724are given. If x is a number, return x.__int__(). For floating point\n\
4725numbers, this truncates towards zero.\n\
4726\n\
4727If x is not a number or if base is given, then x must be a string,\n\
4728bytes, or bytearray instance representing an integer literal in the\n\
4729given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4730by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4731Base 0 means to interpret the base from the string as an integer literal.\n\
4732>>> int('0b100', base=0)\n\
47334");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004734
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004735static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004736 (binaryfunc)long_add, /*nb_add*/
4737 (binaryfunc)long_sub, /*nb_subtract*/
4738 (binaryfunc)long_mul, /*nb_multiply*/
4739 long_mod, /*nb_remainder*/
4740 long_divmod, /*nb_divmod*/
4741 long_pow, /*nb_power*/
4742 (unaryfunc)long_neg, /*nb_negative*/
4743 (unaryfunc)long_long, /*tp_positive*/
4744 (unaryfunc)long_abs, /*tp_absolute*/
4745 (inquiry)long_bool, /*tp_bool*/
4746 (unaryfunc)long_invert, /*nb_invert*/
4747 long_lshift, /*nb_lshift*/
4748 (binaryfunc)long_rshift, /*nb_rshift*/
4749 long_and, /*nb_and*/
4750 long_xor, /*nb_xor*/
4751 long_or, /*nb_or*/
4752 long_long, /*nb_int*/
4753 0, /*nb_reserved*/
4754 long_float, /*nb_float*/
4755 0, /* nb_inplace_add */
4756 0, /* nb_inplace_subtract */
4757 0, /* nb_inplace_multiply */
4758 0, /* nb_inplace_remainder */
4759 0, /* nb_inplace_power */
4760 0, /* nb_inplace_lshift */
4761 0, /* nb_inplace_rshift */
4762 0, /* nb_inplace_and */
4763 0, /* nb_inplace_xor */
4764 0, /* nb_inplace_or */
4765 long_div, /* nb_floor_divide */
4766 long_true_divide, /* nb_true_divide */
4767 0, /* nb_inplace_floor_divide */
4768 0, /* nb_inplace_true_divide */
4769 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004770};
4771
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004772PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4774 "int", /* tp_name */
4775 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4776 sizeof(digit), /* tp_itemsize */
4777 long_dealloc, /* tp_dealloc */
4778 0, /* tp_print */
4779 0, /* tp_getattr */
4780 0, /* tp_setattr */
4781 0, /* tp_reserved */
4782 long_to_decimal_string, /* tp_repr */
4783 &long_as_number, /* tp_as_number */
4784 0, /* tp_as_sequence */
4785 0, /* tp_as_mapping */
4786 (hashfunc)long_hash, /* tp_hash */
4787 0, /* tp_call */
4788 long_to_decimal_string, /* tp_str */
4789 PyObject_GenericGetAttr, /* tp_getattro */
4790 0, /* tp_setattro */
4791 0, /* tp_as_buffer */
4792 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4793 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4794 long_doc, /* tp_doc */
4795 0, /* tp_traverse */
4796 0, /* tp_clear */
4797 long_richcompare, /* tp_richcompare */
4798 0, /* tp_weaklistoffset */
4799 0, /* tp_iter */
4800 0, /* tp_iternext */
4801 long_methods, /* tp_methods */
4802 0, /* tp_members */
4803 long_getset, /* tp_getset */
4804 0, /* tp_base */
4805 0, /* tp_dict */
4806 0, /* tp_descr_get */
4807 0, /* tp_descr_set */
4808 0, /* tp_dictoffset */
4809 0, /* tp_init */
4810 0, /* tp_alloc */
4811 long_new, /* tp_new */
4812 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004813};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004814
Mark Dickinsonbd792642009-03-18 20:06:12 +00004815static PyTypeObject Int_InfoType;
4816
4817PyDoc_STRVAR(int_info__doc__,
4818"sys.int_info\n\
4819\n\
4820A struct sequence that holds information about Python's\n\
4821internal representation of integers. The attributes are read only.");
4822
4823static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004825 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004826 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004827};
4828
4829static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 "sys.int_info", /* name */
4831 int_info__doc__, /* doc */
4832 int_info_fields, /* fields */
4833 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004834};
4835
4836PyObject *
4837PyLong_GetInfo(void)
4838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 PyObject* int_info;
4840 int field = 0;
4841 int_info = PyStructSequence_New(&Int_InfoType);
4842 if (int_info == NULL)
4843 return NULL;
4844 PyStructSequence_SET_ITEM(int_info, field++,
4845 PyLong_FromLong(PyLong_SHIFT));
4846 PyStructSequence_SET_ITEM(int_info, field++,
4847 PyLong_FromLong(sizeof(digit)));
4848 if (PyErr_Occurred()) {
4849 Py_CLEAR(int_info);
4850 return NULL;
4851 }
4852 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004853}
4854
Guido van Rossumddefaf32007-01-14 03:31:43 +00004855int
4856_PyLong_Init(void)
4857{
4858#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004859 int ival, size;
4860 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004862 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4863 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4864 if (Py_TYPE(v) == &PyLong_Type) {
4865 /* The element is already initialized, most likely
4866 * the Python interpreter was initialized before.
4867 */
4868 Py_ssize_t refcnt;
4869 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004871 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4872 _Py_NewReference(op);
4873 /* _Py_NewReference sets the ref count to 1 but
4874 * the ref count might be larger. Set the refcnt
4875 * to the original refcnt + 1 */
4876 Py_REFCNT(op) = refcnt + 1;
4877 assert(Py_SIZE(op) == size);
4878 assert(v->ob_digit[0] == abs(ival));
4879 }
4880 else {
4881 PyObject_INIT(v, &PyLong_Type);
4882 }
4883 Py_SIZE(v) = size;
4884 v->ob_digit[0] = abs(ival);
4885 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004886#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 /* initialize int_info */
4888 if (Int_InfoType.tp_name == 0)
4889 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004892}
4893
4894void
4895PyLong_Fini(void)
4896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 /* Integers are currently statically allocated. Py_DECREF is not
4898 needed, but Python must forget about the reference or multiple
4899 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004900#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004901 int i;
4902 PyLongObject *v = small_ints;
4903 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4904 _Py_DEC_REFTOTAL;
4905 _Py_ForgetReference((PyObject*)v);
4906 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004907#endif
4908}