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