blob: dfedfb7bfec4c5197764154eb0c95936e9288a6e [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{
Tim Peters70128a12001-06-16 08:48:40 +0000929#ifndef HAVE_LONG_LONG
930# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
931#endif
932#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000933# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000934#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* special-case null pointer */
936 if (!p)
937 return PyLong_FromLong(0);
938 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000939
Guido van Rossum78694d91998-09-18 14:14:13 +0000940}
941
942/* Get a C pointer from a long object (or an int object in some cases) */
943
944void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000945PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* This function will allow int or long objects. If vv is neither,
948 then the PyLong_AsLong*() functions will raise the exception:
949 PyExc_SystemError, "bad argument to internal function"
950 */
Tim Peters70128a12001-06-16 08:48:40 +0000951#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
955 x = PyLong_AsLong(vv);
956 else
957 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000958#else
Tim Peters70128a12001-06-16 08:48:40 +0000959
960#ifndef HAVE_LONG_LONG
961# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
962#endif
963#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000964# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000965#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
969 x = PyLong_AsLongLong(vv);
970 else
971 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000972
973#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 if (x == -1 && PyErr_Occurred())
976 return NULL;
977 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000978}
979
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000980#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000981
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000982/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000983 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000984 */
985
Tim Peterscf37dfc2001-06-14 18:42:50 +0000986#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000987#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000988
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000989/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000990
991PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000992PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyLongObject *v;
995 unsigned PY_LONG_LONG abs_ival;
996 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
997 int ndigits = 0;
998 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 CHECK_SMALL_INT(ival);
1001 if (ival < 0) {
1002 /* avoid signed overflow on negation; see comments
1003 in PyLong_FromLong above. */
1004 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1005 negative = 1;
1006 }
1007 else {
1008 abs_ival = (unsigned PY_LONG_LONG)ival;
1009 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* Count the number of Python digits.
1012 We used to pick 5 ("big enough for anything"), but that's a
1013 waste of time and space given that 5*15 = 75 bits are rarely
1014 needed. */
1015 t = abs_ival;
1016 while (t) {
1017 ++ndigits;
1018 t >>= PyLong_SHIFT;
1019 }
1020 v = _PyLong_New(ndigits);
1021 if (v != NULL) {
1022 digit *p = v->ob_digit;
1023 Py_SIZE(v) = negative ? -ndigits : ndigits;
1024 t = abs_ival;
1025 while (t) {
1026 *p++ = (digit)(t & PyLong_MASK);
1027 t >>= PyLong_SHIFT;
1028 }
1029 }
1030 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001031}
1032
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001033/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001034
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001035PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001036PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyLongObject *v;
1039 unsigned PY_LONG_LONG t;
1040 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (ival < PyLong_BASE)
1043 return PyLong_FromLong((long)ival);
1044 /* Count the number of Python digits. */
1045 t = (unsigned PY_LONG_LONG)ival;
1046 while (t) {
1047 ++ndigits;
1048 t >>= PyLong_SHIFT;
1049 }
1050 v = _PyLong_New(ndigits);
1051 if (v != NULL) {
1052 digit *p = v->ob_digit;
1053 Py_SIZE(v) = ndigits;
1054 while (ival) {
1055 *p++ = (digit)(ival & PyLong_MASK);
1056 ival >>= PyLong_SHIFT;
1057 }
1058 }
1059 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001060}
1061
Martin v. Löwis18e16552006-02-15 17:27:45 +00001062/* Create a new long int object from a C Py_ssize_t. */
1063
1064PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001065PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyLongObject *v;
1068 size_t abs_ival;
1069 size_t t; /* unsigned so >> doesn't propagate sign bit */
1070 int ndigits = 0;
1071 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 CHECK_SMALL_INT(ival);
1074 if (ival < 0) {
1075 /* avoid signed overflow when ival = SIZE_T_MIN */
1076 abs_ival = (size_t)(-1-ival)+1;
1077 negative = 1;
1078 }
1079 else {
1080 abs_ival = (size_t)ival;
1081 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 /* Count the number of Python digits. */
1084 t = abs_ival;
1085 while (t) {
1086 ++ndigits;
1087 t >>= PyLong_SHIFT;
1088 }
1089 v = _PyLong_New(ndigits);
1090 if (v != NULL) {
1091 digit *p = v->ob_digit;
1092 Py_SIZE(v) = negative ? -ndigits : ndigits;
1093 t = abs_ival;
1094 while (t) {
1095 *p++ = (digit)(t & PyLong_MASK);
1096 t >>= PyLong_SHIFT;
1097 }
1098 }
1099 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001100}
1101
1102/* Create a new long int object from a C size_t. */
1103
1104PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001105PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 PyLongObject *v;
1108 size_t t;
1109 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (ival < PyLong_BASE)
1112 return PyLong_FromLong((long)ival);
1113 /* Count the number of Python digits. */
1114 t = ival;
1115 while (t) {
1116 ++ndigits;
1117 t >>= PyLong_SHIFT;
1118 }
1119 v = _PyLong_New(ndigits);
1120 if (v != NULL) {
1121 digit *p = v->ob_digit;
1122 Py_SIZE(v) = ndigits;
1123 while (ival) {
1124 *p++ = (digit)(ival & PyLong_MASK);
1125 ival >>= PyLong_SHIFT;
1126 }
1127 }
1128 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001129}
1130
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001131/* Get a C PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001132 Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001133
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001134PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001135PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyLongObject *v;
1138 PY_LONG_LONG bytes;
1139 int one = 1;
1140 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (vv == NULL) {
1143 PyErr_BadInternalCall();
1144 return -1;
1145 }
1146 if (!PyLong_Check(vv)) {
1147 PyNumberMethods *nb;
1148 PyObject *io;
1149 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1150 nb->nb_int == NULL) {
1151 PyErr_SetString(PyExc_TypeError, "an integer is required");
1152 return -1;
1153 }
1154 io = (*nb->nb_int) (vv);
1155 if (io == NULL)
1156 return -1;
1157 if (PyLong_Check(io)) {
1158 bytes = PyLong_AsLongLong(io);
1159 Py_DECREF(io);
1160 return bytes;
1161 }
1162 Py_DECREF(io);
1163 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1164 return -1;
1165 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 v = (PyLongObject*)vv;
1168 switch(Py_SIZE(v)) {
1169 case -1: return -(sdigit)v->ob_digit[0];
1170 case 0: return 0;
1171 case 1: return v->ob_digit[0];
1172 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001173 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1174 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1177 if (res < 0)
1178 return (PY_LONG_LONG)-1;
1179 else
1180 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001181}
1182
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001183/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001184 Return -1 and set an error if overflow occurs. */
1185
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001186unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001187PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 PyLongObject *v;
1190 unsigned PY_LONG_LONG bytes;
1191 int one = 1;
1192 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (vv == NULL || !PyLong_Check(vv)) {
1195 PyErr_BadInternalCall();
1196 return (unsigned PY_LONG_LONG)-1;
1197 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 v = (PyLongObject*)vv;
1200 switch(Py_SIZE(v)) {
1201 case 0: return 0;
1202 case 1: return v->ob_digit[0];
1203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001204
Mark Dickinson22b20182010-05-10 21:27:53 +00001205 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1206 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1209 if (res < 0)
1210 return (unsigned PY_LONG_LONG)res;
1211 else
1212 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001213}
Tim Petersd1a7da62001-06-13 00:35:57 +00001214
Thomas Hellera4ea6032003-04-17 18:55:45 +00001215/* Get a C unsigned long int from a long int object, ignoring the high bits.
1216 Returns -1 and sets an error condition if an error occurs. */
1217
Guido van Rossumddefaf32007-01-14 03:31:43 +00001218static unsigned PY_LONG_LONG
1219_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 register PyLongObject *v;
1222 unsigned PY_LONG_LONG x;
1223 Py_ssize_t i;
1224 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (vv == NULL || !PyLong_Check(vv)) {
1227 PyErr_BadInternalCall();
1228 return (unsigned long) -1;
1229 }
1230 v = (PyLongObject *)vv;
1231 switch(Py_SIZE(v)) {
1232 case 0: return 0;
1233 case 1: return v->ob_digit[0];
1234 }
1235 i = Py_SIZE(v);
1236 sign = 1;
1237 x = 0;
1238 if (i < 0) {
1239 sign = -1;
1240 i = -i;
1241 }
1242 while (--i >= 0) {
1243 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1244 }
1245 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001247
1248unsigned PY_LONG_LONG
1249PyLong_AsUnsignedLongLongMask(register PyObject *op)
1250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyNumberMethods *nb;
1252 PyLongObject *lo;
1253 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (op && PyLong_Check(op))
1256 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1259 nb->nb_int == NULL) {
1260 PyErr_SetString(PyExc_TypeError, "an integer is required");
1261 return (unsigned PY_LONG_LONG)-1;
1262 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 lo = (PyLongObject*) (*nb->nb_int) (op);
1265 if (lo == NULL)
1266 return (unsigned PY_LONG_LONG)-1;
1267 if (PyLong_Check(lo)) {
1268 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1269 Py_DECREF(lo);
1270 if (PyErr_Occurred())
1271 return (unsigned PY_LONG_LONG)-1;
1272 return val;
1273 }
1274 else
1275 {
1276 Py_DECREF(lo);
1277 PyErr_SetString(PyExc_TypeError,
1278 "nb_int should return int object");
1279 return (unsigned PY_LONG_LONG)-1;
1280 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001281}
Tim Petersd1a7da62001-06-13 00:35:57 +00001282#undef IS_LITTLE_ENDIAN
1283
Mark Dickinson93f562c2010-01-30 10:30:15 +00001284/* Get a C long long int from a Python long or Python int object.
1285 On overflow, returns -1 and sets *overflow to 1 or -1 depending
1286 on the sign of the result. Otherwise *overflow is 0.
1287
1288 For other errors (e.g., type error), returns -1 and sets an error
1289 condition.
1290*/
1291
1292PY_LONG_LONG
1293PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 /* This version by Tim Peters */
1296 register PyLongObject *v;
1297 unsigned PY_LONG_LONG x, prev;
1298 PY_LONG_LONG res;
1299 Py_ssize_t i;
1300 int sign;
1301 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 *overflow = 0;
1304 if (vv == NULL) {
1305 PyErr_BadInternalCall();
1306 return -1;
1307 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (!PyLong_Check(vv)) {
1310 PyNumberMethods *nb;
1311 nb = vv->ob_type->tp_as_number;
1312 if (nb == NULL || nb->nb_int == NULL) {
1313 PyErr_SetString(PyExc_TypeError,
1314 "an integer is required");
1315 return -1;
1316 }
1317 vv = (*nb->nb_int) (vv);
1318 if (vv == NULL)
1319 return -1;
1320 do_decref = 1;
1321 if (!PyLong_Check(vv)) {
1322 Py_DECREF(vv);
1323 PyErr_SetString(PyExc_TypeError,
1324 "nb_int should return int object");
1325 return -1;
1326 }
1327 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 res = -1;
1330 v = (PyLongObject *)vv;
1331 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 switch (i) {
1334 case -1:
1335 res = -(sdigit)v->ob_digit[0];
1336 break;
1337 case 0:
1338 res = 0;
1339 break;
1340 case 1:
1341 res = v->ob_digit[0];
1342 break;
1343 default:
1344 sign = 1;
1345 x = 0;
1346 if (i < 0) {
1347 sign = -1;
1348 i = -(i);
1349 }
1350 while (--i >= 0) {
1351 prev = x;
1352 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1353 if ((x >> PyLong_SHIFT) != prev) {
1354 *overflow = sign;
1355 goto exit;
1356 }
1357 }
1358 /* Haven't lost any bits, but casting to long requires extra
1359 * care (see comment above).
1360 */
1361 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1362 res = (PY_LONG_LONG)x * sign;
1363 }
1364 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1365 res = PY_LLONG_MIN;
1366 }
1367 else {
1368 *overflow = sign;
1369 /* res is already set to -1 */
1370 }
1371 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001372 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 if (do_decref) {
1374 Py_DECREF(vv);
1375 }
1376 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001377}
1378
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001379#endif /* HAVE_LONG_LONG */
1380
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001381#define CHECK_BINOP(v,w) \
1382 do { \
1383 if (!PyLong_Check(v) || !PyLong_Check(w)) { \
1384 Py_INCREF(Py_NotImplemented); \
1385 return Py_NotImplemented; \
1386 } \
1387 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001388
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001389/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1390 2**k if d is nonzero, else 0. */
1391
1392static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1394 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001395};
1396
1397static int
1398bits_in_digit(digit d)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 int d_bits = 0;
1401 while (d >= 32) {
1402 d_bits += 6;
1403 d >>= 6;
1404 }
1405 d_bits += (int)BitLengthTable[d];
1406 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001407}
1408
Tim Peters877a2122002-08-12 05:09:36 +00001409/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1410 * is modified in place, by adding y to it. Carries are propagated as far as
1411 * x[m-1], and the remaining carry (0 or 1) is returned.
1412 */
1413static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001414v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 Py_ssize_t i;
1417 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 assert(m >= n);
1420 for (i = 0; i < n; ++i) {
1421 carry += x[i] + y[i];
1422 x[i] = carry & PyLong_MASK;
1423 carry >>= PyLong_SHIFT;
1424 assert((carry & 1) == carry);
1425 }
1426 for (; carry && i < m; ++i) {
1427 carry += x[i];
1428 x[i] = carry & PyLong_MASK;
1429 carry >>= PyLong_SHIFT;
1430 assert((carry & 1) == carry);
1431 }
1432 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001433}
1434
1435/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1436 * is modified in place, by subtracting y from it. Borrows are propagated as
1437 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1438 */
1439static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001440v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 Py_ssize_t i;
1443 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 assert(m >= n);
1446 for (i = 0; i < n; ++i) {
1447 borrow = x[i] - y[i] - borrow;
1448 x[i] = borrow & PyLong_MASK;
1449 borrow >>= PyLong_SHIFT;
1450 borrow &= 1; /* keep only 1 sign bit */
1451 }
1452 for (; borrow && i < m; ++i) {
1453 borrow = x[i] - borrow;
1454 x[i] = borrow & PyLong_MASK;
1455 borrow >>= PyLong_SHIFT;
1456 borrow &= 1;
1457 }
1458 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001459}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001460
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001461/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1462 * result in z[0:m], and return the d bits shifted out of the top.
1463 */
1464static digit
1465v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 Py_ssize_t i;
1468 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 assert(0 <= d && d < PyLong_SHIFT);
1471 for (i=0; i < m; i++) {
1472 twodigits acc = (twodigits)a[i] << d | carry;
1473 z[i] = (digit)acc & PyLong_MASK;
1474 carry = (digit)(acc >> PyLong_SHIFT);
1475 }
1476 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001477}
1478
1479/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1480 * result in z[0:m], and return the d bits shifted out of the bottom.
1481 */
1482static digit
1483v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_ssize_t i;
1486 digit carry = 0;
1487 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 assert(0 <= d && d < PyLong_SHIFT);
1490 for (i=m; i-- > 0;) {
1491 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1492 carry = (digit)acc & mask;
1493 z[i] = (digit)(acc >> d);
1494 }
1495 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001496}
1497
Tim Peters212e6142001-07-14 12:23:19 +00001498/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1499 in pout, and returning the remainder. pin and pout point at the LSD.
1500 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001501 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001502 immutable. */
1503
1504static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001505inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 assert(n > 0 && n <= PyLong_MASK);
1510 pin += size;
1511 pout += size;
1512 while (--size >= 0) {
1513 digit hi;
1514 rem = (rem << PyLong_SHIFT) | *--pin;
1515 *--pout = hi = (digit)(rem / n);
1516 rem -= (twodigits)hi * n;
1517 }
1518 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001519}
1520
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001521/* Divide a long integer by a digit, returning both the quotient
1522 (as function result) and the remainder (through *prem).
1523 The sign of a is ignored; n should not be zero. */
1524
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001525static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001526divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 const Py_ssize_t size = ABS(Py_SIZE(a));
1529 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 assert(n > 0 && n <= PyLong_MASK);
1532 z = _PyLong_New(size);
1533 if (z == NULL)
1534 return NULL;
1535 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1536 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001537}
1538
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001539/* Convert a long integer to a base 10 string. Returns a new non-shared
1540 string. (Return value is non-shared so that callers can modify the
1541 returned value if necessary.) */
1542
1543static PyObject *
1544long_to_decimal_string(PyObject *aa)
1545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 PyLongObject *scratch, *a;
1547 PyObject *str;
1548 Py_ssize_t size, strlen, size_a, i, j;
1549 digit *pout, *pin, rem, tenpow;
1550 Py_UNICODE *p;
1551 int negative;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 a = (PyLongObject *)aa;
1554 if (a == NULL || !PyLong_Check(a)) {
1555 PyErr_BadInternalCall();
1556 return NULL;
1557 }
1558 size_a = ABS(Py_SIZE(a));
1559 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* quick and dirty upper bound for the number of digits
1562 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 But log2(a) < size_a * PyLong_SHIFT, and
1567 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1568 > 3 * _PyLong_DECIMAL_SHIFT
1569 */
1570 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1571 PyErr_SetString(PyExc_OverflowError,
1572 "long is too large to format");
1573 return NULL;
1574 }
1575 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1576 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1577 scratch = _PyLong_New(size);
1578 if (scratch == NULL)
1579 return NULL;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 /* convert array of base _PyLong_BASE digits in pin to an array of
1582 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1583 Volume 2 (3rd edn), section 4.4, Method 1b). */
1584 pin = a->ob_digit;
1585 pout = scratch->ob_digit;
1586 size = 0;
1587 for (i = size_a; --i >= 0; ) {
1588 digit hi = pin[i];
1589 for (j = 0; j < size; j++) {
1590 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1591 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1592 pout[j] = (digit)(z - (twodigits)hi *
1593 _PyLong_DECIMAL_BASE);
1594 }
1595 while (hi) {
1596 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1597 hi /= _PyLong_DECIMAL_BASE;
1598 }
1599 /* check for keyboard interrupt */
1600 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001601 Py_DECREF(scratch);
1602 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001603 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 }
1605 /* pout should have at least one digit, so that the case when a = 0
1606 works correctly */
1607 if (size == 0)
1608 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 /* calculate exact length of output string, and allocate */
1611 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1612 tenpow = 10;
1613 rem = pout[size-1];
1614 while (rem >= tenpow) {
1615 tenpow *= 10;
1616 strlen++;
1617 }
1618 str = PyUnicode_FromUnicode(NULL, strlen);
1619 if (str == NULL) {
1620 Py_DECREF(scratch);
1621 return NULL;
1622 }
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 /* fill the string right-to-left */
1625 p = PyUnicode_AS_UNICODE(str) + strlen;
1626 *p = '\0';
1627 /* pout[0] through pout[size-2] contribute exactly
1628 _PyLong_DECIMAL_SHIFT digits each */
1629 for (i=0; i < size - 1; i++) {
1630 rem = pout[i];
1631 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
1632 *--p = '0' + rem % 10;
1633 rem /= 10;
1634 }
1635 }
1636 /* pout[size-1]: always produce at least one decimal digit */
1637 rem = pout[i];
1638 do {
1639 *--p = '0' + rem % 10;
1640 rem /= 10;
1641 } while (rem != 0);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* and sign */
1644 if (negative)
1645 *--p = '-';
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* check we've counted correctly */
1648 assert(p == PyUnicode_AS_UNICODE(str));
1649 Py_DECREF(scratch);
1650 return (PyObject *)str;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001651}
1652
Mark Dickinsoncd068122009-09-18 14:53:08 +00001653/* Convert a long int object to a string, using a given conversion base,
1654 which should be one of 2, 8, 10 or 16. Return a string object.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001655 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001656
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001657PyObject *
1658_PyLong_Format(PyObject *aa, int base)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 register PyLongObject *a = (PyLongObject *)aa;
1661 PyObject *str;
1662 Py_ssize_t i, sz;
1663 Py_ssize_t size_a;
1664 Py_UNICODE *p, sign = '\0';
1665 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 assert(base == 2 || base == 8 || base == 10 || base == 16);
1668 if (base == 10)
1669 return long_to_decimal_string((PyObject *)a);
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 if (a == NULL || !PyLong_Check(a)) {
1672 PyErr_BadInternalCall();
1673 return NULL;
1674 }
1675 size_a = ABS(Py_SIZE(a));
Tim Peters5af4e6c2002-08-12 02:31:19 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 /* Compute a rough upper bound for the length of the string */
1678 switch (base) {
1679 case 16:
1680 bits = 4;
1681 break;
1682 case 8:
1683 bits = 3;
1684 break;
1685 case 2:
1686 bits = 1;
1687 break;
1688 default:
1689 assert(0); /* shouldn't ever get here */
1690 bits = 0; /* to silence gcc warning */
1691 }
1692 /* compute length of output string: allow 2 characters for prefix and
1693 1 for possible '-' sign. */
1694 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1695 PyErr_SetString(PyExc_OverflowError,
1696 "int is too large to format");
1697 return NULL;
1698 }
1699 /* now size_a * PyLong_SHIFT + 3 <= PY_SSIZE_T_MAX, so the RHS below
1700 is safe from overflow */
1701 sz = 3 + (size_a * PyLong_SHIFT + (bits - 1)) / bits;
1702 assert(sz >= 0);
1703 str = PyUnicode_FromUnicode(NULL, sz);
1704 if (str == NULL)
1705 return NULL;
1706 p = PyUnicode_AS_UNICODE(str) + sz;
1707 *p = '\0';
1708 if (Py_SIZE(a) < 0)
1709 sign = '-';
Tim Peters5af4e6c2002-08-12 02:31:19 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (Py_SIZE(a) == 0) {
1712 *--p = '0';
1713 }
1714 else {
1715 /* JRH: special case for power-of-2 bases */
1716 twodigits accum = 0;
1717 int accumbits = 0; /* # of bits in accum */
1718 for (i = 0; i < size_a; ++i) {
1719 accum |= (twodigits)a->ob_digit[i] << accumbits;
1720 accumbits += PyLong_SHIFT;
1721 assert(accumbits >= bits);
1722 do {
1723 Py_UNICODE cdigit;
1724 cdigit = (Py_UNICODE)(accum & (base - 1));
1725 cdigit += (cdigit < 10) ? '0' : 'a'-10;
1726 assert(p > PyUnicode_AS_UNICODE(str));
1727 *--p = cdigit;
1728 accumbits -= bits;
1729 accum >>= bits;
1730 } while (i < size_a-1 ? accumbits >= bits : accum > 0);
1731 }
1732 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (base == 16)
1735 *--p = 'x';
1736 else if (base == 8)
1737 *--p = 'o';
1738 else /* (base == 2) */
1739 *--p = 'b';
1740 *--p = '0';
1741 if (sign)
1742 *--p = sign;
1743 if (p != PyUnicode_AS_UNICODE(str)) {
1744 Py_UNICODE *q = PyUnicode_AS_UNICODE(str);
1745 assert(p > q);
1746 do {
1747 } while ((*q++ = *p++) != '\0');
1748 q--;
1749 if (PyUnicode_Resize(&str,(Py_ssize_t) (q -
1750 PyUnicode_AS_UNICODE(str)))) {
1751 Py_DECREF(str);
1752 return NULL;
1753 }
1754 }
1755 return (PyObject *)str;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001756}
1757
Thomas Wouters477c8d52006-05-27 19:21:47 +00001758/* Table of digit values for 8-bit string -> integer conversion.
1759 * '0' maps to 0, ..., '9' maps to 9.
1760 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1761 * All other indices map to 37.
1762 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001763 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001764 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001765unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1767 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1768 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1769 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1770 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1771 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1772 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1773 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1774 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 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1778 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1779 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1780 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1781 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001782};
1783
1784/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001785 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1786 * non-digit (which may be *str!). A normalized long is returned.
1787 * The point to this routine is that it takes time linear in the number of
1788 * string characters.
1789 */
1790static PyLongObject *
1791long_from_binary_base(char **str, int base)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 char *p = *str;
1794 char *start = p;
1795 int bits_per_char;
1796 Py_ssize_t n;
1797 PyLongObject *z;
1798 twodigits accum;
1799 int bits_in_accum;
1800 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1803 n = base;
1804 for (bits_per_char = -1; n; ++bits_per_char)
1805 n >>= 1;
1806 /* n <- total # of bits needed, while setting p to end-of-string */
1807 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1808 ++p;
1809 *str = p;
1810 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1811 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1812 if (n / bits_per_char < p - start) {
1813 PyErr_SetString(PyExc_ValueError,
1814 "int string too large to convert");
1815 return NULL;
1816 }
1817 n = n / PyLong_SHIFT;
1818 z = _PyLong_New(n);
1819 if (z == NULL)
1820 return NULL;
1821 /* Read string from right, and fill in long from left; i.e.,
1822 * from least to most significant in both.
1823 */
1824 accum = 0;
1825 bits_in_accum = 0;
1826 pdigit = z->ob_digit;
1827 while (--p >= start) {
1828 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1829 assert(k >= 0 && k < base);
1830 accum |= (twodigits)k << bits_in_accum;
1831 bits_in_accum += bits_per_char;
1832 if (bits_in_accum >= PyLong_SHIFT) {
1833 *pdigit++ = (digit)(accum & PyLong_MASK);
1834 assert(pdigit - z->ob_digit <= n);
1835 accum >>= PyLong_SHIFT;
1836 bits_in_accum -= PyLong_SHIFT;
1837 assert(bits_in_accum < PyLong_SHIFT);
1838 }
1839 }
1840 if (bits_in_accum) {
1841 assert(bits_in_accum <= PyLong_SHIFT);
1842 *pdigit++ = (digit)accum;
1843 assert(pdigit - z->ob_digit <= n);
1844 }
1845 while (pdigit - z->ob_digit < n)
1846 *pdigit++ = 0;
1847 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001848}
1849
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001850PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001851PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 int sign = 1, error_if_nonzero = 0;
1854 char *start, *orig_str = str;
1855 PyLongObject *z = NULL;
1856 PyObject *strobj;
1857 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 if ((base != 0 && base < 2) || base > 36) {
1860 PyErr_SetString(PyExc_ValueError,
1861 "int() arg 2 must be >= 2 and <= 36");
1862 return NULL;
1863 }
1864 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1865 str++;
1866 if (*str == '+')
1867 ++str;
1868 else if (*str == '-') {
1869 ++str;
1870 sign = -1;
1871 }
1872 if (base == 0) {
1873 if (str[0] != '0')
1874 base = 10;
1875 else if (str[1] == 'x' || str[1] == 'X')
1876 base = 16;
1877 else if (str[1] == 'o' || str[1] == 'O')
1878 base = 8;
1879 else if (str[1] == 'b' || str[1] == 'B')
1880 base = 2;
1881 else {
1882 /* "old" (C-style) octal literal, now invalid.
1883 it might still be zero though */
1884 error_if_nonzero = 1;
1885 base = 10;
1886 }
1887 }
1888 if (str[0] == '0' &&
1889 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
1890 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
1891 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
1892 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 start = str;
1895 if ((base & (base - 1)) == 0)
1896 z = long_from_binary_base(&str, base);
1897 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898/***
1899Binary bases can be converted in time linear in the number of digits, because
1900Python's representation base is binary. Other bases (including decimal!) use
1901the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00001902
Thomas Wouters477c8d52006-05-27 19:21:47 +00001903First some math: the largest integer that can be expressed in N base-B digits
1904is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
1905case number of Python digits needed to hold it is the smallest integer n s.t.
1906
1907 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
1908 BASE**n >= B**N [taking logs to base BASE]
1909 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
1910
1911The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
1912this quickly. A Python long with that much space is reserved near the start,
1913and the result is computed into it.
1914
1915The input string is actually treated as being in base base**i (i.e., i digits
1916are processed at a time), where two more static arrays hold:
1917
1918 convwidth_base[base] = the largest integer i such that base**i <= BASE
1919 convmultmax_base[base] = base ** convwidth_base[base]
1920
1921The first of these is the largest i such that i consecutive input digits
1922must fit in a single Python digit. The second is effectively the input
1923base we're really using.
1924
1925Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
1926convmultmax_base[base], the result is "simply"
1927
1928 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
1929
1930where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001931
1932Error analysis: as above, the number of Python digits `n` needed is worst-
1933case
1934
1935 n >= N * log(B)/log(BASE)
1936
1937where `N` is the number of input digits in base `B`. This is computed via
1938
1939 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
1940
1941below. Two numeric concerns are how much space this can waste, and whether
1942the computed result can be too small. To be concrete, assume BASE = 2**15,
1943which is the default (and it's unlikely anyone changes that).
1944
1945Waste isn't a problem: provided the first input digit isn't 0, the difference
1946between the worst-case input with N digits and the smallest input with N
1947digits is about a factor of B, but B is small compared to BASE so at most
1948one allocated Python digit can remain unused on that count. If
1949N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
1950and adding 1 returns a result 1 larger than necessary. However, that can't
1951happen: whenever B is a power of 2, long_from_binary_base() is called
1952instead, and it's impossible for B**i to be an integer power of 2**15 when
1953B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
1954an exact integer when B is not a power of 2, since B**i has a prime factor
1955other than 2 in that case, but (2**15)**j's only prime factor is 2).
1956
1957The computed result can be too small if the true value of N*log(B)/log(BASE)
1958is a little bit larger than an exact integer, but due to roundoff errors (in
1959computing log(B), log(BASE), their quotient, and/or multiplying that by N)
1960yields a numeric result a little less than that integer. Unfortunately, "how
1961close can a transcendental function get to an integer over some range?"
1962questions are generally theoretically intractable. Computer analysis via
1963continued fractions is practical: expand log(B)/log(BASE) via continued
1964fractions, giving a sequence i/j of "the best" rational approximations. Then
1965j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
1966we can get very close to being in trouble, but very rarely. For example,
196776573 is a denominator in one of the continued-fraction approximations to
1968log(10)/log(2**15), and indeed:
1969
1970 >>> log(10)/log(2**15)*76573
1971 16958.000000654003
1972
1973is very close to an integer. If we were working with IEEE single-precision,
1974rounding errors could kill us. Finding worst cases in IEEE double-precision
1975requires better-than-double-precision log() functions, and Tim didn't bother.
1976Instead the code checks to see whether the allocated space is enough as each
1977new Python digit is added, and copies the whole thing to a larger long if not.
1978This should happen extremely rarely, and in fact I don't have a test case
1979that triggers it(!). Instead the code was tested by artificially allocating
1980just 1 digit at the start, so that the copying code was exercised for every
1981digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001982***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 register twodigits c; /* current input character */
1984 Py_ssize_t size_z;
1985 int i;
1986 int convwidth;
1987 twodigits convmultmax, convmult;
1988 digit *pz, *pzstop;
1989 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 static double log_base_BASE[37] = {0.0e0,};
1992 static int convwidth_base[37] = {0,};
1993 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (log_base_BASE[base] == 0.0) {
1996 twodigits convmax = base;
1997 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998
Mark Dickinson22b20182010-05-10 21:27:53 +00001999 log_base_BASE[base] = (log((double)base) /
2000 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 for (;;) {
2002 twodigits next = convmax * base;
2003 if (next > PyLong_BASE)
2004 break;
2005 convmax = next;
2006 ++i;
2007 }
2008 convmultmax_base[base] = convmax;
2009 assert(i > 0);
2010 convwidth_base[base] = i;
2011 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 /* Find length of the string of numeric characters. */
2014 scan = str;
2015 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2016 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 /* Create a long object that can contain the largest possible
2019 * integer with this base and length. Note that there's no
2020 * need to initialize z->ob_digit -- no slot is read up before
2021 * being stored into.
2022 */
2023 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2024 /* Uncomment next line to test exceedingly rare copy code */
2025 /* size_z = 1; */
2026 assert(size_z > 0);
2027 z = _PyLong_New(size_z);
2028 if (z == NULL)
2029 return NULL;
2030 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 /* `convwidth` consecutive input digits are treated as a single
2033 * digit in base `convmultmax`.
2034 */
2035 convwidth = convwidth_base[base];
2036 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* Work ;-) */
2039 while (str < scan) {
2040 /* grab up to convwidth digits from the input string */
2041 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2042 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2043 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002044 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 assert(c < PyLong_BASE);
2046 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 convmult = convmultmax;
2049 /* Calculate the shift only if we couldn't get
2050 * convwidth digits.
2051 */
2052 if (i != convwidth) {
2053 convmult = base;
2054 for ( ; i > 1; --i)
2055 convmult *= base;
2056 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* Multiply z by convmult, and add c. */
2059 pz = z->ob_digit;
2060 pzstop = pz + Py_SIZE(z);
2061 for (; pz < pzstop; ++pz) {
2062 c += (twodigits)*pz * convmult;
2063 *pz = (digit)(c & PyLong_MASK);
2064 c >>= PyLong_SHIFT;
2065 }
2066 /* carry off the current end? */
2067 if (c) {
2068 assert(c < PyLong_BASE);
2069 if (Py_SIZE(z) < size_z) {
2070 *pz = (digit)c;
2071 ++Py_SIZE(z);
2072 }
2073 else {
2074 PyLongObject *tmp;
2075 /* Extremely rare. Get more space. */
2076 assert(Py_SIZE(z) == size_z);
2077 tmp = _PyLong_New(size_z + 1);
2078 if (tmp == NULL) {
2079 Py_DECREF(z);
2080 return NULL;
2081 }
2082 memcpy(tmp->ob_digit,
2083 z->ob_digit,
2084 sizeof(digit) * size_z);
2085 Py_DECREF(z);
2086 z = tmp;
2087 z->ob_digit[size_z] = (digit)c;
2088 ++size_z;
2089 }
2090 }
2091 }
2092 }
2093 if (z == NULL)
2094 return NULL;
2095 if (error_if_nonzero) {
2096 /* reset the base to 0, else the exception message
2097 doesn't make too much sense */
2098 base = 0;
2099 if (Py_SIZE(z) != 0)
2100 goto onError;
2101 /* there might still be other problems, therefore base
2102 remains zero here for the same reason */
2103 }
2104 if (str == start)
2105 goto onError;
2106 if (sign < 0)
2107 Py_SIZE(z) = -(Py_SIZE(z));
2108 while (*str && isspace(Py_CHARMASK(*str)))
2109 str++;
2110 if (*str != '\0')
2111 goto onError;
2112 if (pend)
2113 *pend = str;
2114 long_normalize(z);
2115 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002116
Mark Dickinson22b20182010-05-10 21:27:53 +00002117 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_XDECREF(z);
2119 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2120 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2121 if (strobj == NULL)
2122 return NULL;
2123 PyErr_Format(PyExc_ValueError,
2124 "invalid literal for int() with base %d: %R",
2125 base, strobj);
2126 Py_DECREF(strobj);
2127 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002128}
2129
2130PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002131PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002134 PyObject *asciidig;
2135 char *buffer, *end;
2136 Py_ssize_t i, buflen;
2137 Py_UNICODE *ptr;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002138
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002139 asciidig = PyUnicode_TransformDecimalToASCII(u, length);
2140 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 return NULL;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002142 /* Replace non-ASCII whitespace with ' ' */
2143 ptr = PyUnicode_AS_UNICODE(asciidig);
2144 for (i = 0; i < length; i++) {
Mark Dickinsonc9fb3c62010-12-04 11:06:25 +00002145 Py_UNICODE ch = ptr[i];
2146 if (ch > 127 && Py_UNICODE_ISSPACE(ch))
2147 ptr[i] = ' ';
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002148 }
2149 buffer = _PyUnicode_AsStringAndSize(asciidig, &buflen);
2150 if (buffer == NULL) {
2151 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 return NULL;
2153 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002154 result = PyLong_FromString(buffer, &end, base);
2155 if (result != NULL && end != buffer + buflen) {
2156 PyErr_SetString(PyExc_ValueError,
2157 "null byte in argument for int()");
2158 Py_DECREF(result);
2159 result = NULL;
2160 }
2161 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002163}
2164
Tim Peters9f688bf2000-07-07 15:53:28 +00002165/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002168static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002169
2170/* Long division with remainder, top-level routine */
2171
Guido van Rossume32e0141992-01-19 16:31:05 +00002172static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002173long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2177 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (size_b == 0) {
2180 PyErr_SetString(PyExc_ZeroDivisionError,
2181 "integer division or modulo by zero");
2182 return -1;
2183 }
2184 if (size_a < size_b ||
2185 (size_a == size_b &&
2186 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2187 /* |a| < |b|. */
2188 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2189 if (*pdiv == NULL)
2190 return -1;
2191 Py_INCREF(a);
2192 *prem = (PyLongObject *) a;
2193 return 0;
2194 }
2195 if (size_b == 1) {
2196 digit rem = 0;
2197 z = divrem1(a, b->ob_digit[0], &rem);
2198 if (z == NULL)
2199 return -1;
2200 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2201 if (*prem == NULL) {
2202 Py_DECREF(z);
2203 return -1;
2204 }
2205 }
2206 else {
2207 z = x_divrem(a, b, prem);
2208 if (z == NULL)
2209 return -1;
2210 }
2211 /* Set the signs.
2212 The quotient z has the sign of a*b;
2213 the remainder r has the sign of a,
2214 so a = b*z + r. */
2215 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2216 NEGATE(z);
2217 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2218 NEGATE(*prem);
2219 *pdiv = maybe_small_long(z);
2220 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002221}
2222
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002223/* Unsigned long division with remainder -- the algorithm. The arguments v1
2224 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002226static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002227x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyLongObject *v, *w, *a;
2230 Py_ssize_t i, k, size_v, size_w;
2231 int d;
2232 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2233 twodigits vv;
2234 sdigit zhi;
2235 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2238 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2239 handle the special case when the initial estimate q for a quotient
2240 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2241 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 /* allocate space; w will also be used to hold the final remainder */
2244 size_v = ABS(Py_SIZE(v1));
2245 size_w = ABS(Py_SIZE(w1));
2246 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2247 v = _PyLong_New(size_v+1);
2248 if (v == NULL) {
2249 *prem = NULL;
2250 return NULL;
2251 }
2252 w = _PyLong_New(size_w);
2253 if (w == NULL) {
2254 Py_DECREF(v);
2255 *prem = NULL;
2256 return NULL;
2257 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2260 shift v1 left by the same amount. Results go into w and v. */
2261 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2262 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2263 assert(carry == 0);
2264 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2265 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2266 v->ob_digit[size_v] = carry;
2267 size_v++;
2268 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2271 at most (and usually exactly) k = size_v - size_w digits. */
2272 k = size_v - size_w;
2273 assert(k >= 0);
2274 a = _PyLong_New(k);
2275 if (a == NULL) {
2276 Py_DECREF(w);
2277 Py_DECREF(v);
2278 *prem = NULL;
2279 return NULL;
2280 }
2281 v0 = v->ob_digit;
2282 w0 = w->ob_digit;
2283 wm1 = w0[size_w-1];
2284 wm2 = w0[size_w-2];
2285 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2286 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2287 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002290 Py_DECREF(a);
2291 Py_DECREF(w);
2292 Py_DECREF(v);
2293 *prem = NULL;
2294 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002295 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* estimate quotient digit q; may overestimate by 1 (rare) */
2298 vtop = vk[size_w];
2299 assert(vtop <= wm1);
2300 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2301 q = (digit)(vv / wm1);
2302 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2303 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2304 | vk[size_w-2])) {
2305 --q;
2306 r += wm1;
2307 if (r >= PyLong_BASE)
2308 break;
2309 }
2310 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2313 zhi = 0;
2314 for (i = 0; i < size_w; ++i) {
2315 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2316 -PyLong_BASE * q <= z < PyLong_BASE */
2317 z = (sdigit)vk[i] + zhi -
2318 (stwodigits)q * (stwodigits)w0[i];
2319 vk[i] = (digit)z & PyLong_MASK;
2320 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002321 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* add w back if q was too large (this branch taken rarely) */
2325 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2326 if ((sdigit)vtop + zhi < 0) {
2327 carry = 0;
2328 for (i = 0; i < size_w; ++i) {
2329 carry += vk[i] + w0[i];
2330 vk[i] = carry & PyLong_MASK;
2331 carry >>= PyLong_SHIFT;
2332 }
2333 --q;
2334 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* store quotient digit */
2337 assert(q < PyLong_BASE);
2338 *--ak = q;
2339 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* unshift remainder; we reuse w to store the result */
2342 carry = v_rshift(w0, v0, size_w, d);
2343 assert(carry==0);
2344 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 *prem = long_normalize(w);
2347 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002348}
2349
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002350/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2351 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2352 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2353 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2354 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2355 -1.0. */
2356
2357/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2358#if DBL_MANT_DIG == 53
2359#define EXP2_DBL_MANT_DIG 9007199254740992.0
2360#else
2361#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2362#endif
2363
2364double
2365_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2368 /* See below for why x_digits is always large enough. */
2369 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2370 double dx;
2371 /* Correction term for round-half-to-even rounding. For a digit x,
2372 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2373 multiple of 4, rounding ties to a multiple of 8. */
2374 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 a_size = ABS(Py_SIZE(a));
2377 if (a_size == 0) {
2378 /* Special case for 0: significand 0.0, exponent 0. */
2379 *e = 0;
2380 return 0.0;
2381 }
2382 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2383 /* The following is an overflow-free version of the check
2384 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2385 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2386 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2387 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002388 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2392 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 Number of digits needed for result: write // for floor division.
2395 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2404 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2407 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2408 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 in both cases.
2415 */
2416 if (a_bits <= DBL_MANT_DIG + 2) {
2417 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2418 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2419 x_size = 0;
2420 while (x_size < shift_digits)
2421 x_digits[x_size++] = 0;
2422 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2423 (int)shift_bits);
2424 x_size += a_size;
2425 x_digits[x_size++] = rem;
2426 }
2427 else {
2428 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2429 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2430 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2431 a_size - shift_digits, (int)shift_bits);
2432 x_size = a_size - shift_digits;
2433 /* For correct rounding below, we need the least significant
2434 bit of x to be 'sticky' for this shift: if any of the bits
2435 shifted out was nonzero, we set the least significant bit
2436 of x. */
2437 if (rem)
2438 x_digits[0] |= 1;
2439 else
2440 while (shift_digits > 0)
2441 if (a->ob_digit[--shift_digits]) {
2442 x_digits[0] |= 1;
2443 break;
2444 }
2445 }
Mark Dickinson22b20182010-05-10 21:27:53 +00002446 assert(1 <= x_size &&
2447 x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* Round, and convert to double. */
2450 x_digits[0] += half_even_correction[x_digits[0] & 7];
2451 dx = x_digits[--x_size];
2452 while (x_size > 0)
2453 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 /* Rescale; make correction if result is 1.0. */
2456 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2457 if (dx == 1.0) {
2458 if (a_bits == PY_SSIZE_T_MAX)
2459 goto overflow;
2460 dx = 0.5;
2461 a_bits += 1;
2462 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 *e = a_bits;
2465 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002466
2467 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* exponent > PY_SSIZE_T_MAX */
2469 PyErr_SetString(PyExc_OverflowError,
2470 "huge integer: number of bits overflows a Py_ssize_t");
2471 *e = 0;
2472 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002473}
2474
2475/* Get a C double from a long int object. Rounds to the nearest double,
2476 using the round-half-to-even rule in the case of a tie. */
2477
2478double
2479PyLong_AsDouble(PyObject *v)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 Py_ssize_t exponent;
2482 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 if (v == NULL || !PyLong_Check(v)) {
2485 PyErr_BadInternalCall();
2486 return -1.0;
2487 }
2488 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2489 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2490 PyErr_SetString(PyExc_OverflowError,
2491 "long int too large to convert to float");
2492 return -1.0;
2493 }
2494 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002495}
2496
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002497/* Methods */
2498
2499static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002500long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002503}
2504
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002505static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002506long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 if (Py_SIZE(a) != Py_SIZE(b)) {
2511 sign = Py_SIZE(a) - Py_SIZE(b);
2512 }
2513 else {
2514 Py_ssize_t i = ABS(Py_SIZE(a));
2515 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2516 ;
2517 if (i < 0)
2518 sign = 0;
2519 else {
2520 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2521 if (Py_SIZE(a) < 0)
2522 sign = -sign;
2523 }
2524 }
2525 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002526}
2527
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002528#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002530
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002531static PyObject *
2532long_richcompare(PyObject *self, PyObject *other, int op)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 int result;
2535 PyObject *v;
2536 CHECK_BINOP(self, other);
2537 if (self == other)
2538 result = 0;
2539 else
2540 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2541 /* Convert the return value to a Boolean */
2542 switch (op) {
2543 case Py_EQ:
2544 v = TEST_COND(result == 0);
2545 break;
2546 case Py_NE:
2547 v = TEST_COND(result != 0);
2548 break;
2549 case Py_LE:
2550 v = TEST_COND(result <= 0);
2551 break;
2552 case Py_GE:
2553 v = TEST_COND(result >= 0);
2554 break;
2555 case Py_LT:
2556 v = TEST_COND(result == -1);
2557 break;
2558 case Py_GT:
2559 v = TEST_COND(result == 1);
2560 break;
2561 default:
2562 PyErr_BadArgument();
2563 return NULL;
2564 }
2565 Py_INCREF(v);
2566 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002567}
2568
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002569static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002570long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002571{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002572 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 Py_ssize_t i;
2574 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 i = Py_SIZE(v);
2577 switch(i) {
2578 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2579 case 0: return 0;
2580 case 1: return v->ob_digit[0];
2581 }
2582 sign = 1;
2583 x = 0;
2584 if (i < 0) {
2585 sign = -1;
2586 i = -(i);
2587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002589 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2590 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2591 _PyHASH_MODULUS.
2592
2593 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2594 amounts to a rotation of the bits of x. To see this, write
2595
2596 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2597
2598 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2599 PyLong_SHIFT bits of x (those that are shifted out of the
2600 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2601 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2602 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2603 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2604 congruent to y modulo _PyHASH_MODULUS. So
2605
2606 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2607
2608 The right-hand side is just the result of rotating the
2609 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2610 not all _PyHASH_BITS bits of x are 1s, the same is true
2611 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2612 the reduction of x*2**PyLong_SHIFT modulo
2613 _PyHASH_MODULUS. */
2614 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2615 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002617 if (x >= _PyHASH_MODULUS)
2618 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 }
2620 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002621 if (x == (Py_uhash_t)-1)
2622 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002623 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002624}
2625
2626
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002627/* Add the absolute values of two long integers. */
2628
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002629static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002630x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2633 PyLongObject *z;
2634 Py_ssize_t i;
2635 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 /* Ensure a is the larger of the two: */
2638 if (size_a < size_b) {
2639 { PyLongObject *temp = a; a = b; b = temp; }
2640 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002641 size_a = size_b;
2642 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 }
2644 z = _PyLong_New(size_a+1);
2645 if (z == NULL)
2646 return NULL;
2647 for (i = 0; i < size_b; ++i) {
2648 carry += a->ob_digit[i] + b->ob_digit[i];
2649 z->ob_digit[i] = carry & PyLong_MASK;
2650 carry >>= PyLong_SHIFT;
2651 }
2652 for (; i < size_a; ++i) {
2653 carry += a->ob_digit[i];
2654 z->ob_digit[i] = carry & PyLong_MASK;
2655 carry >>= PyLong_SHIFT;
2656 }
2657 z->ob_digit[i] = carry;
2658 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002659}
2660
2661/* Subtract the absolute values of two integers. */
2662
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002663static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002664x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2667 PyLongObject *z;
2668 Py_ssize_t i;
2669 int sign = 1;
2670 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* Ensure a is the larger of the two: */
2673 if (size_a < size_b) {
2674 sign = -1;
2675 { PyLongObject *temp = a; a = b; b = temp; }
2676 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002677 size_a = size_b;
2678 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 }
2680 else if (size_a == size_b) {
2681 /* Find highest digit where a and b differ: */
2682 i = size_a;
2683 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2684 ;
2685 if (i < 0)
2686 return (PyLongObject *)PyLong_FromLong(0);
2687 if (a->ob_digit[i] < b->ob_digit[i]) {
2688 sign = -1;
2689 { PyLongObject *temp = a; a = b; b = temp; }
2690 }
2691 size_a = size_b = i+1;
2692 }
2693 z = _PyLong_New(size_a);
2694 if (z == NULL)
2695 return NULL;
2696 for (i = 0; i < size_b; ++i) {
2697 /* The following assumes unsigned arithmetic
2698 works module 2**N for some N>PyLong_SHIFT. */
2699 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2700 z->ob_digit[i] = borrow & PyLong_MASK;
2701 borrow >>= PyLong_SHIFT;
2702 borrow &= 1; /* Keep only one sign bit */
2703 }
2704 for (; i < size_a; ++i) {
2705 borrow = a->ob_digit[i] - borrow;
2706 z->ob_digit[i] = borrow & PyLong_MASK;
2707 borrow >>= PyLong_SHIFT;
2708 borrow &= 1; /* Keep only one sign bit */
2709 }
2710 assert(borrow == 0);
2711 if (sign < 0)
2712 NEGATE(z);
2713 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002714}
2715
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002716static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002717long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2724 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2725 MEDIUM_VALUE(b));
2726 return result;
2727 }
2728 if (Py_SIZE(a) < 0) {
2729 if (Py_SIZE(b) < 0) {
2730 z = x_add(a, b);
2731 if (z != NULL && Py_SIZE(z) != 0)
2732 Py_SIZE(z) = -(Py_SIZE(z));
2733 }
2734 else
2735 z = x_sub(b, a);
2736 }
2737 else {
2738 if (Py_SIZE(b) < 0)
2739 z = x_sub(a, b);
2740 else
2741 z = x_add(a, b);
2742 }
2743 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002744}
2745
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002746static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002747long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2754 PyObject* r;
2755 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2756 return r;
2757 }
2758 if (Py_SIZE(a) < 0) {
2759 if (Py_SIZE(b) < 0)
2760 z = x_sub(a, b);
2761 else
2762 z = x_add(a, b);
2763 if (z != NULL && Py_SIZE(z) != 0)
2764 Py_SIZE(z) = -(Py_SIZE(z));
2765 }
2766 else {
2767 if (Py_SIZE(b) < 0)
2768 z = x_add(a, b);
2769 else
2770 z = x_sub(a, b);
2771 }
2772 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002773}
2774
Tim Peters5af4e6c2002-08-12 02:31:19 +00002775/* Grade school multiplication, ignoring the signs.
2776 * Returns the absolute value of the product, or NULL if error.
2777 */
2778static PyLongObject *
2779x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 PyLongObject *z;
2782 Py_ssize_t size_a = ABS(Py_SIZE(a));
2783 Py_ssize_t size_b = ABS(Py_SIZE(b));
2784 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 z = _PyLong_New(size_a + size_b);
2787 if (z == NULL)
2788 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2791 if (a == b) {
2792 /* Efficient squaring per HAC, Algorithm 14.16:
2793 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2794 * Gives slightly less than a 2x speedup when a == b,
2795 * via exploiting that each entry in the multiplication
2796 * pyramid appears twice (except for the size_a squares).
2797 */
2798 for (i = 0; i < size_a; ++i) {
2799 twodigits carry;
2800 twodigits f = a->ob_digit[i];
2801 digit *pz = z->ob_digit + (i << 1);
2802 digit *pa = a->ob_digit + i + 1;
2803 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002806 Py_DECREF(z);
2807 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002808 });
Tim Peters0973b992004-08-29 22:16:50 +00002809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 carry = *pz + f * f;
2811 *pz++ = (digit)(carry & PyLong_MASK);
2812 carry >>= PyLong_SHIFT;
2813 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 /* Now f is added in twice in each column of the
2816 * pyramid it appears. Same as adding f<<1 once.
2817 */
2818 f <<= 1;
2819 while (pa < paend) {
2820 carry += *pz + *pa++ * f;
2821 *pz++ = (digit)(carry & PyLong_MASK);
2822 carry >>= PyLong_SHIFT;
2823 assert(carry <= (PyLong_MASK << 1));
2824 }
2825 if (carry) {
2826 carry += *pz;
2827 *pz++ = (digit)(carry & PyLong_MASK);
2828 carry >>= PyLong_SHIFT;
2829 }
2830 if (carry)
2831 *pz += (digit)(carry & PyLong_MASK);
2832 assert((carry >> PyLong_SHIFT) == 0);
2833 }
2834 }
2835 else { /* a is not the same as b -- gradeschool long mult */
2836 for (i = 0; i < size_a; ++i) {
2837 twodigits carry = 0;
2838 twodigits f = a->ob_digit[i];
2839 digit *pz = z->ob_digit + i;
2840 digit *pb = b->ob_digit;
2841 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002844 Py_DECREF(z);
2845 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002846 });
Tim Peters0973b992004-08-29 22:16:50 +00002847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 while (pb < pbend) {
2849 carry += *pz + *pb++ * f;
2850 *pz++ = (digit)(carry & PyLong_MASK);
2851 carry >>= PyLong_SHIFT;
2852 assert(carry <= PyLong_MASK);
2853 }
2854 if (carry)
2855 *pz += (digit)(carry & PyLong_MASK);
2856 assert((carry >> PyLong_SHIFT) == 0);
2857 }
2858 }
2859 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002860}
2861
2862/* A helper for Karatsuba multiplication (k_mul).
2863 Takes a long "n" and an integer "size" representing the place to
2864 split, and sets low and high such that abs(n) == (high << size) + low,
2865 viewing the shift as being by digits. The sign bit is ignored, and
2866 the return values are >= 0.
2867 Returns 0 on success, -1 on failure.
2868*/
2869static int
Mark Dickinson22b20182010-05-10 21:27:53 +00002870kmul_split(PyLongObject *n,
2871 Py_ssize_t size,
2872 PyLongObject **high,
2873 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00002874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 PyLongObject *hi, *lo;
2876 Py_ssize_t size_lo, size_hi;
2877 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 size_lo = MIN(size_n, size);
2880 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 if ((hi = _PyLong_New(size_hi)) == NULL)
2883 return -1;
2884 if ((lo = _PyLong_New(size_lo)) == NULL) {
2885 Py_DECREF(hi);
2886 return -1;
2887 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
2890 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 *high = long_normalize(hi);
2893 *low = long_normalize(lo);
2894 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002895}
2896
Tim Peters60004642002-08-12 22:01:34 +00002897static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
2898
Tim Peters5af4e6c2002-08-12 02:31:19 +00002899/* Karatsuba multiplication. Ignores the input signs, and returns the
2900 * absolute value of the product (or NULL if error).
2901 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
2902 */
2903static PyLongObject *
2904k_mul(PyLongObject *a, PyLongObject *b)
2905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 Py_ssize_t asize = ABS(Py_SIZE(a));
2907 Py_ssize_t bsize = ABS(Py_SIZE(b));
2908 PyLongObject *ah = NULL;
2909 PyLongObject *al = NULL;
2910 PyLongObject *bh = NULL;
2911 PyLongObject *bl = NULL;
2912 PyLongObject *ret = NULL;
2913 PyLongObject *t1, *t2, *t3;
2914 Py_ssize_t shift; /* the number of digits we split off */
2915 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
2918 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
2919 * Then the original product is
2920 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
2921 * By picking X to be a power of 2, "*X" is just shifting, and it's
2922 * been reduced to 3 multiplies on numbers half the size.
2923 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 /* We want to split based on the larger number; fiddle so that b
2926 * is largest.
2927 */
2928 if (asize > bsize) {
2929 t1 = a;
2930 a = b;
2931 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 i = asize;
2934 asize = bsize;
2935 bsize = i;
2936 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 /* Use gradeschool math when either number is too small. */
2939 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
2940 if (asize <= i) {
2941 if (asize == 0)
2942 return (PyLongObject *)PyLong_FromLong(0);
2943 else
2944 return x_mul(a, b);
2945 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 /* If a is small compared to b, splitting on b gives a degenerate
2948 * case with ah==0, and Karatsuba may be (even much) less efficient
2949 * than "grade school" then. However, we can still win, by viewing
2950 * b as a string of "big digits", each of width a->ob_size. That
2951 * leads to a sequence of balanced calls to k_mul.
2952 */
2953 if (2 * asize <= bsize)
2954 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00002955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956 /* Split a & b into hi & lo pieces. */
2957 shift = bsize >> 1;
2958 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
2959 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 if (a == b) {
2962 bh = ah;
2963 bl = al;
2964 Py_INCREF(bh);
2965 Py_INCREF(bl);
2966 }
2967 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 /* The plan:
2970 * 1. Allocate result space (asize + bsize digits: that's always
2971 * enough).
2972 * 2. Compute ah*bh, and copy into result at 2*shift.
2973 * 3. Compute al*bl, and copy into result at 0. Note that this
2974 * can't overlap with #2.
2975 * 4. Subtract al*bl from the result, starting at shift. This may
2976 * underflow (borrow out of the high digit), but we don't care:
2977 * we're effectively doing unsigned arithmetic mod
2978 * BASE**(sizea + sizeb), and so long as the *final* result fits,
2979 * borrows and carries out of the high digit can be ignored.
2980 * 5. Subtract ah*bh from the result, starting at shift.
2981 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
2982 * at shift.
2983 */
Tim Petersd64c1de2002-08-12 17:36:03 +00002984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002985 /* 1. Allocate result space. */
2986 ret = _PyLong_New(asize + bsize);
2987 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002988#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 /* Fill with trash, to catch reference to uninitialized digits. */
2990 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00002991#endif
Tim Peters44121a62002-08-12 06:17:58 +00002992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 /* 2. t1 <- ah*bh, and copy into high digits of result. */
2994 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
2995 assert(Py_SIZE(t1) >= 0);
2996 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
2997 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
2998 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 /* Zero-out the digits higher than the ah*bh copy. */
3001 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3002 if (i)
3003 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3004 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 /* 3. t2 <- al*bl, and copy into the low digits. */
3007 if ((t2 = k_mul(al, bl)) == NULL) {
3008 Py_DECREF(t1);
3009 goto fail;
3010 }
3011 assert(Py_SIZE(t2) >= 0);
3012 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3013 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 /* Zero out remaining digits. */
3016 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3017 if (i)
3018 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3021 * because it's fresher in cache.
3022 */
3023 i = Py_SIZE(ret) - shift; /* # digits after shift */
3024 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3025 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3028 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3031 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3032 Py_DECREF(ah);
3033 Py_DECREF(al);
3034 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 if (a == b) {
3037 t2 = t1;
3038 Py_INCREF(t2);
3039 }
3040 else if ((t2 = x_add(bh, bl)) == NULL) {
3041 Py_DECREF(t1);
3042 goto fail;
3043 }
3044 Py_DECREF(bh);
3045 Py_DECREF(bl);
3046 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 t3 = k_mul(t1, t2);
3049 Py_DECREF(t1);
3050 Py_DECREF(t2);
3051 if (t3 == NULL) goto fail;
3052 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 /* Add t3. It's not obvious why we can't run out of room here.
3055 * See the (*) comment after this function.
3056 */
3057 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3058 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003061
Mark Dickinson22b20182010-05-10 21:27:53 +00003062 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 Py_XDECREF(ret);
3064 Py_XDECREF(ah);
3065 Py_XDECREF(al);
3066 Py_XDECREF(bh);
3067 Py_XDECREF(bl);
3068 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003069}
3070
Tim Petersd6974a52002-08-13 20:37:51 +00003071/* (*) Why adding t3 can't "run out of room" above.
3072
Tim Petersab86c2b2002-08-15 20:06:00 +00003073Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3074to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003075
Tim Petersab86c2b2002-08-15 20:06:00 +000030761. For any integer i, i = c(i/2) + f(i/2). In particular,
3077 bsize = c(bsize/2) + f(bsize/2).
30782. shift = f(bsize/2)
30793. asize <= bsize
30804. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3081 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003082
Tim Petersab86c2b2002-08-15 20:06:00 +00003083We allocated asize + bsize result digits, and add t3 into them at an offset
3084of shift. This leaves asize+bsize-shift allocated digit positions for t3
3085to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3086asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003087
Tim Petersab86c2b2002-08-15 20:06:00 +00003088bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3089at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003090
Tim Petersab86c2b2002-08-15 20:06:00 +00003091If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3092digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3093most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003094
Tim Petersab86c2b2002-08-15 20:06:00 +00003095The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003096
Tim Petersab86c2b2002-08-15 20:06:00 +00003097 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003098
Tim Petersab86c2b2002-08-15 20:06:00 +00003099and we have asize + c(bsize/2) available digit positions. We need to show
3100this is always enough. An instance of c(bsize/2) cancels out in both, so
3101the question reduces to whether asize digits is enough to hold
3102(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3103then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3104asize 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 +00003105digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003106asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003107c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3108is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3109bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003110
Tim Peters48d52c02002-08-14 17:07:32 +00003111Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3112clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3113ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003114*/
3115
Tim Peters60004642002-08-12 22:01:34 +00003116/* b has at least twice the digits of a, and a is big enough that Karatsuba
3117 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3118 * of slices, each with a->ob_size digits, and multiply the slices by a,
3119 * one at a time. This gives k_mul balanced inputs to work with, and is
3120 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003121 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003122 * single-width slice overlap between successive partial sums).
3123 */
3124static PyLongObject *
3125k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 const Py_ssize_t asize = ABS(Py_SIZE(a));
3128 Py_ssize_t bsize = ABS(Py_SIZE(b));
3129 Py_ssize_t nbdone; /* # of b digits already multiplied */
3130 PyLongObject *ret;
3131 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 assert(asize > KARATSUBA_CUTOFF);
3134 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 /* Allocate result space, and zero it out. */
3137 ret = _PyLong_New(asize + bsize);
3138 if (ret == NULL)
3139 return NULL;
3140 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 /* Successive slices of b are copied into bslice. */
3143 bslice = _PyLong_New(asize);
3144 if (bslice == NULL)
3145 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 nbdone = 0;
3148 while (bsize > 0) {
3149 PyLongObject *product;
3150 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 /* Multiply the next slice of b by a. */
3153 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3154 nbtouse * sizeof(digit));
3155 Py_SIZE(bslice) = nbtouse;
3156 product = k_mul(a, bslice);
3157 if (product == NULL)
3158 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 /* Add into result. */
3161 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3162 product->ob_digit, Py_SIZE(product));
3163 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 bsize -= nbtouse;
3166 nbdone += nbtouse;
3167 }
Tim Peters60004642002-08-12 22:01:34 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 Py_DECREF(bslice);
3170 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003171
Mark Dickinson22b20182010-05-10 21:27:53 +00003172 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 Py_DECREF(ret);
3174 Py_XDECREF(bslice);
3175 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003176}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003177
3178static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003179long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 /* fast path for single-digit multiplication */
3186 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3187 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003188#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003190#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 /* if we don't have long long then we're almost certainly
3192 using 15-bit digits, so v will fit in a long. In the
3193 unlikely event that we're using 30-bit digits on a platform
3194 without long long, a large v will just cause us to fall
3195 through to the general multiplication code below. */
3196 if (v >= LONG_MIN && v <= LONG_MAX)
3197 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003198#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 z = k_mul(a, b);
3202 /* Negate if exactly one of the inputs is negative. */
3203 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3204 NEGATE(z);
3205 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003206}
3207
Guido van Rossume32e0141992-01-19 16:31:05 +00003208/* The / and % operators are now defined in terms of divmod().
3209 The expression a mod b has the value a - b*floor(a/b).
3210 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003211 |a| by |b|, with the sign of a. This is also expressed
3212 as a - b*trunc(a/b), if trunc truncates towards zero.
3213 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 a b a rem b a mod b
3215 13 10 3 3
3216 -13 10 -3 7
3217 13 -10 3 -7
3218 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003219 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003220 have different signs. We then subtract one from the 'div'
3221 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003222
Tim Peters47e52ee2004-08-30 02:44:38 +00003223/* Compute
3224 * *pdiv, *pmod = divmod(v, w)
3225 * NULL can be passed for pdiv or pmod, in which case that part of
3226 * the result is simply thrown away. The caller owns a reference to
3227 * each of these it requests (does not pass NULL for).
3228 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003229static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003230l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 if (long_divrem(v, w, &div, &mod) < 0)
3236 return -1;
3237 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3238 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3239 PyLongObject *temp;
3240 PyLongObject *one;
3241 temp = (PyLongObject *) long_add(mod, w);
3242 Py_DECREF(mod);
3243 mod = temp;
3244 if (mod == NULL) {
3245 Py_DECREF(div);
3246 return -1;
3247 }
3248 one = (PyLongObject *) PyLong_FromLong(1L);
3249 if (one == NULL ||
3250 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3251 Py_DECREF(mod);
3252 Py_DECREF(div);
3253 Py_XDECREF(one);
3254 return -1;
3255 }
3256 Py_DECREF(one);
3257 Py_DECREF(div);
3258 div = temp;
3259 }
3260 if (pdiv != NULL)
3261 *pdiv = div;
3262 else
3263 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 if (pmod != NULL)
3266 *pmod = mod;
3267 else
3268 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003271}
3272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003273static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003274long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 CHECK_BINOP(a, b);
3279 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3280 div = NULL;
3281 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003282}
3283
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003284/* PyLong/PyLong -> float, with correctly rounded result. */
3285
3286#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3287#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3288
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003289static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003290long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 PyLongObject *a, *b, *x;
3293 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3294 digit mask, low;
3295 int inexact, negate, a_is_small, b_is_small;
3296 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 CHECK_BINOP(v, w);
3299 a = (PyLongObject *)v;
3300 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 /*
3303 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3306 1. choose a suitable integer 'shift'
3307 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3308 3. adjust x for correct rounding
3309 4. convert x to a double dx with the same value
3310 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3315 returns either 0.0 or -0.0, depending on the sign of b. For a and
3316 b both nonzero, ignore signs of a and b, and add the sign back in
3317 at the end. Now write a_bits and b_bits for the bit lengths of a
3318 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3319 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3324 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3325 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3326 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 1. The integer 'shift' is chosen so that x has the right number of
3331 bits for a double, plus two or three extra bits that will be used
3332 in the rounding decisions. Writing a_bits and b_bits for the
3333 number of significant bits in a and b respectively, a
3334 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 This is fine in the usual case, but if a/b is smaller than the
3339 smallest normal float then it can lead to double rounding on an
3340 IEEE 754 platform, giving incorrectly rounded results. So we
3341 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 2. The quantity x is computed by first shifting a (left -shift bits
3346 if shift <= 0, right shift bits if shift > 0) and then dividing by
3347 b. For both the shift and the division, we keep track of whether
3348 the result is inexact, in a flag 'inexact'; this information is
3349 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 With the choice of shift above, together with our assumption that
3352 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3353 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3356 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 For float representability, we need x/2**extra_bits <
3361 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3362 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 To round, we just modify the bottom digit of x in-place; this can
3367 end up giving a digit with value > PyLONG_MASK, but that's not a
3368 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 With the original choices for shift above, extra_bits will always
3371 be 2 or 3. Then rounding under the round-half-to-even rule, we
3372 round up iff the most significant of the extra bits is 1, and
3373 either: (a) the computation of x in step 2 had an inexact result,
3374 or (b) at least one other of the extra bits is 1, or (c) the least
3375 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 4. Conversion to a double is straightforward; all floating-point
3378 operations involved in the conversion are exact, so there's no
3379 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3382 The result will always be exactly representable as a double, except
3383 in the case that it overflows. To avoid dependence on the exact
3384 behaviour of ldexp on overflow, we check for overflow before
3385 applying ldexp. The result of ldexp is adjusted for sign before
3386 returning.
3387 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 /* Reduce to case where a and b are both positive. */
3390 a_size = ABS(Py_SIZE(a));
3391 b_size = ABS(Py_SIZE(b));
3392 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3393 if (b_size == 0) {
3394 PyErr_SetString(PyExc_ZeroDivisionError,
3395 "division by zero");
3396 goto error;
3397 }
3398 if (a_size == 0)
3399 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* Fast path for a and b small (exactly representable in a double).
3402 Relies on floating-point division being correctly rounded; results
3403 may be subject to double rounding on x86 machines that operate with
3404 the x87 FPU set to 64-bit precision. */
3405 a_is_small = a_size <= MANT_DIG_DIGITS ||
3406 (a_size == MANT_DIG_DIGITS+1 &&
3407 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3408 b_is_small = b_size <= MANT_DIG_DIGITS ||
3409 (b_size == MANT_DIG_DIGITS+1 &&
3410 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3411 if (a_is_small && b_is_small) {
3412 double da, db;
3413 da = a->ob_digit[--a_size];
3414 while (a_size > 0)
3415 da = da * PyLong_BASE + a->ob_digit[--a_size];
3416 db = b->ob_digit[--b_size];
3417 while (b_size > 0)
3418 db = db * PyLong_BASE + b->ob_digit[--b_size];
3419 result = da / db;
3420 goto success;
3421 }
Tim Peterse2a60002001-09-04 06:17:36 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 /* Catch obvious cases of underflow and overflow */
3424 diff = a_size - b_size;
3425 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3426 /* Extreme overflow */
3427 goto overflow;
3428 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3429 /* Extreme underflow */
3430 goto underflow_or_zero;
3431 /* Next line is now safe from overflowing a Py_ssize_t */
3432 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3433 bits_in_digit(b->ob_digit[b_size - 1]);
3434 /* Now diff = a_bits - b_bits. */
3435 if (diff > DBL_MAX_EXP)
3436 goto overflow;
3437 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3438 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 /* Choose value for shift; see comments for step 1 above. */
3441 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 /* x = abs(a * 2**-shift) */
3446 if (shift <= 0) {
3447 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3448 digit rem;
3449 /* x = a << -shift */
3450 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3451 /* In practice, it's probably impossible to end up
3452 here. Both a and b would have to be enormous,
3453 using close to SIZE_T_MAX bytes of memory each. */
3454 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003455 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 goto error;
3457 }
3458 x = _PyLong_New(a_size + shift_digits + 1);
3459 if (x == NULL)
3460 goto error;
3461 for (i = 0; i < shift_digits; i++)
3462 x->ob_digit[i] = 0;
3463 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3464 a_size, -shift % PyLong_SHIFT);
3465 x->ob_digit[a_size + shift_digits] = rem;
3466 }
3467 else {
3468 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3469 digit rem;
3470 /* x = a >> shift */
3471 assert(a_size >= shift_digits);
3472 x = _PyLong_New(a_size - shift_digits);
3473 if (x == NULL)
3474 goto error;
3475 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3476 a_size - shift_digits, shift % PyLong_SHIFT);
3477 /* set inexact if any of the bits shifted out is nonzero */
3478 if (rem)
3479 inexact = 1;
3480 while (!inexact && shift_digits > 0)
3481 if (a->ob_digit[--shift_digits])
3482 inexact = 1;
3483 }
3484 long_normalize(x);
3485 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3488 reference to x, so it's safe to modify it in-place. */
3489 if (b_size == 1) {
3490 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3491 b->ob_digit[0]);
3492 long_normalize(x);
3493 if (rem)
3494 inexact = 1;
3495 }
3496 else {
3497 PyLongObject *div, *rem;
3498 div = x_divrem(x, b, &rem);
3499 Py_DECREF(x);
3500 x = div;
3501 if (x == NULL)
3502 goto error;
3503 if (Py_SIZE(rem))
3504 inexact = 1;
3505 Py_DECREF(rem);
3506 }
3507 x_size = ABS(Py_SIZE(x));
3508 assert(x_size > 0); /* result of division is never zero */
3509 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 /* The number of extra bits that have to be rounded away. */
3512 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3513 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 /* Round by directly modifying the low digit of x. */
3516 mask = (digit)1 << (extra_bits - 1);
3517 low = x->ob_digit[0] | inexact;
3518 if (low & mask && low & (3*mask-1))
3519 low += mask;
3520 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 /* Convert x to a double dx; the conversion is exact. */
3523 dx = x->ob_digit[--x_size];
3524 while (x_size > 0)
3525 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3526 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /* Check whether ldexp result will overflow a double. */
3529 if (shift + x_bits >= DBL_MAX_EXP &&
3530 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3531 goto overflow;
3532 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003533
3534 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003536
3537 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
3540 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 PyErr_SetString(PyExc_OverflowError,
3542 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003543 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003545}
3546
3547static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003548long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003552 CHECK_BINOP(a, b);
3553
3554 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3555 mod = NULL;
3556 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003557}
3558
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003559static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003560long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 PyLongObject *div, *mod;
3563 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3568 return NULL;
3569 }
3570 z = PyTuple_New(2);
3571 if (z != NULL) {
3572 PyTuple_SetItem(z, 0, (PyObject *) div);
3573 PyTuple_SetItem(z, 1, (PyObject *) mod);
3574 }
3575 else {
3576 Py_DECREF(div);
3577 Py_DECREF(mod);
3578 }
3579 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003580}
3581
Tim Peters47e52ee2004-08-30 02:44:38 +00003582/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003583static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003584long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3587 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 PyLongObject *z = NULL; /* accumulated result */
3590 Py_ssize_t i, j, k; /* counters */
3591 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 /* 5-ary values. If the exponent is large enough, table is
3594 * precomputed so that table[i] == a**i % c for i in range(32).
3595 */
3596 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3597 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 /* a, b, c = v, w, x */
3600 CHECK_BINOP(v, w);
3601 a = (PyLongObject*)v; Py_INCREF(a);
3602 b = (PyLongObject*)w; Py_INCREF(b);
3603 if (PyLong_Check(x)) {
3604 c = (PyLongObject *)x;
3605 Py_INCREF(x);
3606 }
3607 else if (x == Py_None)
3608 c = NULL;
3609 else {
3610 Py_DECREF(a);
3611 Py_DECREF(b);
3612 Py_INCREF(Py_NotImplemented);
3613 return Py_NotImplemented;
3614 }
Tim Peters4c483c42001-09-05 06:24:58 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3617 if (c) {
3618 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003619 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 goto Error;
3621 }
3622 else {
3623 /* else return a float. This works because we know
3624 that this calls float_pow() which converts its
3625 arguments to double. */
3626 Py_DECREF(a);
3627 Py_DECREF(b);
3628 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3629 }
3630 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 if (c) {
3633 /* if modulus == 0:
3634 raise ValueError() */
3635 if (Py_SIZE(c) == 0) {
3636 PyErr_SetString(PyExc_ValueError,
3637 "pow() 3rd argument cannot be 0");
3638 goto Error;
3639 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003641 /* if modulus < 0:
3642 negativeOutput = True
3643 modulus = -modulus */
3644 if (Py_SIZE(c) < 0) {
3645 negativeOutput = 1;
3646 temp = (PyLongObject *)_PyLong_Copy(c);
3647 if (temp == NULL)
3648 goto Error;
3649 Py_DECREF(c);
3650 c = temp;
3651 temp = NULL;
3652 NEGATE(c);
3653 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 /* if modulus == 1:
3656 return 0 */
3657 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3658 z = (PyLongObject *)PyLong_FromLong(0L);
3659 goto Done;
3660 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* if base < 0:
3663 base = base % modulus
3664 Having the base positive just makes things easier. */
3665 if (Py_SIZE(a) < 0) {
3666 if (l_divmod(a, c, NULL, &temp) < 0)
3667 goto Error;
3668 Py_DECREF(a);
3669 a = temp;
3670 temp = NULL;
3671 }
3672 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 /* At this point a, b, and c are guaranteed non-negative UNLESS
3675 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 z = (PyLongObject *)PyLong_FromLong(1L);
3678 if (z == NULL)
3679 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 /* Perform a modular reduction, X = X % c, but leave X alone if c
3682 * is NULL.
3683 */
3684#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003685 do { \
3686 if (c != NULL) { \
3687 if (l_divmod(X, c, NULL, &temp) < 0) \
3688 goto Error; \
3689 Py_XDECREF(X); \
3690 X = temp; \
3691 temp = NULL; \
3692 } \
3693 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 /* Multiply two values, then reduce the result:
3696 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003697#define MULT(X, Y, result) \
3698 do { \
3699 temp = (PyLongObject *)long_mul(X, Y); \
3700 if (temp == NULL) \
3701 goto Error; \
3702 Py_XDECREF(result); \
3703 result = temp; \
3704 temp = NULL; \
3705 REDUCE(result); \
3706 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3709 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3710 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3711 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3712 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003715 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003717 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 }
3719 }
3720 }
3721 else {
3722 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3723 Py_INCREF(z); /* still holds 1L */
3724 table[0] = z;
3725 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003726 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3729 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3732 const int index = (bi >> j) & 0x1f;
3733 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003734 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003736 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 }
3738 }
3739 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 if (negativeOutput && (Py_SIZE(z) != 0)) {
3742 temp = (PyLongObject *)long_sub(z, c);
3743 if (temp == NULL)
3744 goto Error;
3745 Py_DECREF(z);
3746 z = temp;
3747 temp = NULL;
3748 }
3749 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003750
Mark Dickinson22b20182010-05-10 21:27:53 +00003751 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 if (z != NULL) {
3753 Py_DECREF(z);
3754 z = NULL;
3755 }
3756 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003757 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3759 for (i = 0; i < 32; ++i)
3760 Py_XDECREF(table[i]);
3761 }
3762 Py_DECREF(a);
3763 Py_DECREF(b);
3764 Py_XDECREF(c);
3765 Py_XDECREF(temp);
3766 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003767}
3768
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003769static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003770long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 /* Implement ~x as -(x+1) */
3773 PyLongObject *x;
3774 PyLongObject *w;
3775 if (ABS(Py_SIZE(v)) <=1)
3776 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3777 w = (PyLongObject *)PyLong_FromLong(1L);
3778 if (w == NULL)
3779 return NULL;
3780 x = (PyLongObject *) long_add(v, w);
3781 Py_DECREF(w);
3782 if (x == NULL)
3783 return NULL;
3784 Py_SIZE(x) = -(Py_SIZE(x));
3785 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003786}
3787
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003788static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003789long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 PyLongObject *z;
3792 if (ABS(Py_SIZE(v)) <= 1)
3793 return PyLong_FromLong(-MEDIUM_VALUE(v));
3794 z = (PyLongObject *)_PyLong_Copy(v);
3795 if (z != NULL)
3796 Py_SIZE(z) = -(Py_SIZE(v));
3797 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003798}
3799
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003800static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003801long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 if (Py_SIZE(v) < 0)
3804 return long_neg(v);
3805 else
3806 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003807}
3808
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003809static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003810long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003813}
3814
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003815static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003816long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 PyLongObject *z = NULL;
3819 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3820 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003822 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 if (Py_SIZE(a) < 0) {
3825 /* Right shifting negative numbers is harder */
3826 PyLongObject *a1, *a2;
3827 a1 = (PyLongObject *) long_invert(a);
3828 if (a1 == NULL)
3829 goto rshift_error;
3830 a2 = (PyLongObject *) long_rshift(a1, b);
3831 Py_DECREF(a1);
3832 if (a2 == NULL)
3833 goto rshift_error;
3834 z = (PyLongObject *) long_invert(a2);
3835 Py_DECREF(a2);
3836 }
3837 else {
3838 shiftby = PyLong_AsSsize_t((PyObject *)b);
3839 if (shiftby == -1L && PyErr_Occurred())
3840 goto rshift_error;
3841 if (shiftby < 0) {
3842 PyErr_SetString(PyExc_ValueError,
3843 "negative shift count");
3844 goto rshift_error;
3845 }
3846 wordshift = shiftby / PyLong_SHIFT;
3847 newsize = ABS(Py_SIZE(a)) - wordshift;
3848 if (newsize <= 0)
3849 return PyLong_FromLong(0);
3850 loshift = shiftby % PyLong_SHIFT;
3851 hishift = PyLong_SHIFT - loshift;
3852 lomask = ((digit)1 << hishift) - 1;
3853 himask = PyLong_MASK ^ lomask;
3854 z = _PyLong_New(newsize);
3855 if (z == NULL)
3856 goto rshift_error;
3857 if (Py_SIZE(a) < 0)
3858 Py_SIZE(z) = -(Py_SIZE(z));
3859 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3860 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3861 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00003862 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003863 }
3864 z = long_normalize(z);
3865 }
Mark Dickinson22b20182010-05-10 21:27:53 +00003866 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003868
Guido van Rossumc6913e71991-11-19 20:26:46 +00003869}
3870
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003871static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003872long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003874 /* This version due to Tim Peters */
3875 PyLongObject *a = (PyLongObject*)v;
3876 PyLongObject *b = (PyLongObject*)w;
3877 PyLongObject *z = NULL;
3878 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
3879 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 shiftby = PyLong_AsSsize_t((PyObject *)b);
3884 if (shiftby == -1L && PyErr_Occurred())
3885 goto lshift_error;
3886 if (shiftby < 0) {
3887 PyErr_SetString(PyExc_ValueError, "negative shift count");
3888 goto lshift_error;
3889 }
3890 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
3891 wordshift = shiftby / PyLong_SHIFT;
3892 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 oldsize = ABS(Py_SIZE(a));
3895 newsize = oldsize + wordshift;
3896 if (remshift)
3897 ++newsize;
3898 z = _PyLong_New(newsize);
3899 if (z == NULL)
3900 goto lshift_error;
3901 if (Py_SIZE(a) < 0)
3902 NEGATE(z);
3903 for (i = 0; i < wordshift; i++)
3904 z->ob_digit[i] = 0;
3905 accum = 0;
3906 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
3907 accum |= (twodigits)a->ob_digit[j] << remshift;
3908 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
3909 accum >>= PyLong_SHIFT;
3910 }
3911 if (remshift)
3912 z->ob_digit[newsize-1] = (digit)accum;
3913 else
3914 assert(!accum);
3915 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00003916 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00003918}
3919
Mark Dickinson27a87a22009-10-25 20:43:34 +00003920/* Compute two's complement of digit vector a[0:m], writing result to
3921 z[0:m]. The digit vector a need not be normalized, but should not
3922 be entirely zero. a and z may point to the same digit vector. */
3923
3924static void
3925v_complement(digit *z, digit *a, Py_ssize_t m)
3926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 Py_ssize_t i;
3928 digit carry = 1;
3929 for (i = 0; i < m; ++i) {
3930 carry += a[i] ^ PyLong_MASK;
3931 z[i] = carry & PyLong_MASK;
3932 carry >>= PyLong_SHIFT;
3933 }
3934 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003935}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003936
3937/* Bitwise and/xor/or operations */
3938
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003939static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003940long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00003942 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 int nega, negb, negz;
3945 Py_ssize_t size_a, size_b, size_z, i;
3946 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 /* Bitwise operations for negative numbers operate as though
3949 on a two's complement representation. So convert arguments
3950 from sign-magnitude to two's complement, and convert the
3951 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 /* If a is negative, replace it by its two's complement. */
3954 size_a = ABS(Py_SIZE(a));
3955 nega = Py_SIZE(a) < 0;
3956 if (nega) {
3957 z = _PyLong_New(size_a);
3958 if (z == NULL)
3959 return NULL;
3960 v_complement(z->ob_digit, a->ob_digit, size_a);
3961 a = z;
3962 }
3963 else
3964 /* Keep reference count consistent. */
3965 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00003966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 /* Same for b. */
3968 size_b = ABS(Py_SIZE(b));
3969 negb = Py_SIZE(b) < 0;
3970 if (negb) {
3971 z = _PyLong_New(size_b);
3972 if (z == NULL) {
3973 Py_DECREF(a);
3974 return NULL;
3975 }
3976 v_complement(z->ob_digit, b->ob_digit, size_b);
3977 b = z;
3978 }
3979 else
3980 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003982 /* Swap a and b if necessary to ensure size_a >= size_b. */
3983 if (size_a < size_b) {
3984 z = a; a = b; b = z;
3985 size_z = size_a; size_a = size_b; size_b = size_z;
3986 negz = nega; nega = negb; negb = negz;
3987 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 /* JRH: The original logic here was to allocate the result value (z)
3990 as the longer of the two operands. However, there are some cases
3991 where the result is guaranteed to be shorter than that: AND of two
3992 positives, OR of two negatives: use the shorter number. AND with
3993 mixed signs: use the positive number. OR with mixed signs: use the
3994 negative number.
3995 */
3996 switch (op) {
3997 case '^':
3998 negz = nega ^ negb;
3999 size_z = size_a;
4000 break;
4001 case '&':
4002 negz = nega & negb;
4003 size_z = negb ? size_a : size_b;
4004 break;
4005 case '|':
4006 negz = nega | negb;
4007 size_z = negb ? size_b : size_a;
4008 break;
4009 default:
4010 PyErr_BadArgument();
4011 return NULL;
4012 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004014 /* We allow an extra digit if z is negative, to make sure that
4015 the final two's complement of z doesn't overflow. */
4016 z = _PyLong_New(size_z + negz);
4017 if (z == NULL) {
4018 Py_DECREF(a);
4019 Py_DECREF(b);
4020 return NULL;
4021 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 /* Compute digits for overlap of a and b. */
4024 switch(op) {
4025 case '&':
4026 for (i = 0; i < size_b; ++i)
4027 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4028 break;
4029 case '|':
4030 for (i = 0; i < size_b; ++i)
4031 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4032 break;
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 default:
4038 PyErr_BadArgument();
4039 return NULL;
4040 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 /* Copy any remaining digits of a, inverting if necessary. */
4043 if (op == '^' && negb)
4044 for (; i < size_z; ++i)
4045 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4046 else if (i < size_z)
4047 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4048 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004050 /* Complement result if negative. */
4051 if (negz) {
4052 Py_SIZE(z) = -(Py_SIZE(z));
4053 z->ob_digit[size_z] = PyLong_MASK;
4054 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4055 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 Py_DECREF(a);
4058 Py_DECREF(b);
4059 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004060}
4061
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004062static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004063long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 PyObject *c;
4066 CHECK_BINOP(a, b);
4067 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4068 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004069}
4070
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004071static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004072long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 PyObject *c;
4075 CHECK_BINOP(a, b);
4076 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4077 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004078}
4079
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004080static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004081long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 PyObject *c;
4084 CHECK_BINOP(a, b);
4085 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4086 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004087}
4088
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004089static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004090long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 if (PyLong_CheckExact(v))
4093 Py_INCREF(v);
4094 else
4095 v = _PyLong_Copy((PyLongObject *)v);
4096 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004097}
4098
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004099static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004100long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004102 double result;
4103 result = PyLong_AsDouble(v);
4104 if (result == -1.0 && PyErr_Occurred())
4105 return NULL;
4106 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004107}
4108
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004109static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004110long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004111
Tim Peters6d6c1a32001-08-02 04:15:00 +00004112static PyObject *
4113long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4114{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004115 PyObject *obase = NULL, *x = NULL;
4116 long base;
4117 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 if (type != &PyLong_Type)
4121 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004122 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4123 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004124 return NULL;
4125 if (x == NULL)
4126 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004127 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004128 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004129
4130 base = PyLong_AsLongAndOverflow(obase, &overflow);
4131 if (base == -1 && PyErr_Occurred())
4132 return NULL;
4133 if (overflow || (base != 0 && base < 2) || base > 36) {
4134 PyErr_SetString(PyExc_ValueError,
4135 "int() arg 2 must be >= 2 and <= 36");
4136 return NULL;
4137 }
4138
4139 if (PyUnicode_Check(x))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
4141 PyUnicode_GET_SIZE(x),
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004142 (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004143 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4144 /* Since PyLong_FromString doesn't have a length parameter,
4145 * check here for possible NULs in the string. */
4146 char *string;
4147 Py_ssize_t size = Py_SIZE(x);
4148 if (PyByteArray_Check(x))
4149 string = PyByteArray_AS_STRING(x);
4150 else
4151 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004152 if (strlen(string) != (size_t)size || !size) {
4153 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 x is a bytes or buffer, *and* a base is given. */
4155 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004156 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004157 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 return NULL;
4159 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004160 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 }
4162 else {
4163 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004164 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 return NULL;
4166 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004167}
4168
Guido van Rossumbef14172001-08-29 15:47:46 +00004169/* Wimpy, slow approach to tp_new calls for subtypes of long:
4170 first create a regular long from whatever arguments we got,
4171 then allocate a subtype instance and initialize it from
4172 the regular long. The regular long is then thrown away.
4173*/
4174static PyObject *
4175long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 PyLongObject *tmp, *newobj;
4178 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 assert(PyType_IsSubtype(type, &PyLong_Type));
4181 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4182 if (tmp == NULL)
4183 return NULL;
4184 assert(PyLong_CheckExact(tmp));
4185 n = Py_SIZE(tmp);
4186 if (n < 0)
4187 n = -n;
4188 newobj = (PyLongObject *)type->tp_alloc(type, n);
4189 if (newobj == NULL) {
4190 Py_DECREF(tmp);
4191 return NULL;
4192 }
4193 assert(PyLong_Check(newobj));
4194 Py_SIZE(newobj) = Py_SIZE(tmp);
4195 for (i = 0; i < n; i++)
4196 newobj->ob_digit[i] = tmp->ob_digit[i];
4197 Py_DECREF(tmp);
4198 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004199}
4200
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004201static PyObject *
4202long_getnewargs(PyLongObject *v)
4203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004205}
4206
Guido van Rossumb43daf72007-08-01 18:08:08 +00004207static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004208long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004210}
4211
4212static PyObject *
4213long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004215}
4216
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004217static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004218long__format__(PyObject *self, PyObject *args)
4219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 PyObject *format_spec;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004222 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4223 return NULL;
4224 return _PyLong_FormatAdvanced(self,
4225 PyUnicode_AS_UNICODE(format_spec),
4226 PyUnicode_GET_SIZE(format_spec));
Eric Smith8c663262007-08-25 02:26:07 +00004227}
4228
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004229/* Return a pair (q, r) such that a = b * q + r, and
4230 abs(r) <= abs(b)/2, with equality possible only if q is even.
4231 In other words, q == a / b, rounded to the nearest integer using
4232 round-half-to-even. */
4233
4234PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004235_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004236{
4237 PyLongObject *quo = NULL, *rem = NULL;
4238 PyObject *one = NULL, *twice_rem, *result, *temp;
4239 int cmp, quo_is_odd, quo_is_neg;
4240
4241 /* Equivalent Python code:
4242
4243 def divmod_near(a, b):
4244 q, r = divmod(a, b)
4245 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4246 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4247 # positive, 2 * r < b if b negative.
4248 greater_than_half = 2*r > b if b > 0 else 2*r < b
4249 exactly_half = 2*r == b
4250 if greater_than_half or exactly_half and q % 2 == 1:
4251 q += 1
4252 r -= b
4253 return q, r
4254
4255 */
4256 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4257 PyErr_SetString(PyExc_TypeError,
4258 "non-integer arguments in division");
4259 return NULL;
4260 }
4261
4262 /* Do a and b have different signs? If so, quotient is negative. */
4263 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4264
4265 one = PyLong_FromLong(1L);
4266 if (one == NULL)
4267 return NULL;
4268
4269 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4270 goto error;
4271
4272 /* compare twice the remainder with the divisor, to see
4273 if we need to adjust the quotient and remainder */
4274 twice_rem = long_lshift((PyObject *)rem, one);
4275 if (twice_rem == NULL)
4276 goto error;
4277 if (quo_is_neg) {
4278 temp = long_neg((PyLongObject*)twice_rem);
4279 Py_DECREF(twice_rem);
4280 twice_rem = temp;
4281 if (twice_rem == NULL)
4282 goto error;
4283 }
4284 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4285 Py_DECREF(twice_rem);
4286
4287 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4288 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4289 /* fix up quotient */
4290 if (quo_is_neg)
4291 temp = long_sub(quo, (PyLongObject *)one);
4292 else
4293 temp = long_add(quo, (PyLongObject *)one);
4294 Py_DECREF(quo);
4295 quo = (PyLongObject *)temp;
4296 if (quo == NULL)
4297 goto error;
4298 /* and remainder */
4299 if (quo_is_neg)
4300 temp = long_add(rem, (PyLongObject *)b);
4301 else
4302 temp = long_sub(rem, (PyLongObject *)b);
4303 Py_DECREF(rem);
4304 rem = (PyLongObject *)temp;
4305 if (rem == NULL)
4306 goto error;
4307 }
4308
4309 result = PyTuple_New(2);
4310 if (result == NULL)
4311 goto error;
4312
4313 /* PyTuple_SET_ITEM steals references */
4314 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4315 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4316 Py_DECREF(one);
4317 return result;
4318
4319 error:
4320 Py_XDECREF(quo);
4321 Py_XDECREF(rem);
4322 Py_XDECREF(one);
4323 return NULL;
4324}
4325
Eric Smith8c663262007-08-25 02:26:07 +00004326static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004327long_round(PyObject *self, PyObject *args)
4328{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004329 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004330
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004331 /* To round an integer m to the nearest 10**n (n positive), we make use of
4332 * the divmod_near operation, defined by:
4333 *
4334 * divmod_near(a, b) = (q, r)
4335 *
4336 * where q is the nearest integer to the quotient a / b (the
4337 * nearest even integer in the case of a tie) and r == a - q * b.
4338 * Hence q * b = a - r is the nearest multiple of b to a,
4339 * preferring even multiples in the case of a tie.
4340 *
4341 * So the nearest multiple of 10**n to m is:
4342 *
4343 * m - divmod_near(m, 10**n)[1].
4344 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4346 return NULL;
4347 if (o_ndigits == NULL)
4348 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004349
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004350 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 if (ndigits == NULL)
4352 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004353
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004354 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 if (Py_SIZE(ndigits) >= 0) {
4356 Py_DECREF(ndigits);
4357 return long_long(self);
4358 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004359
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004360 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4361 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004363 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004365 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004366
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004367 result = PyLong_FromLong(10L);
4368 if (result == NULL) {
4369 Py_DECREF(ndigits);
4370 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004372
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004373 temp = long_pow(result, ndigits, Py_None);
4374 Py_DECREF(ndigits);
4375 Py_DECREF(result);
4376 result = temp;
4377 if (result == NULL)
4378 return NULL;
4379
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004380 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004381 Py_DECREF(result);
4382 result = temp;
4383 if (result == NULL)
4384 return NULL;
4385
4386 temp = long_sub((PyLongObject *)self,
4387 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4388 Py_DECREF(result);
4389 result = temp;
4390
4391 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004392}
4393
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004394static PyObject *
4395long_sizeof(PyLongObject *v)
4396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4400 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004401}
4402
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004403static PyObject *
4404long_bit_length(PyLongObject *v)
4405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004406 PyLongObject *result, *x, *y;
4407 Py_ssize_t ndigits, msd_bits = 0;
4408 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 assert(v != NULL);
4411 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 ndigits = ABS(Py_SIZE(v));
4414 if (ndigits == 0)
4415 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 msd = v->ob_digit[ndigits-1];
4418 while (msd >= 32) {
4419 msd_bits += 6;
4420 msd >>= 6;
4421 }
4422 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4425 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 /* expression above may overflow; use Python integers instead */
4428 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4429 if (result == NULL)
4430 return NULL;
4431 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4432 if (x == NULL)
4433 goto error;
4434 y = (PyLongObject *)long_mul(result, x);
4435 Py_DECREF(x);
4436 if (y == NULL)
4437 goto error;
4438 Py_DECREF(result);
4439 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4442 if (x == NULL)
4443 goto error;
4444 y = (PyLongObject *)long_add(result, x);
4445 Py_DECREF(x);
4446 if (y == NULL)
4447 goto error;
4448 Py_DECREF(result);
4449 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004452
Mark Dickinson22b20182010-05-10 21:27:53 +00004453 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 Py_DECREF(result);
4455 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004456}
4457
4458PyDoc_STRVAR(long_bit_length_doc,
4459"int.bit_length() -> int\n\
4460\n\
4461Number of bits necessary to represent self in binary.\n\
4462>>> bin(37)\n\
4463'0b100101'\n\
4464>>> (37).bit_length()\n\
44656");
4466
Christian Heimes53876d92008-04-19 00:31:39 +00004467#if 0
4468static PyObject *
4469long_is_finite(PyObject *v)
4470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004472}
4473#endif
4474
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004475
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004476static PyObject *
4477long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 PyObject *byteorder_str;
4480 PyObject *is_signed_obj = NULL;
4481 Py_ssize_t length;
4482 int little_endian;
4483 int is_signed;
4484 PyObject *bytes;
4485 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4488 &length, &byteorder_str,
4489 &is_signed_obj))
4490 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492 if (args != NULL && Py_SIZE(args) > 2) {
4493 PyErr_SetString(PyExc_TypeError,
4494 "'signed' is a keyword-only argument");
4495 return NULL;
4496 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4499 little_endian = 1;
4500 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4501 little_endian = 0;
4502 else {
4503 PyErr_SetString(PyExc_ValueError,
4504 "byteorder must be either 'little' or 'big'");
4505 return NULL;
4506 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 if (is_signed_obj != NULL) {
4509 int cmp = PyObject_IsTrue(is_signed_obj);
4510 if (cmp < 0)
4511 return NULL;
4512 is_signed = cmp ? 1 : 0;
4513 }
4514 else {
4515 /* If the signed argument was omitted, use False as the
4516 default. */
4517 is_signed = 0;
4518 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 if (length < 0) {
4521 PyErr_SetString(PyExc_ValueError,
4522 "length argument must be non-negative");
4523 return NULL;
4524 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 bytes = PyBytes_FromStringAndSize(NULL, length);
4527 if (bytes == NULL)
4528 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004530 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4531 length, little_endian, is_signed) < 0) {
4532 Py_DECREF(bytes);
4533 return NULL;
4534 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004537}
4538
Mark Dickinson078c2532010-01-30 18:06:17 +00004539PyDoc_STRVAR(long_to_bytes_doc,
4540"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004541\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004542Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004543\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004544The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004545raised if the integer is not representable with the given number of\n\
4546bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004547\n\
4548The byteorder argument determines the byte order used to represent the\n\
4549integer. If byteorder is 'big', the most significant byte is at the\n\
4550beginning of the byte array. If byteorder is 'little', the most\n\
4551significant byte is at the end of the byte array. To request the native\n\
4552byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4553\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004554The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004555used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004556is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004557
4558static PyObject *
4559long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 PyObject *byteorder_str;
4562 PyObject *is_signed_obj = NULL;
4563 int little_endian;
4564 int is_signed;
4565 PyObject *obj;
4566 PyObject *bytes;
4567 PyObject *long_obj;
4568 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4571 &obj, &byteorder_str,
4572 &is_signed_obj))
4573 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 if (args != NULL && Py_SIZE(args) > 2) {
4576 PyErr_SetString(PyExc_TypeError,
4577 "'signed' is a keyword-only argument");
4578 return NULL;
4579 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004581 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4582 little_endian = 1;
4583 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4584 little_endian = 0;
4585 else {
4586 PyErr_SetString(PyExc_ValueError,
4587 "byteorder must be either 'little' or 'big'");
4588 return NULL;
4589 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004591 if (is_signed_obj != NULL) {
4592 int cmp = PyObject_IsTrue(is_signed_obj);
4593 if (cmp < 0)
4594 return NULL;
4595 is_signed = cmp ? 1 : 0;
4596 }
4597 else {
4598 /* If the signed argument was omitted, use False as the
4599 default. */
4600 is_signed = 0;
4601 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 bytes = PyObject_Bytes(obj);
4604 if (bytes == NULL)
4605 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 long_obj = _PyLong_FromByteArray(
4608 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4609 little_endian, is_signed);
4610 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 /* If from_bytes() was used on subclass, allocate new subclass
4613 * instance, initialize it with decoded long value and return it.
4614 */
4615 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4616 PyLongObject *newobj;
4617 int i;
4618 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004620 newobj = (PyLongObject *)type->tp_alloc(type, n);
4621 if (newobj == NULL) {
4622 Py_DECREF(long_obj);
4623 return NULL;
4624 }
4625 assert(PyLong_Check(newobj));
4626 Py_SIZE(newobj) = Py_SIZE(long_obj);
4627 for (i = 0; i < n; i++) {
4628 newobj->ob_digit[i] =
4629 ((PyLongObject *)long_obj)->ob_digit[i];
4630 }
4631 Py_DECREF(long_obj);
4632 return (PyObject *)newobj;
4633 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004636}
4637
Mark Dickinson078c2532010-01-30 18:06:17 +00004638PyDoc_STRVAR(long_from_bytes_doc,
4639"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4640\n\
4641Return the integer represented by the given array of bytes.\n\
4642\n\
4643The bytes argument must either support the buffer protocol or be an\n\
4644iterable object producing bytes. Bytes and bytearray are examples of\n\
4645built-in objects that support the buffer protocol.\n\
4646\n\
4647The byteorder argument determines the byte order used to represent the\n\
4648integer. If byteorder is 'big', the most significant byte is at the\n\
4649beginning of the byte array. If byteorder is 'little', the most\n\
4650significant byte is at the end of the byte array. To request the native\n\
4651byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4652\n\
4653The signed keyword-only argument indicates whether two's complement is\n\
4654used to represent the integer.");
4655
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004656static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4658 "Returns self, the complex conjugate of any int."},
4659 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4660 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004661#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4663 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004664#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 {"to_bytes", (PyCFunction)long_to_bytes,
4666 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4667 {"from_bytes", (PyCFunction)long_from_bytes,
4668 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4669 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4670 "Truncating an Integral returns itself."},
4671 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4672 "Flooring an Integral returns itself."},
4673 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4674 "Ceiling of an Integral returns itself."},
4675 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4676 "Rounding an Integral returns itself.\n"
4677 "Rounding with an ndigits argument also returns an integer."},
4678 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4679 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4680 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4681 "Returns size in memory, in bytes"},
4682 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004683};
4684
Guido van Rossumb43daf72007-08-01 18:08:08 +00004685static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004686 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004687 (getter)long_long, (setter)NULL,
4688 "the real part of a complex number",
4689 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004690 {"imag",
4691 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004692 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004693 NULL},
4694 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004695 (getter)long_long, (setter)NULL,
4696 "the numerator of a rational number in lowest terms",
4697 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004698 {"denominator",
4699 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004700 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004701 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004702 {NULL} /* Sentinel */
4703};
4704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004705PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004706"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004707\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004708Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004709point argument will be truncated towards zero (this does not include a\n\
4710string representation of a floating point number!) When converting a\n\
4711string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004712converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004713
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004714static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004715 (binaryfunc)long_add, /*nb_add*/
4716 (binaryfunc)long_sub, /*nb_subtract*/
4717 (binaryfunc)long_mul, /*nb_multiply*/
4718 long_mod, /*nb_remainder*/
4719 long_divmod, /*nb_divmod*/
4720 long_pow, /*nb_power*/
4721 (unaryfunc)long_neg, /*nb_negative*/
4722 (unaryfunc)long_long, /*tp_positive*/
4723 (unaryfunc)long_abs, /*tp_absolute*/
4724 (inquiry)long_bool, /*tp_bool*/
4725 (unaryfunc)long_invert, /*nb_invert*/
4726 long_lshift, /*nb_lshift*/
4727 (binaryfunc)long_rshift, /*nb_rshift*/
4728 long_and, /*nb_and*/
4729 long_xor, /*nb_xor*/
4730 long_or, /*nb_or*/
4731 long_long, /*nb_int*/
4732 0, /*nb_reserved*/
4733 long_float, /*nb_float*/
4734 0, /* nb_inplace_add */
4735 0, /* nb_inplace_subtract */
4736 0, /* nb_inplace_multiply */
4737 0, /* nb_inplace_remainder */
4738 0, /* nb_inplace_power */
4739 0, /* nb_inplace_lshift */
4740 0, /* nb_inplace_rshift */
4741 0, /* nb_inplace_and */
4742 0, /* nb_inplace_xor */
4743 0, /* nb_inplace_or */
4744 long_div, /* nb_floor_divide */
4745 long_true_divide, /* nb_true_divide */
4746 0, /* nb_inplace_floor_divide */
4747 0, /* nb_inplace_true_divide */
4748 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004749};
4750
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004751PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4753 "int", /* tp_name */
4754 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4755 sizeof(digit), /* tp_itemsize */
4756 long_dealloc, /* tp_dealloc */
4757 0, /* tp_print */
4758 0, /* tp_getattr */
4759 0, /* tp_setattr */
4760 0, /* tp_reserved */
4761 long_to_decimal_string, /* tp_repr */
4762 &long_as_number, /* tp_as_number */
4763 0, /* tp_as_sequence */
4764 0, /* tp_as_mapping */
4765 (hashfunc)long_hash, /* tp_hash */
4766 0, /* tp_call */
4767 long_to_decimal_string, /* tp_str */
4768 PyObject_GenericGetAttr, /* tp_getattro */
4769 0, /* tp_setattro */
4770 0, /* tp_as_buffer */
4771 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4772 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4773 long_doc, /* tp_doc */
4774 0, /* tp_traverse */
4775 0, /* tp_clear */
4776 long_richcompare, /* tp_richcompare */
4777 0, /* tp_weaklistoffset */
4778 0, /* tp_iter */
4779 0, /* tp_iternext */
4780 long_methods, /* tp_methods */
4781 0, /* tp_members */
4782 long_getset, /* tp_getset */
4783 0, /* tp_base */
4784 0, /* tp_dict */
4785 0, /* tp_descr_get */
4786 0, /* tp_descr_set */
4787 0, /* tp_dictoffset */
4788 0, /* tp_init */
4789 0, /* tp_alloc */
4790 long_new, /* tp_new */
4791 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004792};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004793
Mark Dickinsonbd792642009-03-18 20:06:12 +00004794static PyTypeObject Int_InfoType;
4795
4796PyDoc_STRVAR(int_info__doc__,
4797"sys.int_info\n\
4798\n\
4799A struct sequence that holds information about Python's\n\
4800internal representation of integers. The attributes are read only.");
4801
4802static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004804 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004805 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004806};
4807
4808static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 "sys.int_info", /* name */
4810 int_info__doc__, /* doc */
4811 int_info_fields, /* fields */
4812 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004813};
4814
4815PyObject *
4816PyLong_GetInfo(void)
4817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004818 PyObject* int_info;
4819 int field = 0;
4820 int_info = PyStructSequence_New(&Int_InfoType);
4821 if (int_info == NULL)
4822 return NULL;
4823 PyStructSequence_SET_ITEM(int_info, field++,
4824 PyLong_FromLong(PyLong_SHIFT));
4825 PyStructSequence_SET_ITEM(int_info, field++,
4826 PyLong_FromLong(sizeof(digit)));
4827 if (PyErr_Occurred()) {
4828 Py_CLEAR(int_info);
4829 return NULL;
4830 }
4831 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004832}
4833
Guido van Rossumddefaf32007-01-14 03:31:43 +00004834int
4835_PyLong_Init(void)
4836{
4837#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 int ival, size;
4839 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4842 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4843 if (Py_TYPE(v) == &PyLong_Type) {
4844 /* The element is already initialized, most likely
4845 * the Python interpreter was initialized before.
4846 */
4847 Py_ssize_t refcnt;
4848 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4851 _Py_NewReference(op);
4852 /* _Py_NewReference sets the ref count to 1 but
4853 * the ref count might be larger. Set the refcnt
4854 * to the original refcnt + 1 */
4855 Py_REFCNT(op) = refcnt + 1;
4856 assert(Py_SIZE(op) == size);
4857 assert(v->ob_digit[0] == abs(ival));
4858 }
4859 else {
4860 PyObject_INIT(v, &PyLong_Type);
4861 }
4862 Py_SIZE(v) = size;
4863 v->ob_digit[0] = abs(ival);
4864 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004865#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004866 /* initialize int_info */
4867 if (Int_InfoType.tp_name == 0)
4868 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00004869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004870 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00004871}
4872
4873void
4874PyLong_Fini(void)
4875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004876 /* Integers are currently statically allocated. Py_DECREF is not
4877 needed, but Python must forget about the reference or multiple
4878 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00004879#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004880 int i;
4881 PyLongObject *v = small_ints;
4882 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
4883 _Py_DEC_REFTOTAL;
4884 _Py_ForgetReference((PyObject*)v);
4885 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00004886#endif
4887}