blob: d4dc45a23bc0dd1be829cf373fca9a6e2e390dbc [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
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
Serhiy Storchaka441d30f2013-01-19 12:26:26 +0200437/* Get a C int from a long int object or any object that has an __int__
438 method. Return -1 and set an error if overflow occurs. */
439
440int
441_PyLong_AsInt(PyObject *obj)
442{
443 int overflow;
444 long result = PyLong_AsLongAndOverflow(obj, &overflow);
445 if (overflow || result > INT_MAX || result < INT_MIN) {
446 /* XXX: could be cute and give a different
447 message for overflow == -1 */
448 PyErr_SetString(PyExc_OverflowError,
449 "Python int too large to convert to C int");
450 return -1;
451 }
452 return (int)result;
453}
454
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000455/* Get a Py_ssize_t from a long int object.
456 Returns -1 and sets an error condition if overflow occurs. */
457
458Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000459PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 register PyLongObject *v;
461 size_t x, prev;
462 Py_ssize_t i;
463 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (vv == NULL) {
466 PyErr_BadInternalCall();
467 return -1;
468 }
469 if (!PyLong_Check(vv)) {
470 PyErr_SetString(PyExc_TypeError, "an integer is required");
471 return -1;
472 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 v = (PyLongObject *)vv;
475 i = Py_SIZE(v);
476 switch (i) {
477 case -1: return -(sdigit)v->ob_digit[0];
478 case 0: return 0;
479 case 1: return v->ob_digit[0];
480 }
481 sign = 1;
482 x = 0;
483 if (i < 0) {
484 sign = -1;
485 i = -(i);
486 }
487 while (--i >= 0) {
488 prev = x;
489 x = (x << PyLong_SHIFT) | v->ob_digit[i];
490 if ((x >> PyLong_SHIFT) != prev)
491 goto overflow;
492 }
493 /* Haven't lost any bits, but casting to a signed type requires
494 * extra care (see comment above).
495 */
496 if (x <= (size_t)PY_SSIZE_T_MAX) {
497 return (Py_ssize_t)x * sign;
498 }
499 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
500 return PY_SSIZE_T_MIN;
501 }
502 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000503
Mark Dickinson22b20182010-05-10 21:27:53 +0000504 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyErr_SetString(PyExc_OverflowError,
506 "Python int too large to convert to C ssize_t");
507 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000508}
509
Guido van Rossumd8c80482002-08-13 00:24:58 +0000510/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000511 Returns -1 and sets an error condition if overflow occurs. */
512
513unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000514PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 register PyLongObject *v;
517 unsigned long x, prev;
518 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (vv == NULL) {
521 PyErr_BadInternalCall();
522 return (unsigned long)-1;
523 }
524 if (!PyLong_Check(vv)) {
525 PyErr_SetString(PyExc_TypeError, "an integer is required");
526 return (unsigned long)-1;
527 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 v = (PyLongObject *)vv;
530 i = Py_SIZE(v);
531 x = 0;
532 if (i < 0) {
533 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000534 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return (unsigned long) -1;
536 }
537 switch (i) {
538 case 0: return 0;
539 case 1: return v->ob_digit[0];
540 }
541 while (--i >= 0) {
542 prev = x;
543 x = (x << PyLong_SHIFT) | v->ob_digit[i];
544 if ((x >> PyLong_SHIFT) != prev) {
545 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000546 "python int too large to convert "
547 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return (unsigned long) -1;
549 }
550 }
551 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000552}
553
Stefan Krahb77c6c62011-09-12 16:22:47 +0200554/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
555 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000556
557size_t
558PyLong_AsSize_t(PyObject *vv)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 register PyLongObject *v;
561 size_t x, prev;
562 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (vv == NULL) {
565 PyErr_BadInternalCall();
566 return (size_t) -1;
567 }
568 if (!PyLong_Check(vv)) {
569 PyErr_SetString(PyExc_TypeError, "an integer is required");
570 return (size_t)-1;
571 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 v = (PyLongObject *)vv;
574 i = Py_SIZE(v);
575 x = 0;
576 if (i < 0) {
577 PyErr_SetString(PyExc_OverflowError,
578 "can't convert negative value to size_t");
579 return (size_t) -1;
580 }
581 switch (i) {
582 case 0: return 0;
583 case 1: return v->ob_digit[0];
584 }
585 while (--i >= 0) {
586 prev = x;
587 x = (x << PyLong_SHIFT) | v->ob_digit[i];
588 if ((x >> PyLong_SHIFT) != prev) {
589 PyErr_SetString(PyExc_OverflowError,
590 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200591 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 }
593 }
594 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000595}
596
Thomas Hellera4ea6032003-04-17 18:55:45 +0000597/* Get a C unsigned long int from a long int object, ignoring the high bits.
598 Returns -1 and sets an error condition if an error occurs. */
599
Guido van Rossumddefaf32007-01-14 03:31:43 +0000600static unsigned long
601_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 register PyLongObject *v;
604 unsigned long x;
605 Py_ssize_t i;
606 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (vv == NULL || !PyLong_Check(vv)) {
609 PyErr_BadInternalCall();
610 return (unsigned long) -1;
611 }
612 v = (PyLongObject *)vv;
613 i = Py_SIZE(v);
614 switch (i) {
615 case 0: return 0;
616 case 1: return v->ob_digit[0];
617 }
618 sign = 1;
619 x = 0;
620 if (i < 0) {
621 sign = -1;
622 i = -i;
623 }
624 while (--i >= 0) {
625 x = (x << PyLong_SHIFT) | v->ob_digit[i];
626 }
627 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000628}
629
Guido van Rossumddefaf32007-01-14 03:31:43 +0000630unsigned long
631PyLong_AsUnsignedLongMask(register PyObject *op)
632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PyNumberMethods *nb;
634 PyLongObject *lo;
635 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (op && PyLong_Check(op))
638 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
641 nb->nb_int == NULL) {
642 PyErr_SetString(PyExc_TypeError, "an integer is required");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 lo = (PyLongObject*) (*nb->nb_int) (op);
647 if (lo == NULL)
648 return (unsigned long)-1;
649 if (PyLong_Check(lo)) {
650 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
651 Py_DECREF(lo);
652 if (PyErr_Occurred())
653 return (unsigned long)-1;
654 return val;
655 }
656 else
657 {
658 Py_DECREF(lo);
659 PyErr_SetString(PyExc_TypeError,
660 "nb_int should return int object");
661 return (unsigned long)-1;
662 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000663}
664
Tim Peters5b8132f2003-01-31 15:52:05 +0000665int
666_PyLong_Sign(PyObject *vv)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 assert(v != NULL);
671 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000674}
675
Tim Petersbaefd9e2003-01-28 20:37:45 +0000676size_t
677_PyLong_NumBits(PyObject *vv)
678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyLongObject *v = (PyLongObject *)vv;
680 size_t result = 0;
681 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 assert(v != NULL);
684 assert(PyLong_Check(v));
685 ndigits = ABS(Py_SIZE(v));
686 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
687 if (ndigits > 0) {
688 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100689 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100691 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 do {
693 ++result;
694 if (result == 0)
695 goto Overflow;
696 msd >>= 1;
697 } while (msd);
698 }
699 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000700
Mark Dickinson22b20182010-05-10 21:27:53 +0000701 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
703 "to express in a platform size_t");
704 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000705}
706
Tim Peters2a9b3672001-06-11 21:23:58 +0000707PyObject *
708_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000710{
Mark Dickinson22b20182010-05-10 21:27:53 +0000711 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 int incr; /* direction to move pstartbyte */
713 const unsigned char* pendbyte; /* MSB of bytes */
714 size_t numsignificantbytes; /* number of bytes that matter */
715 Py_ssize_t ndigits; /* number of Python long digits */
716 PyLongObject* v; /* result */
717 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (n == 0)
720 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (little_endian) {
723 pstartbyte = bytes;
724 pendbyte = bytes + n - 1;
725 incr = 1;
726 }
727 else {
728 pstartbyte = bytes + n - 1;
729 pendbyte = bytes;
730 incr = -1;
731 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (is_signed)
734 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200737 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 is positive, and leading 0xff bytes if negative. */
739 {
740 size_t i;
741 const unsigned char* p = pendbyte;
742 const int pincr = -incr; /* search MSB to LSB */
743 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 for (i = 0; i < n; ++i, p += pincr) {
746 if (*p != insignficant)
747 break;
748 }
749 numsignificantbytes = n - i;
750 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
751 actually has 2 significant bytes. OTOH, 0xff0001 ==
752 -0x00ffff, so we wouldn't *need* to bump it there; but we
753 do for 0xffff = -0x0001. To be safe without bothering to
754 check every case, bump it regardless. */
755 if (is_signed && numsignificantbytes < n)
756 ++numsignificantbytes;
757 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* How many Python long digits do we need? We have
760 8*numsignificantbytes bits, and each Python long digit has
761 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
762 /* catch overflow before it happens */
763 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
764 PyErr_SetString(PyExc_OverflowError,
765 "byte array too long to convert to int");
766 return NULL;
767 }
768 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
769 v = _PyLong_New(ndigits);
770 if (v == NULL)
771 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 /* Copy the bits over. The tricky parts are computing 2's-comp on
774 the fly for signed numbers, and dealing with the mismatch between
775 8-bit bytes and (probably) 15-bit Python digits.*/
776 {
777 size_t i;
778 twodigits carry = 1; /* for 2's-comp calculation */
779 twodigits accum = 0; /* sliding register */
780 unsigned int accumbits = 0; /* number of bits in accum */
781 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
784 twodigits thisbyte = *p;
785 /* Compute correction for 2's comp, if needed. */
786 if (is_signed) {
787 thisbyte = (0xff ^ thisbyte) + carry;
788 carry = thisbyte >> 8;
789 thisbyte &= 0xff;
790 }
791 /* Because we're going LSB to MSB, thisbyte is
792 more significant than what's already in accum,
793 so needs to be prepended to accum. */
794 accum |= (twodigits)thisbyte << accumbits;
795 accumbits += 8;
796 if (accumbits >= PyLong_SHIFT) {
797 /* There's enough to fill a Python digit. */
798 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000799 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 ++idigit;
801 accum >>= PyLong_SHIFT;
802 accumbits -= PyLong_SHIFT;
803 assert(accumbits < PyLong_SHIFT);
804 }
805 }
806 assert(accumbits < PyLong_SHIFT);
807 if (accumbits) {
808 assert(idigit < ndigits);
809 v->ob_digit[idigit] = (digit)accum;
810 ++idigit;
811 }
812 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_SIZE(v) = is_signed ? -idigit : idigit;
815 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000816}
817
818int
819_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 unsigned char* bytes, size_t n,
821 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000824 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000826 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
828 digit carry; /* for computing 2's-comp */
829 size_t j; /* # bytes filled */
830 unsigned char* p; /* pointer to next byte in bytes */
831 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (Py_SIZE(v) < 0) {
836 ndigits = -(Py_SIZE(v));
837 if (!is_signed) {
838 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000839 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return -1;
841 }
842 do_twos_comp = 1;
843 }
844 else {
845 ndigits = Py_SIZE(v);
846 do_twos_comp = 0;
847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (little_endian) {
850 p = bytes;
851 pincr = 1;
852 }
853 else {
854 p = bytes + n - 1;
855 pincr = -1;
856 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* Copy over all the Python digits.
859 It's crucial that every Python digit except for the MSD contribute
860 exactly PyLong_SHIFT bits to the total, so first assert that the long is
861 normalized. */
862 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
863 j = 0;
864 accum = 0;
865 accumbits = 0;
866 carry = do_twos_comp ? 1 : 0;
867 for (i = 0; i < ndigits; ++i) {
868 digit thisdigit = v->ob_digit[i];
869 if (do_twos_comp) {
870 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
871 carry = thisdigit >> PyLong_SHIFT;
872 thisdigit &= PyLong_MASK;
873 }
874 /* Because we're going LSB to MSB, thisdigit is more
875 significant than what's already in accum, so needs to be
876 prepended to accum. */
877 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* The most-significant digit may be (probably is) at least
880 partly empty. */
881 if (i == ndigits - 1) {
882 /* Count # of sign bits -- they needn't be stored,
883 * although for signed conversion we need later to
884 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000885 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 while (s != 0) {
887 s >>= 1;
888 accumbits++;
889 }
890 }
891 else
892 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Store as many bytes as possible. */
895 while (accumbits >= 8) {
896 if (j >= n)
897 goto Overflow;
898 ++j;
899 *p = (unsigned char)(accum & 0xff);
900 p += pincr;
901 accumbits -= 8;
902 accum >>= 8;
903 }
904 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Store the straggler (if any). */
907 assert(accumbits < 8);
908 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
909 if (accumbits > 0) {
910 if (j >= n)
911 goto Overflow;
912 ++j;
913 if (do_twos_comp) {
914 /* Fill leading bits of the byte with sign bits
915 (appropriately pretending that the long had an
916 infinite supply of sign bits). */
917 accum |= (~(twodigits)0) << accumbits;
918 }
919 *p = (unsigned char)(accum & 0xff);
920 p += pincr;
921 }
922 else if (j == n && n > 0 && is_signed) {
923 /* The main loop filled the byte array exactly, so the code
924 just above didn't get to ensure there's a sign bit, and the
925 loop below wouldn't add one either. Make sure a sign bit
926 exists. */
927 unsigned char msb = *(p - pincr);
928 int sign_bit_set = msb >= 0x80;
929 assert(accumbits == 0);
930 if (sign_bit_set == do_twos_comp)
931 return 0;
932 else
933 goto Overflow;
934 }
Tim Peters05607ad2001-06-13 21:01:27 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Fill remaining bytes with copies of the sign bit. */
937 {
938 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
939 for ( ; j < n; ++j, p += pincr)
940 *p = signbyte;
941 }
Tim Peters05607ad2001-06-13 21:01:27 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000944
Mark Dickinson22b20182010-05-10 21:27:53 +0000945 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
947 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000948
Tim Peters2a9b3672001-06-11 21:23:58 +0000949}
950
Mark Dickinson8d48b432011-10-23 20:47:14 +0100951/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000952
953PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000954PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000955{
Mark Dickinson91044792012-10-18 19:21:43 +0100956#if SIZEOF_VOID_P <= SIZEOF_LONG
957 /* special-case null pointer */
958 if (!p)
959 return PyLong_FromLong(0);
960 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
961#else
962
Tim Peters70128a12001-06-16 08:48:40 +0000963#ifndef HAVE_LONG_LONG
964# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
965#endif
966#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000968#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* special-case null pointer */
970 if (!p)
971 return PyLong_FromLong(0);
972 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100973#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000974
Guido van Rossum78694d91998-09-18 14:14:13 +0000975}
976
Mark Dickinson8d48b432011-10-23 20:47:14 +0100977/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000978
979void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000980PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000981{
Tim Peters70128a12001-06-16 08:48:40 +0000982#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
986 x = PyLong_AsLong(vv);
987 else
988 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000989#else
Tim Peters70128a12001-06-16 08:48:40 +0000990
991#ifndef HAVE_LONG_LONG
992# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
993#endif
994#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000996#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1000 x = PyLong_AsLongLong(vv);
1001 else
1002 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001003
1004#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (x == -1 && PyErr_Occurred())
1007 return NULL;
1008 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009}
1010
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001011#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001012
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001013/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001014 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001015 */
1016
Tim Peterscf37dfc2001-06-14 18:42:50 +00001017#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +00001018#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001019
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001020/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021
1022PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyLongObject *v;
1026 unsigned PY_LONG_LONG abs_ival;
1027 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1028 int ndigits = 0;
1029 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 CHECK_SMALL_INT(ival);
1032 if (ival < 0) {
1033 /* avoid signed overflow on negation; see comments
1034 in PyLong_FromLong above. */
1035 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1036 negative = 1;
1037 }
1038 else {
1039 abs_ival = (unsigned PY_LONG_LONG)ival;
1040 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 /* Count the number of Python digits.
1043 We used to pick 5 ("big enough for anything"), but that's a
1044 waste of time and space given that 5*15 = 75 bits are rarely
1045 needed. */
1046 t = abs_ival;
1047 while (t) {
1048 ++ndigits;
1049 t >>= PyLong_SHIFT;
1050 }
1051 v = _PyLong_New(ndigits);
1052 if (v != NULL) {
1053 digit *p = v->ob_digit;
1054 Py_SIZE(v) = negative ? -ndigits : ndigits;
1055 t = abs_ival;
1056 while (t) {
1057 *p++ = (digit)(t & PyLong_MASK);
1058 t >>= PyLong_SHIFT;
1059 }
1060 }
1061 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001062}
1063
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001064/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001065
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001067PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyLongObject *v;
1070 unsigned PY_LONG_LONG t;
1071 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (ival < PyLong_BASE)
1074 return PyLong_FromLong((long)ival);
1075 /* Count the number of Python digits. */
1076 t = (unsigned PY_LONG_LONG)ival;
1077 while (t) {
1078 ++ndigits;
1079 t >>= PyLong_SHIFT;
1080 }
1081 v = _PyLong_New(ndigits);
1082 if (v != NULL) {
1083 digit *p = v->ob_digit;
1084 Py_SIZE(v) = ndigits;
1085 while (ival) {
1086 *p++ = (digit)(ival & PyLong_MASK);
1087 ival >>= PyLong_SHIFT;
1088 }
1089 }
1090 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001091}
1092
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093/* Create a new long int object from a C Py_ssize_t. */
1094
1095PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001096PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyLongObject *v;
1099 size_t abs_ival;
1100 size_t t; /* unsigned so >> doesn't propagate sign bit */
1101 int ndigits = 0;
1102 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 CHECK_SMALL_INT(ival);
1105 if (ival < 0) {
1106 /* avoid signed overflow when ival = SIZE_T_MIN */
1107 abs_ival = (size_t)(-1-ival)+1;
1108 negative = 1;
1109 }
1110 else {
1111 abs_ival = (size_t)ival;
1112 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* Count the number of Python digits. */
1115 t = abs_ival;
1116 while (t) {
1117 ++ndigits;
1118 t >>= PyLong_SHIFT;
1119 }
1120 v = _PyLong_New(ndigits);
1121 if (v != NULL) {
1122 digit *p = v->ob_digit;
1123 Py_SIZE(v) = negative ? -ndigits : ndigits;
1124 t = abs_ival;
1125 while (t) {
1126 *p++ = (digit)(t & PyLong_MASK);
1127 t >>= PyLong_SHIFT;
1128 }
1129 }
1130 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131}
1132
1133/* Create a new long int object from a C size_t. */
1134
1135PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001136PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyLongObject *v;
1139 size_t t;
1140 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (ival < PyLong_BASE)
1143 return PyLong_FromLong((long)ival);
1144 /* Count the number of Python digits. */
1145 t = ival;
1146 while (t) {
1147 ++ndigits;
1148 t >>= PyLong_SHIFT;
1149 }
1150 v = _PyLong_New(ndigits);
1151 if (v != NULL) {
1152 digit *p = v->ob_digit;
1153 Py_SIZE(v) = ndigits;
1154 while (ival) {
1155 *p++ = (digit)(ival & PyLong_MASK);
1156 ival >>= PyLong_SHIFT;
1157 }
1158 }
1159 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001160}
1161
Mark Dickinson8d48b432011-10-23 20:47:14 +01001162/* Get a C long long int from a long int object or any object that has an
1163 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001164
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001165PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001166PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyLongObject *v;
1169 PY_LONG_LONG bytes;
1170 int one = 1;
1171 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (vv == NULL) {
1174 PyErr_BadInternalCall();
1175 return -1;
1176 }
1177 if (!PyLong_Check(vv)) {
1178 PyNumberMethods *nb;
1179 PyObject *io;
1180 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1181 nb->nb_int == NULL) {
1182 PyErr_SetString(PyExc_TypeError, "an integer is required");
1183 return -1;
1184 }
1185 io = (*nb->nb_int) (vv);
1186 if (io == NULL)
1187 return -1;
1188 if (PyLong_Check(io)) {
1189 bytes = PyLong_AsLongLong(io);
1190 Py_DECREF(io);
1191 return bytes;
1192 }
1193 Py_DECREF(io);
1194 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1195 return -1;
1196 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 v = (PyLongObject*)vv;
1199 switch(Py_SIZE(v)) {
1200 case -1: return -(sdigit)v->ob_digit[0];
1201 case 0: return 0;
1202 case 1: return v->ob_digit[0];
1203 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001204 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1205 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1208 if (res < 0)
1209 return (PY_LONG_LONG)-1;
1210 else
1211 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001212}
1213
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001214/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001215 Return -1 and set an error if overflow occurs. */
1216
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001217unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001218PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyLongObject *v;
1221 unsigned PY_LONG_LONG bytes;
1222 int one = 1;
1223 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001224
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001225 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyErr_BadInternalCall();
1227 return (unsigned PY_LONG_LONG)-1;
1228 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001229 if (!PyLong_Check(vv)) {
1230 PyErr_SetString(PyExc_TypeError, "an integer is required");
1231 return (unsigned PY_LONG_LONG)-1;
1232 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 v = (PyLongObject*)vv;
1235 switch(Py_SIZE(v)) {
1236 case 0: return 0;
1237 case 1: return v->ob_digit[0];
1238 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001239
Mark Dickinson22b20182010-05-10 21:27:53 +00001240 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1241 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1244 if (res < 0)
1245 return (unsigned PY_LONG_LONG)res;
1246 else
1247 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001248}
Tim Petersd1a7da62001-06-13 00:35:57 +00001249
Thomas Hellera4ea6032003-04-17 18:55:45 +00001250/* Get a C unsigned long int from a long int object, ignoring the high bits.
1251 Returns -1 and sets an error condition if an error occurs. */
1252
Guido van Rossumddefaf32007-01-14 03:31:43 +00001253static unsigned PY_LONG_LONG
1254_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 register PyLongObject *v;
1257 unsigned PY_LONG_LONG x;
1258 Py_ssize_t i;
1259 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (vv == NULL || !PyLong_Check(vv)) {
1262 PyErr_BadInternalCall();
1263 return (unsigned long) -1;
1264 }
1265 v = (PyLongObject *)vv;
1266 switch(Py_SIZE(v)) {
1267 case 0: return 0;
1268 case 1: return v->ob_digit[0];
1269 }
1270 i = Py_SIZE(v);
1271 sign = 1;
1272 x = 0;
1273 if (i < 0) {
1274 sign = -1;
1275 i = -i;
1276 }
1277 while (--i >= 0) {
1278 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1279 }
1280 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001281}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001282
1283unsigned PY_LONG_LONG
1284PyLong_AsUnsignedLongLongMask(register PyObject *op)
1285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyNumberMethods *nb;
1287 PyLongObject *lo;
1288 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (op && PyLong_Check(op))
1291 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1294 nb->nb_int == NULL) {
1295 PyErr_SetString(PyExc_TypeError, "an integer is required");
1296 return (unsigned PY_LONG_LONG)-1;
1297 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 lo = (PyLongObject*) (*nb->nb_int) (op);
1300 if (lo == NULL)
1301 return (unsigned PY_LONG_LONG)-1;
1302 if (PyLong_Check(lo)) {
1303 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1304 Py_DECREF(lo);
1305 if (PyErr_Occurred())
1306 return (unsigned PY_LONG_LONG)-1;
1307 return val;
1308 }
1309 else
1310 {
1311 Py_DECREF(lo);
1312 PyErr_SetString(PyExc_TypeError,
1313 "nb_int should return int object");
1314 return (unsigned PY_LONG_LONG)-1;
1315 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001316}
Tim Petersd1a7da62001-06-13 00:35:57 +00001317#undef IS_LITTLE_ENDIAN
1318
Mark Dickinson8d48b432011-10-23 20:47:14 +01001319/* Get a C long long int from a long int object or any object that has an
1320 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001321
Mark Dickinson8d48b432011-10-23 20:47:14 +01001322 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1323 the result. Otherwise *overflow is 0.
1324
1325 For other errors (e.g., TypeError), return -1 and set an error condition.
1326 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001327*/
1328
1329PY_LONG_LONG
1330PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* This version by Tim Peters */
1333 register PyLongObject *v;
1334 unsigned PY_LONG_LONG x, prev;
1335 PY_LONG_LONG res;
1336 Py_ssize_t i;
1337 int sign;
1338 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 *overflow = 0;
1341 if (vv == NULL) {
1342 PyErr_BadInternalCall();
1343 return -1;
1344 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (!PyLong_Check(vv)) {
1347 PyNumberMethods *nb;
1348 nb = vv->ob_type->tp_as_number;
1349 if (nb == NULL || nb->nb_int == NULL) {
1350 PyErr_SetString(PyExc_TypeError,
1351 "an integer is required");
1352 return -1;
1353 }
1354 vv = (*nb->nb_int) (vv);
1355 if (vv == NULL)
1356 return -1;
1357 do_decref = 1;
1358 if (!PyLong_Check(vv)) {
1359 Py_DECREF(vv);
1360 PyErr_SetString(PyExc_TypeError,
1361 "nb_int should return int object");
1362 return -1;
1363 }
1364 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 res = -1;
1367 v = (PyLongObject *)vv;
1368 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 switch (i) {
1371 case -1:
1372 res = -(sdigit)v->ob_digit[0];
1373 break;
1374 case 0:
1375 res = 0;
1376 break;
1377 case 1:
1378 res = v->ob_digit[0];
1379 break;
1380 default:
1381 sign = 1;
1382 x = 0;
1383 if (i < 0) {
1384 sign = -1;
1385 i = -(i);
1386 }
1387 while (--i >= 0) {
1388 prev = x;
1389 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1390 if ((x >> PyLong_SHIFT) != prev) {
1391 *overflow = sign;
1392 goto exit;
1393 }
1394 }
1395 /* Haven't lost any bits, but casting to long requires extra
1396 * care (see comment above).
1397 */
1398 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1399 res = (PY_LONG_LONG)x * sign;
1400 }
1401 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1402 res = PY_LLONG_MIN;
1403 }
1404 else {
1405 *overflow = sign;
1406 /* res is already set to -1 */
1407 }
1408 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001409 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (do_decref) {
1411 Py_DECREF(vv);
1412 }
1413 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001414}
1415
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001416#endif /* HAVE_LONG_LONG */
1417
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001418#define CHECK_BINOP(v,w) \
1419 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001420 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1421 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001422 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001423
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001424/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1425 2**k if d is nonzero, else 0. */
1426
1427static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1429 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001430};
1431
1432static int
1433bits_in_digit(digit d)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 int d_bits = 0;
1436 while (d >= 32) {
1437 d_bits += 6;
1438 d >>= 6;
1439 }
1440 d_bits += (int)BitLengthTable[d];
1441 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001442}
1443
Tim Peters877a2122002-08-12 05:09:36 +00001444/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1445 * is modified in place, by adding y to it. Carries are propagated as far as
1446 * x[m-1], and the remaining carry (0 or 1) is returned.
1447 */
1448static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001449v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 Py_ssize_t i;
1452 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 assert(m >= n);
1455 for (i = 0; i < n; ++i) {
1456 carry += x[i] + y[i];
1457 x[i] = carry & PyLong_MASK;
1458 carry >>= PyLong_SHIFT;
1459 assert((carry & 1) == carry);
1460 }
1461 for (; carry && i < m; ++i) {
1462 carry += x[i];
1463 x[i] = carry & PyLong_MASK;
1464 carry >>= PyLong_SHIFT;
1465 assert((carry & 1) == carry);
1466 }
1467 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001468}
1469
1470/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1471 * is modified in place, by subtracting y from it. Borrows are propagated as
1472 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1473 */
1474static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001475v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 Py_ssize_t i;
1478 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 assert(m >= n);
1481 for (i = 0; i < n; ++i) {
1482 borrow = x[i] - y[i] - borrow;
1483 x[i] = borrow & PyLong_MASK;
1484 borrow >>= PyLong_SHIFT;
1485 borrow &= 1; /* keep only 1 sign bit */
1486 }
1487 for (; borrow && i < m; ++i) {
1488 borrow = x[i] - borrow;
1489 x[i] = borrow & PyLong_MASK;
1490 borrow >>= PyLong_SHIFT;
1491 borrow &= 1;
1492 }
1493 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001494}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001495
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001496/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1497 * result in z[0:m], and return the d bits shifted out of the top.
1498 */
1499static digit
1500v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 Py_ssize_t i;
1503 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 assert(0 <= d && d < PyLong_SHIFT);
1506 for (i=0; i < m; i++) {
1507 twodigits acc = (twodigits)a[i] << d | carry;
1508 z[i] = (digit)acc & PyLong_MASK;
1509 carry = (digit)(acc >> PyLong_SHIFT);
1510 }
1511 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001512}
1513
1514/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1515 * result in z[0:m], and return the d bits shifted out of the bottom.
1516 */
1517static digit
1518v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_ssize_t i;
1521 digit carry = 0;
1522 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 assert(0 <= d && d < PyLong_SHIFT);
1525 for (i=m; i-- > 0;) {
1526 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1527 carry = (digit)acc & mask;
1528 z[i] = (digit)(acc >> d);
1529 }
1530 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001531}
1532
Tim Peters212e6142001-07-14 12:23:19 +00001533/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1534 in pout, and returning the remainder. pin and pout point at the LSD.
1535 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001536 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001537 immutable. */
1538
1539static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001540inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 assert(n > 0 && n <= PyLong_MASK);
1545 pin += size;
1546 pout += size;
1547 while (--size >= 0) {
1548 digit hi;
1549 rem = (rem << PyLong_SHIFT) | *--pin;
1550 *--pout = hi = (digit)(rem / n);
1551 rem -= (twodigits)hi * n;
1552 }
1553 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001554}
1555
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001556/* Divide a long integer by a digit, returning both the quotient
1557 (as function result) and the remainder (through *prem).
1558 The sign of a is ignored; n should not be zero. */
1559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001560static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001561divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 const Py_ssize_t size = ABS(Py_SIZE(a));
1564 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 assert(n > 0 && n <= PyLong_MASK);
1567 z = _PyLong_New(size);
1568 if (z == NULL)
1569 return NULL;
1570 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1571 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001572}
1573
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001574/* Convert a long integer to a base 10 string. Returns a new non-shared
1575 string. (Return value is non-shared so that callers can modify the
1576 returned value if necessary.) */
1577
Victor Stinnerd3f08822012-05-29 12:57:52 +02001578static int
1579long_to_decimal_string_internal(PyObject *aa,
1580 PyObject **p_output,
1581 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 PyLongObject *scratch, *a;
1584 PyObject *str;
1585 Py_ssize_t size, strlen, size_a, i, j;
1586 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001588 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 a = (PyLongObject *)aa;
1591 if (a == NULL || !PyLong_Check(a)) {
1592 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001593 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
1595 size_a = ABS(Py_SIZE(a));
1596 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 /* quick and dirty upper bound for the number of digits
1599 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 But log2(a) < size_a * PyLong_SHIFT, and
1604 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1605 > 3 * _PyLong_DECIMAL_SHIFT
1606 */
1607 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1608 PyErr_SetString(PyExc_OverflowError,
1609 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001610 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 }
1612 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1613 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1614 scratch = _PyLong_New(size);
1615 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001616 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* convert array of base _PyLong_BASE digits in pin to an array of
1619 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1620 Volume 2 (3rd edn), section 4.4, Method 1b). */
1621 pin = a->ob_digit;
1622 pout = scratch->ob_digit;
1623 size = 0;
1624 for (i = size_a; --i >= 0; ) {
1625 digit hi = pin[i];
1626 for (j = 0; j < size; j++) {
1627 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1628 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1629 pout[j] = (digit)(z - (twodigits)hi *
1630 _PyLong_DECIMAL_BASE);
1631 }
1632 while (hi) {
1633 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1634 hi /= _PyLong_DECIMAL_BASE;
1635 }
1636 /* check for keyboard interrupt */
1637 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001638 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001639 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001640 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 }
1642 /* pout should have at least one digit, so that the case when a = 0
1643 works correctly */
1644 if (size == 0)
1645 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* calculate exact length of output string, and allocate */
1648 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1649 tenpow = 10;
1650 rem = pout[size-1];
1651 while (rem >= tenpow) {
1652 tenpow *= 10;
1653 strlen++;
1654 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001655 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001656 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1657 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001658 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001659 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001660 kind = writer->kind;
1661 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001663 else {
1664 str = PyUnicode_New(strlen, '9');
1665 if (str == NULL) {
1666 Py_DECREF(scratch);
1667 return -1;
1668 }
1669 kind = PyUnicode_KIND(str);
1670 }
1671
1672#define WRITE_DIGITS(TYPE) \
1673 do { \
1674 if (writer) \
1675 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1676 else \
1677 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1678 \
1679 *p = '\0'; \
1680 /* pout[0] through pout[size-2] contribute exactly \
1681 _PyLong_DECIMAL_SHIFT digits each */ \
1682 for (i=0; i < size - 1; i++) { \
1683 rem = pout[i]; \
1684 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1685 *--p = '0' + rem % 10; \
1686 rem /= 10; \
1687 } \
1688 } \
1689 /* pout[size-1]: always produce at least one decimal digit */ \
1690 rem = pout[i]; \
1691 do { \
1692 *--p = '0' + rem % 10; \
1693 rem /= 10; \
1694 } while (rem != 0); \
1695 \
1696 /* and sign */ \
1697 if (negative) \
1698 *--p = '-'; \
1699 \
1700 /* check we've counted correctly */ \
1701 if (writer) \
1702 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1703 else \
1704 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1705 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 if (kind == PyUnicode_1BYTE_KIND) {
1709 Py_UCS1 *p;
1710 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001712 else if (kind == PyUnicode_2BYTE_KIND) {
1713 Py_UCS2 *p;
1714 WRITE_DIGITS(Py_UCS2);
1715 }
1716 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001718 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 WRITE_DIGITS(Py_UCS4);
1720 }
1721#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001724 if (writer) {
1725 writer->pos += strlen;
1726 }
1727 else {
1728 assert(_PyUnicode_CheckConsistency(str, 1));
1729 *p_output = (PyObject *)str;
1730 }
1731 return 0;
1732}
1733
1734static PyObject *
1735long_to_decimal_string(PyObject *aa)
1736{
1737 PyObject *v;
1738 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1739 return NULL;
1740 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001741}
1742
Mark Dickinsoncd068122009-09-18 14:53:08 +00001743/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001744 which should be one of 2, 8 or 16. Return a string object.
1745 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1746 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001747
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748static int
1749long_format_binary(PyObject *aa, int base, int alternate,
1750 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001754 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001756 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001757 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001759
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (a == NULL || !PyLong_Check(a)) {
1762 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 }
1765 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001766 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* Compute a rough upper bound for the length of the string */
1769 switch (base) {
1770 case 16:
1771 bits = 4;
1772 break;
1773 case 8:
1774 bits = 3;
1775 break;
1776 case 2:
1777 bits = 1;
1778 break;
1779 default:
1780 assert(0); /* shouldn't ever get here */
1781 bits = 0; /* to silence gcc warning */
1782 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001783
Mark Dickinsone2846542012-04-20 21:21:24 +01001784 /* Compute exact length 'sz' of output string. */
1785 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001787 }
1788 else {
1789 Py_ssize_t size_a_in_bits;
1790 /* Ensure overflow doesn't occur during computation of sz. */
1791 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1792 PyErr_SetString(PyExc_OverflowError,
1793 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001794 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001795 }
1796 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1797 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001798 /* Allow 1 character for a '-' sign. */
1799 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1800 }
1801 if (alternate) {
1802 /* 2 characters for prefix */
1803 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001804 }
1805
Victor Stinnerd3f08822012-05-29 12:57:52 +02001806 if (writer) {
1807 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1808 return -1;
1809 kind = writer->kind;
1810 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 }
1812 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 v = PyUnicode_New(sz, 'x');
1814 if (v == NULL)
1815 return -1;
1816 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001818
Victor Stinnerd3f08822012-05-29 12:57:52 +02001819#define WRITE_DIGITS(TYPE) \
1820 do { \
1821 if (writer) \
1822 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1823 else \
1824 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1825 \
1826 if (size_a == 0) { \
1827 *--p = '0'; \
1828 } \
1829 else { \
1830 /* JRH: special case for power-of-2 bases */ \
1831 twodigits accum = 0; \
1832 int accumbits = 0; /* # of bits in accum */ \
1833 Py_ssize_t i; \
1834 for (i = 0; i < size_a; ++i) { \
1835 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1836 accumbits += PyLong_SHIFT; \
1837 assert(accumbits >= bits); \
1838 do { \
1839 char cdigit; \
1840 cdigit = (char)(accum & (base - 1)); \
1841 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1842 *--p = cdigit; \
1843 accumbits -= bits; \
1844 accum >>= bits; \
1845 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1846 } \
1847 } \
1848 \
1849 if (alternate) { \
1850 if (base == 16) \
1851 *--p = 'x'; \
1852 else if (base == 8) \
1853 *--p = 'o'; \
1854 else /* (base == 2) */ \
1855 *--p = 'b'; \
1856 *--p = '0'; \
1857 } \
1858 if (negative) \
1859 *--p = '-'; \
1860 if (writer) \
1861 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1862 else \
1863 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1864 } while (0)
1865
1866 if (kind == PyUnicode_1BYTE_KIND) {
1867 Py_UCS1 *p;
1868 WRITE_DIGITS(Py_UCS1);
1869 }
1870 else if (kind == PyUnicode_2BYTE_KIND) {
1871 Py_UCS2 *p;
1872 WRITE_DIGITS(Py_UCS2);
1873 }
1874 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001875 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001876 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001877 WRITE_DIGITS(Py_UCS4);
1878 }
1879#undef WRITE_DIGITS
1880
1881 if (writer) {
1882 writer->pos += sz;
1883 }
1884 else {
1885 assert(_PyUnicode_CheckConsistency(v, 1));
1886 *p_output = v;
1887 }
1888 return 0;
1889}
1890
1891PyObject *
1892_PyLong_Format(PyObject *obj, int base)
1893{
1894 PyObject *str;
1895 int err;
1896 if (base == 10)
1897 err = long_to_decimal_string_internal(obj, &str, NULL);
1898 else
1899 err = long_format_binary(obj, base, 1, &str, NULL);
1900 if (err == -1)
1901 return NULL;
1902 return str;
1903}
1904
1905int
1906_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1907 PyObject *obj,
1908 int base, int alternate)
1909{
1910 if (base == 10)
1911 return long_to_decimal_string_internal(obj, NULL, writer);
1912 else
1913 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001914}
1915
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916/* Table of digit values for 8-bit string -> integer conversion.
1917 * '0' maps to 0, ..., '9' maps to 9.
1918 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1919 * All other indices map to 37.
1920 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001921 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001923unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1925 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1926 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1927 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1928 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1929 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1930 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1931 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1932 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1933 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1934 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1935 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1936 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1937 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1938 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1939 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001940};
1941
1942/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001943 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1944 * non-digit (which may be *str!). A normalized long is returned.
1945 * The point to this routine is that it takes time linear in the number of
1946 * string characters.
1947 */
1948static PyLongObject *
1949long_from_binary_base(char **str, int base)
1950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 char *p = *str;
1952 char *start = p;
1953 int bits_per_char;
1954 Py_ssize_t n;
1955 PyLongObject *z;
1956 twodigits accum;
1957 int bits_in_accum;
1958 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1961 n = base;
1962 for (bits_per_char = -1; n; ++bits_per_char)
1963 n >>= 1;
1964 /* n <- total # of bits needed, while setting p to end-of-string */
1965 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1966 ++p;
1967 *str = p;
1968 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1969 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1970 if (n / bits_per_char < p - start) {
1971 PyErr_SetString(PyExc_ValueError,
1972 "int string too large to convert");
1973 return NULL;
1974 }
1975 n = n / PyLong_SHIFT;
1976 z = _PyLong_New(n);
1977 if (z == NULL)
1978 return NULL;
1979 /* Read string from right, and fill in long from left; i.e.,
1980 * from least to most significant in both.
1981 */
1982 accum = 0;
1983 bits_in_accum = 0;
1984 pdigit = z->ob_digit;
1985 while (--p >= start) {
1986 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1987 assert(k >= 0 && k < base);
1988 accum |= (twodigits)k << bits_in_accum;
1989 bits_in_accum += bits_per_char;
1990 if (bits_in_accum >= PyLong_SHIFT) {
1991 *pdigit++ = (digit)(accum & PyLong_MASK);
1992 assert(pdigit - z->ob_digit <= n);
1993 accum >>= PyLong_SHIFT;
1994 bits_in_accum -= PyLong_SHIFT;
1995 assert(bits_in_accum < PyLong_SHIFT);
1996 }
1997 }
1998 if (bits_in_accum) {
1999 assert(bits_in_accum <= PyLong_SHIFT);
2000 *pdigit++ = (digit)accum;
2001 assert(pdigit - z->ob_digit <= n);
2002 }
2003 while (pdigit - z->ob_digit < n)
2004 *pdigit++ = 0;
2005 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002006}
2007
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002008PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002009PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 int sign = 1, error_if_nonzero = 0;
2012 char *start, *orig_str = str;
2013 PyLongObject *z = NULL;
2014 PyObject *strobj;
2015 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 if ((base != 0 && base < 2) || base > 36) {
2018 PyErr_SetString(PyExc_ValueError,
2019 "int() arg 2 must be >= 2 and <= 36");
2020 return NULL;
2021 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002022 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 str++;
2024 if (*str == '+')
2025 ++str;
2026 else if (*str == '-') {
2027 ++str;
2028 sign = -1;
2029 }
2030 if (base == 0) {
2031 if (str[0] != '0')
2032 base = 10;
2033 else if (str[1] == 'x' || str[1] == 'X')
2034 base = 16;
2035 else if (str[1] == 'o' || str[1] == 'O')
2036 base = 8;
2037 else if (str[1] == 'b' || str[1] == 'B')
2038 base = 2;
2039 else {
2040 /* "old" (C-style) octal literal, now invalid.
2041 it might still be zero though */
2042 error_if_nonzero = 1;
2043 base = 10;
2044 }
2045 }
2046 if (str[0] == '0' &&
2047 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2048 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2049 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2050 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 start = str;
2053 if ((base & (base - 1)) == 0)
2054 z = long_from_binary_base(&str, base);
2055 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056/***
2057Binary bases can be converted in time linear in the number of digits, because
2058Python's representation base is binary. Other bases (including decimal!) use
2059the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002060
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061First some math: the largest integer that can be expressed in N base-B digits
2062is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2063case number of Python digits needed to hold it is the smallest integer n s.t.
2064
2065 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2066 BASE**n >= B**N [taking logs to base BASE]
2067 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2068
2069The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2070this quickly. A Python long with that much space is reserved near the start,
2071and the result is computed into it.
2072
2073The input string is actually treated as being in base base**i (i.e., i digits
2074are processed at a time), where two more static arrays hold:
2075
2076 convwidth_base[base] = the largest integer i such that base**i <= BASE
2077 convmultmax_base[base] = base ** convwidth_base[base]
2078
2079The first of these is the largest i such that i consecutive input digits
2080must fit in a single Python digit. The second is effectively the input
2081base we're really using.
2082
2083Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2084convmultmax_base[base], the result is "simply"
2085
2086 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2087
2088where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002089
2090Error analysis: as above, the number of Python digits `n` needed is worst-
2091case
2092
2093 n >= N * log(B)/log(BASE)
2094
2095where `N` is the number of input digits in base `B`. This is computed via
2096
2097 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2098
2099below. Two numeric concerns are how much space this can waste, and whether
2100the computed result can be too small. To be concrete, assume BASE = 2**15,
2101which is the default (and it's unlikely anyone changes that).
2102
2103Waste isn't a problem: provided the first input digit isn't 0, the difference
2104between the worst-case input with N digits and the smallest input with N
2105digits is about a factor of B, but B is small compared to BASE so at most
2106one allocated Python digit can remain unused on that count. If
2107N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2108and adding 1 returns a result 1 larger than necessary. However, that can't
2109happen: whenever B is a power of 2, long_from_binary_base() is called
2110instead, and it's impossible for B**i to be an integer power of 2**15 when
2111B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2112an exact integer when B is not a power of 2, since B**i has a prime factor
2113other than 2 in that case, but (2**15)**j's only prime factor is 2).
2114
2115The computed result can be too small if the true value of N*log(B)/log(BASE)
2116is a little bit larger than an exact integer, but due to roundoff errors (in
2117computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2118yields a numeric result a little less than that integer. Unfortunately, "how
2119close can a transcendental function get to an integer over some range?"
2120questions are generally theoretically intractable. Computer analysis via
2121continued fractions is practical: expand log(B)/log(BASE) via continued
2122fractions, giving a sequence i/j of "the best" rational approximations. Then
2123j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2124we can get very close to being in trouble, but very rarely. For example,
212576573 is a denominator in one of the continued-fraction approximations to
2126log(10)/log(2**15), and indeed:
2127
2128 >>> log(10)/log(2**15)*76573
2129 16958.000000654003
2130
2131is very close to an integer. If we were working with IEEE single-precision,
2132rounding errors could kill us. Finding worst cases in IEEE double-precision
2133requires better-than-double-precision log() functions, and Tim didn't bother.
2134Instead the code checks to see whether the allocated space is enough as each
2135new Python digit is added, and copies the whole thing to a larger long if not.
2136This should happen extremely rarely, and in fact I don't have a test case
2137that triggers it(!). Instead the code was tested by artificially allocating
2138just 1 digit at the start, so that the copying code was exercised for every
2139digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002140***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 register twodigits c; /* current input character */
2142 Py_ssize_t size_z;
2143 int i;
2144 int convwidth;
2145 twodigits convmultmax, convmult;
2146 digit *pz, *pzstop;
2147 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 static double log_base_BASE[37] = {0.0e0,};
2150 static int convwidth_base[37] = {0,};
2151 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (log_base_BASE[base] == 0.0) {
2154 twodigits convmax = base;
2155 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156
Mark Dickinson22b20182010-05-10 21:27:53 +00002157 log_base_BASE[base] = (log((double)base) /
2158 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 for (;;) {
2160 twodigits next = convmax * base;
2161 if (next > PyLong_BASE)
2162 break;
2163 convmax = next;
2164 ++i;
2165 }
2166 convmultmax_base[base] = convmax;
2167 assert(i > 0);
2168 convwidth_base[base] = i;
2169 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Find length of the string of numeric characters. */
2172 scan = str;
2173 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2174 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 /* Create a long object that can contain the largest possible
2177 * integer with this base and length. Note that there's no
2178 * need to initialize z->ob_digit -- no slot is read up before
2179 * being stored into.
2180 */
2181 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2182 /* Uncomment next line to test exceedingly rare copy code */
2183 /* size_z = 1; */
2184 assert(size_z > 0);
2185 z = _PyLong_New(size_z);
2186 if (z == NULL)
2187 return NULL;
2188 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 /* `convwidth` consecutive input digits are treated as a single
2191 * digit in base `convmultmax`.
2192 */
2193 convwidth = convwidth_base[base];
2194 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* Work ;-) */
2197 while (str < scan) {
2198 /* grab up to convwidth digits from the input string */
2199 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2200 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2201 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002202 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 assert(c < PyLong_BASE);
2204 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 convmult = convmultmax;
2207 /* Calculate the shift only if we couldn't get
2208 * convwidth digits.
2209 */
2210 if (i != convwidth) {
2211 convmult = base;
2212 for ( ; i > 1; --i)
2213 convmult *= base;
2214 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /* Multiply z by convmult, and add c. */
2217 pz = z->ob_digit;
2218 pzstop = pz + Py_SIZE(z);
2219 for (; pz < pzstop; ++pz) {
2220 c += (twodigits)*pz * convmult;
2221 *pz = (digit)(c & PyLong_MASK);
2222 c >>= PyLong_SHIFT;
2223 }
2224 /* carry off the current end? */
2225 if (c) {
2226 assert(c < PyLong_BASE);
2227 if (Py_SIZE(z) < size_z) {
2228 *pz = (digit)c;
2229 ++Py_SIZE(z);
2230 }
2231 else {
2232 PyLongObject *tmp;
2233 /* Extremely rare. Get more space. */
2234 assert(Py_SIZE(z) == size_z);
2235 tmp = _PyLong_New(size_z + 1);
2236 if (tmp == NULL) {
2237 Py_DECREF(z);
2238 return NULL;
2239 }
2240 memcpy(tmp->ob_digit,
2241 z->ob_digit,
2242 sizeof(digit) * size_z);
2243 Py_DECREF(z);
2244 z = tmp;
2245 z->ob_digit[size_z] = (digit)c;
2246 ++size_z;
2247 }
2248 }
2249 }
2250 }
2251 if (z == NULL)
2252 return NULL;
2253 if (error_if_nonzero) {
2254 /* reset the base to 0, else the exception message
2255 doesn't make too much sense */
2256 base = 0;
2257 if (Py_SIZE(z) != 0)
2258 goto onError;
2259 /* there might still be other problems, therefore base
2260 remains zero here for the same reason */
2261 }
2262 if (str == start)
2263 goto onError;
2264 if (sign < 0)
2265 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002266 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 str++;
2268 if (*str != '\0')
2269 goto onError;
2270 if (pend)
2271 *pend = str;
2272 long_normalize(z);
2273 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002274
Mark Dickinson22b20182010-05-10 21:27:53 +00002275 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 Py_XDECREF(z);
2277 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2278 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2279 if (strobj == NULL)
2280 return NULL;
2281 PyErr_Format(PyExc_ValueError,
2282 "invalid literal for int() with base %d: %R",
2283 base, strobj);
2284 Py_DECREF(strobj);
2285 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002286}
2287
2288PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002289PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002290{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2292 if (unicode == NULL)
2293 return NULL;
2294 v = PyLong_FromUnicodeObject(unicode, base);
2295 Py_DECREF(unicode);
2296 return v;
2297}
2298
2299PyObject *
2300PyLong_FromUnicodeObject(PyObject *u, int base)
2301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002303 PyObject *asciidig;
2304 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002305 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002308 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002311 if (buffer == NULL) {
2312 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 return NULL;
2314 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002315 result = PyLong_FromString(buffer, &end, base);
2316 if (result != NULL && end != buffer + buflen) {
2317 PyErr_SetString(PyExc_ValueError,
2318 "null byte in argument for int()");
2319 Py_DECREF(result);
2320 result = NULL;
2321 }
2322 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002324}
2325
Tim Peters9f688bf2000-07-07 15:53:28 +00002326/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002329static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002330
2331/* Long division with remainder, top-level routine */
2332
Guido van Rossume32e0141992-01-19 16:31:05 +00002333static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002334long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2338 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 if (size_b == 0) {
2341 PyErr_SetString(PyExc_ZeroDivisionError,
2342 "integer division or modulo by zero");
2343 return -1;
2344 }
2345 if (size_a < size_b ||
2346 (size_a == size_b &&
2347 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2348 /* |a| < |b|. */
2349 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2350 if (*pdiv == NULL)
2351 return -1;
2352 Py_INCREF(a);
2353 *prem = (PyLongObject *) a;
2354 return 0;
2355 }
2356 if (size_b == 1) {
2357 digit rem = 0;
2358 z = divrem1(a, b->ob_digit[0], &rem);
2359 if (z == NULL)
2360 return -1;
2361 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2362 if (*prem == NULL) {
2363 Py_DECREF(z);
2364 return -1;
2365 }
2366 }
2367 else {
2368 z = x_divrem(a, b, prem);
2369 if (z == NULL)
2370 return -1;
2371 }
2372 /* Set the signs.
2373 The quotient z has the sign of a*b;
2374 the remainder r has the sign of a,
2375 so a = b*z + r. */
2376 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2377 NEGATE(z);
2378 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2379 NEGATE(*prem);
2380 *pdiv = maybe_small_long(z);
2381 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382}
2383
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002384/* Unsigned long division with remainder -- the algorithm. The arguments v1
2385 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002386
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002387static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002388x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 PyLongObject *v, *w, *a;
2391 Py_ssize_t i, k, size_v, size_w;
2392 int d;
2393 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2394 twodigits vv;
2395 sdigit zhi;
2396 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2399 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2400 handle the special case when the initial estimate q for a quotient
2401 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2402 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* allocate space; w will also be used to hold the final remainder */
2405 size_v = ABS(Py_SIZE(v1));
2406 size_w = ABS(Py_SIZE(w1));
2407 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2408 v = _PyLong_New(size_v+1);
2409 if (v == NULL) {
2410 *prem = NULL;
2411 return NULL;
2412 }
2413 w = _PyLong_New(size_w);
2414 if (w == NULL) {
2415 Py_DECREF(v);
2416 *prem = NULL;
2417 return NULL;
2418 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2421 shift v1 left by the same amount. Results go into w and v. */
2422 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2423 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2424 assert(carry == 0);
2425 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2426 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2427 v->ob_digit[size_v] = carry;
2428 size_v++;
2429 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2432 at most (and usually exactly) k = size_v - size_w digits. */
2433 k = size_v - size_w;
2434 assert(k >= 0);
2435 a = _PyLong_New(k);
2436 if (a == NULL) {
2437 Py_DECREF(w);
2438 Py_DECREF(v);
2439 *prem = NULL;
2440 return NULL;
2441 }
2442 v0 = v->ob_digit;
2443 w0 = w->ob_digit;
2444 wm1 = w0[size_w-1];
2445 wm2 = w0[size_w-2];
2446 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2447 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2448 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002451 Py_DECREF(a);
2452 Py_DECREF(w);
2453 Py_DECREF(v);
2454 *prem = NULL;
2455 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002456 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* estimate quotient digit q; may overestimate by 1 (rare) */
2459 vtop = vk[size_w];
2460 assert(vtop <= wm1);
2461 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2462 q = (digit)(vv / wm1);
2463 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2464 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2465 | vk[size_w-2])) {
2466 --q;
2467 r += wm1;
2468 if (r >= PyLong_BASE)
2469 break;
2470 }
2471 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2474 zhi = 0;
2475 for (i = 0; i < size_w; ++i) {
2476 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2477 -PyLong_BASE * q <= z < PyLong_BASE */
2478 z = (sdigit)vk[i] + zhi -
2479 (stwodigits)q * (stwodigits)w0[i];
2480 vk[i] = (digit)z & PyLong_MASK;
2481 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002482 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 /* add w back if q was too large (this branch taken rarely) */
2486 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2487 if ((sdigit)vtop + zhi < 0) {
2488 carry = 0;
2489 for (i = 0; i < size_w; ++i) {
2490 carry += vk[i] + w0[i];
2491 vk[i] = carry & PyLong_MASK;
2492 carry >>= PyLong_SHIFT;
2493 }
2494 --q;
2495 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 /* store quotient digit */
2498 assert(q < PyLong_BASE);
2499 *--ak = q;
2500 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* unshift remainder; we reuse w to store the result */
2503 carry = v_rshift(w0, v0, size_w, d);
2504 assert(carry==0);
2505 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 *prem = long_normalize(w);
2508 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002509}
2510
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002511/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2512 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2513 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2514 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2515 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2516 -1.0. */
2517
2518/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2519#if DBL_MANT_DIG == 53
2520#define EXP2_DBL_MANT_DIG 9007199254740992.0
2521#else
2522#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2523#endif
2524
2525double
2526_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2529 /* See below for why x_digits is always large enough. */
2530 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2531 double dx;
2532 /* Correction term for round-half-to-even rounding. For a digit x,
2533 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2534 multiple of 4, rounding ties to a multiple of 8. */
2535 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 a_size = ABS(Py_SIZE(a));
2538 if (a_size == 0) {
2539 /* Special case for 0: significand 0.0, exponent 0. */
2540 *e = 0;
2541 return 0.0;
2542 }
2543 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2544 /* The following is an overflow-free version of the check
2545 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2546 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2547 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2548 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002549 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2553 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 Number of digits needed for result: write // for floor division.
2556 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2565 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2568 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2569 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 in both cases.
2576 */
2577 if (a_bits <= DBL_MANT_DIG + 2) {
2578 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2579 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2580 x_size = 0;
2581 while (x_size < shift_digits)
2582 x_digits[x_size++] = 0;
2583 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2584 (int)shift_bits);
2585 x_size += a_size;
2586 x_digits[x_size++] = rem;
2587 }
2588 else {
2589 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2590 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2591 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2592 a_size - shift_digits, (int)shift_bits);
2593 x_size = a_size - shift_digits;
2594 /* For correct rounding below, we need the least significant
2595 bit of x to be 'sticky' for this shift: if any of the bits
2596 shifted out was nonzero, we set the least significant bit
2597 of x. */
2598 if (rem)
2599 x_digits[0] |= 1;
2600 else
2601 while (shift_digits > 0)
2602 if (a->ob_digit[--shift_digits]) {
2603 x_digits[0] |= 1;
2604 break;
2605 }
2606 }
Victor Stinner63941882011-09-29 00:42:28 +02002607 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* Round, and convert to double. */
2610 x_digits[0] += half_even_correction[x_digits[0] & 7];
2611 dx = x_digits[--x_size];
2612 while (x_size > 0)
2613 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 /* Rescale; make correction if result is 1.0. */
2616 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2617 if (dx == 1.0) {
2618 if (a_bits == PY_SSIZE_T_MAX)
2619 goto overflow;
2620 dx = 0.5;
2621 a_bits += 1;
2622 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 *e = a_bits;
2625 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002626
2627 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 /* exponent > PY_SSIZE_T_MAX */
2629 PyErr_SetString(PyExc_OverflowError,
2630 "huge integer: number of bits overflows a Py_ssize_t");
2631 *e = 0;
2632 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002633}
2634
2635/* Get a C double from a long int object. Rounds to the nearest double,
2636 using the round-half-to-even rule in the case of a tie. */
2637
2638double
2639PyLong_AsDouble(PyObject *v)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 Py_ssize_t exponent;
2642 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002643
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002644 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyErr_BadInternalCall();
2646 return -1.0;
2647 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002648 if (!PyLong_Check(v)) {
2649 PyErr_SetString(PyExc_TypeError, "an integer is required");
2650 return -1.0;
2651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2653 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2654 PyErr_SetString(PyExc_OverflowError,
2655 "long int too large to convert to float");
2656 return -1.0;
2657 }
2658 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002659}
2660
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002661/* Methods */
2662
2663static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002664long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002667}
2668
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002669static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002670long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 if (Py_SIZE(a) != Py_SIZE(b)) {
2675 sign = Py_SIZE(a) - Py_SIZE(b);
2676 }
2677 else {
2678 Py_ssize_t i = ABS(Py_SIZE(a));
2679 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2680 ;
2681 if (i < 0)
2682 sign = 0;
2683 else {
2684 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2685 if (Py_SIZE(a) < 0)
2686 sign = -sign;
2687 }
2688 }
2689 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002690}
2691
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002692#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002694
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002695static PyObject *
2696long_richcompare(PyObject *self, PyObject *other, int op)
2697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 int result;
2699 PyObject *v;
2700 CHECK_BINOP(self, other);
2701 if (self == other)
2702 result = 0;
2703 else
2704 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2705 /* Convert the return value to a Boolean */
2706 switch (op) {
2707 case Py_EQ:
2708 v = TEST_COND(result == 0);
2709 break;
2710 case Py_NE:
2711 v = TEST_COND(result != 0);
2712 break;
2713 case Py_LE:
2714 v = TEST_COND(result <= 0);
2715 break;
2716 case Py_GE:
2717 v = TEST_COND(result >= 0);
2718 break;
2719 case Py_LT:
2720 v = TEST_COND(result == -1);
2721 break;
2722 case Py_GT:
2723 v = TEST_COND(result == 1);
2724 break;
2725 default:
2726 PyErr_BadArgument();
2727 return NULL;
2728 }
2729 Py_INCREF(v);
2730 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002731}
2732
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002733static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002734long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002735{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002736 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 Py_ssize_t i;
2738 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 i = Py_SIZE(v);
2741 switch(i) {
2742 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2743 case 0: return 0;
2744 case 1: return v->ob_digit[0];
2745 }
2746 sign = 1;
2747 x = 0;
2748 if (i < 0) {
2749 sign = -1;
2750 i = -(i);
2751 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002753 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2754 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2755 _PyHASH_MODULUS.
2756
2757 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2758 amounts to a rotation of the bits of x. To see this, write
2759
2760 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2761
2762 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2763 PyLong_SHIFT bits of x (those that are shifted out of the
2764 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2765 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2766 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2767 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2768 congruent to y modulo _PyHASH_MODULUS. So
2769
2770 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2771
2772 The right-hand side is just the result of rotating the
2773 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2774 not all _PyHASH_BITS bits of x are 1s, the same is true
2775 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2776 the reduction of x*2**PyLong_SHIFT modulo
2777 _PyHASH_MODULUS. */
2778 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2779 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002781 if (x >= _PyHASH_MODULUS)
2782 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 }
2784 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002785 if (x == (Py_uhash_t)-1)
2786 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002787 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002788}
2789
2790
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002791/* Add the absolute values of two long integers. */
2792
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002793static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002794x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2797 PyLongObject *z;
2798 Py_ssize_t i;
2799 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 /* Ensure a is the larger of the two: */
2802 if (size_a < size_b) {
2803 { PyLongObject *temp = a; a = b; b = temp; }
2804 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002805 size_a = size_b;
2806 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 }
2808 z = _PyLong_New(size_a+1);
2809 if (z == NULL)
2810 return NULL;
2811 for (i = 0; i < size_b; ++i) {
2812 carry += a->ob_digit[i] + b->ob_digit[i];
2813 z->ob_digit[i] = carry & PyLong_MASK;
2814 carry >>= PyLong_SHIFT;
2815 }
2816 for (; i < size_a; ++i) {
2817 carry += a->ob_digit[i];
2818 z->ob_digit[i] = carry & PyLong_MASK;
2819 carry >>= PyLong_SHIFT;
2820 }
2821 z->ob_digit[i] = carry;
2822 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002823}
2824
2825/* Subtract the absolute values of two integers. */
2826
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002827static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002828x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2831 PyLongObject *z;
2832 Py_ssize_t i;
2833 int sign = 1;
2834 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* Ensure a is the larger of the two: */
2837 if (size_a < size_b) {
2838 sign = -1;
2839 { PyLongObject *temp = a; a = b; b = temp; }
2840 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002841 size_a = size_b;
2842 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 }
2844 else if (size_a == size_b) {
2845 /* Find highest digit where a and b differ: */
2846 i = size_a;
2847 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2848 ;
2849 if (i < 0)
2850 return (PyLongObject *)PyLong_FromLong(0);
2851 if (a->ob_digit[i] < b->ob_digit[i]) {
2852 sign = -1;
2853 { PyLongObject *temp = a; a = b; b = temp; }
2854 }
2855 size_a = size_b = i+1;
2856 }
2857 z = _PyLong_New(size_a);
2858 if (z == NULL)
2859 return NULL;
2860 for (i = 0; i < size_b; ++i) {
2861 /* The following assumes unsigned arithmetic
2862 works module 2**N for some N>PyLong_SHIFT. */
2863 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2864 z->ob_digit[i] = borrow & PyLong_MASK;
2865 borrow >>= PyLong_SHIFT;
2866 borrow &= 1; /* Keep only one sign bit */
2867 }
2868 for (; i < size_a; ++i) {
2869 borrow = a->ob_digit[i] - borrow;
2870 z->ob_digit[i] = borrow & PyLong_MASK;
2871 borrow >>= PyLong_SHIFT;
2872 borrow &= 1; /* Keep only one sign bit */
2873 }
2874 assert(borrow == 0);
2875 if (sign < 0)
2876 NEGATE(z);
2877 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002878}
2879
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002880static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002881long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2888 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2889 MEDIUM_VALUE(b));
2890 return result;
2891 }
2892 if (Py_SIZE(a) < 0) {
2893 if (Py_SIZE(b) < 0) {
2894 z = x_add(a, b);
2895 if (z != NULL && Py_SIZE(z) != 0)
2896 Py_SIZE(z) = -(Py_SIZE(z));
2897 }
2898 else
2899 z = x_sub(b, a);
2900 }
2901 else {
2902 if (Py_SIZE(b) < 0)
2903 z = x_sub(a, b);
2904 else
2905 z = x_add(a, b);
2906 }
2907 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002908}
2909
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002910static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002911long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2918 PyObject* r;
2919 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2920 return r;
2921 }
2922 if (Py_SIZE(a) < 0) {
2923 if (Py_SIZE(b) < 0)
2924 z = x_sub(a, b);
2925 else
2926 z = x_add(a, b);
2927 if (z != NULL && Py_SIZE(z) != 0)
2928 Py_SIZE(z) = -(Py_SIZE(z));
2929 }
2930 else {
2931 if (Py_SIZE(b) < 0)
2932 z = x_add(a, b);
2933 else
2934 z = x_sub(a, b);
2935 }
2936 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002937}
2938
Tim Peters5af4e6c2002-08-12 02:31:19 +00002939/* Grade school multiplication, ignoring the signs.
2940 * Returns the absolute value of the product, or NULL if error.
2941 */
2942static PyLongObject *
2943x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 PyLongObject *z;
2946 Py_ssize_t size_a = ABS(Py_SIZE(a));
2947 Py_ssize_t size_b = ABS(Py_SIZE(b));
2948 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 z = _PyLong_New(size_a + size_b);
2951 if (z == NULL)
2952 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2955 if (a == b) {
2956 /* Efficient squaring per HAC, Algorithm 14.16:
2957 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2958 * Gives slightly less than a 2x speedup when a == b,
2959 * via exploiting that each entry in the multiplication
2960 * pyramid appears twice (except for the size_a squares).
2961 */
2962 for (i = 0; i < size_a; ++i) {
2963 twodigits carry;
2964 twodigits f = a->ob_digit[i];
2965 digit *pz = z->ob_digit + (i << 1);
2966 digit *pa = a->ob_digit + i + 1;
2967 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002970 Py_DECREF(z);
2971 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002972 });
Tim Peters0973b992004-08-29 22:16:50 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 carry = *pz + f * f;
2975 *pz++ = (digit)(carry & PyLong_MASK);
2976 carry >>= PyLong_SHIFT;
2977 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 /* Now f is added in twice in each column of the
2980 * pyramid it appears. Same as adding f<<1 once.
2981 */
2982 f <<= 1;
2983 while (pa < paend) {
2984 carry += *pz + *pa++ * f;
2985 *pz++ = (digit)(carry & PyLong_MASK);
2986 carry >>= PyLong_SHIFT;
2987 assert(carry <= (PyLong_MASK << 1));
2988 }
2989 if (carry) {
2990 carry += *pz;
2991 *pz++ = (digit)(carry & PyLong_MASK);
2992 carry >>= PyLong_SHIFT;
2993 }
2994 if (carry)
2995 *pz += (digit)(carry & PyLong_MASK);
2996 assert((carry >> PyLong_SHIFT) == 0);
2997 }
2998 }
2999 else { /* a is not the same as b -- gradeschool long mult */
3000 for (i = 0; i < size_a; ++i) {
3001 twodigits carry = 0;
3002 twodigits f = a->ob_digit[i];
3003 digit *pz = z->ob_digit + i;
3004 digit *pb = b->ob_digit;
3005 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003008 Py_DECREF(z);
3009 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003010 });
Tim Peters0973b992004-08-29 22:16:50 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 while (pb < pbend) {
3013 carry += *pz + *pb++ * f;
3014 *pz++ = (digit)(carry & PyLong_MASK);
3015 carry >>= PyLong_SHIFT;
3016 assert(carry <= PyLong_MASK);
3017 }
3018 if (carry)
3019 *pz += (digit)(carry & PyLong_MASK);
3020 assert((carry >> PyLong_SHIFT) == 0);
3021 }
3022 }
3023 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003024}
3025
3026/* A helper for Karatsuba multiplication (k_mul).
3027 Takes a long "n" and an integer "size" representing the place to
3028 split, and sets low and high such that abs(n) == (high << size) + low,
3029 viewing the shift as being by digits. The sign bit is ignored, and
3030 the return values are >= 0.
3031 Returns 0 on success, -1 on failure.
3032*/
3033static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003034kmul_split(PyLongObject *n,
3035 Py_ssize_t size,
3036 PyLongObject **high,
3037 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 PyLongObject *hi, *lo;
3040 Py_ssize_t size_lo, size_hi;
3041 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003043 size_lo = MIN(size_n, size);
3044 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 if ((hi = _PyLong_New(size_hi)) == NULL)
3047 return -1;
3048 if ((lo = _PyLong_New(size_lo)) == NULL) {
3049 Py_DECREF(hi);
3050 return -1;
3051 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3054 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 *high = long_normalize(hi);
3057 *low = long_normalize(lo);
3058 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003059}
3060
Tim Peters60004642002-08-12 22:01:34 +00003061static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3062
Tim Peters5af4e6c2002-08-12 02:31:19 +00003063/* Karatsuba multiplication. Ignores the input signs, and returns the
3064 * absolute value of the product (or NULL if error).
3065 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3066 */
3067static PyLongObject *
3068k_mul(PyLongObject *a, PyLongObject *b)
3069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 Py_ssize_t asize = ABS(Py_SIZE(a));
3071 Py_ssize_t bsize = ABS(Py_SIZE(b));
3072 PyLongObject *ah = NULL;
3073 PyLongObject *al = NULL;
3074 PyLongObject *bh = NULL;
3075 PyLongObject *bl = NULL;
3076 PyLongObject *ret = NULL;
3077 PyLongObject *t1, *t2, *t3;
3078 Py_ssize_t shift; /* the number of digits we split off */
3079 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003081 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3082 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3083 * Then the original product is
3084 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3085 * By picking X to be a power of 2, "*X" is just shifting, and it's
3086 * been reduced to 3 multiplies on numbers half the size.
3087 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 /* We want to split based on the larger number; fiddle so that b
3090 * is largest.
3091 */
3092 if (asize > bsize) {
3093 t1 = a;
3094 a = b;
3095 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 i = asize;
3098 asize = bsize;
3099 bsize = i;
3100 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 /* Use gradeschool math when either number is too small. */
3103 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3104 if (asize <= i) {
3105 if (asize == 0)
3106 return (PyLongObject *)PyLong_FromLong(0);
3107 else
3108 return x_mul(a, b);
3109 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 /* If a is small compared to b, splitting on b gives a degenerate
3112 * case with ah==0, and Karatsuba may be (even much) less efficient
3113 * than "grade school" then. However, we can still win, by viewing
3114 * b as a string of "big digits", each of width a->ob_size. That
3115 * leads to a sequence of balanced calls to k_mul.
3116 */
3117 if (2 * asize <= bsize)
3118 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120 /* Split a & b into hi & lo pieces. */
3121 shift = bsize >> 1;
3122 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3123 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 if (a == b) {
3126 bh = ah;
3127 bl = al;
3128 Py_INCREF(bh);
3129 Py_INCREF(bl);
3130 }
3131 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 /* The plan:
3134 * 1. Allocate result space (asize + bsize digits: that's always
3135 * enough).
3136 * 2. Compute ah*bh, and copy into result at 2*shift.
3137 * 3. Compute al*bl, and copy into result at 0. Note that this
3138 * can't overlap with #2.
3139 * 4. Subtract al*bl from the result, starting at shift. This may
3140 * underflow (borrow out of the high digit), but we don't care:
3141 * we're effectively doing unsigned arithmetic mod
3142 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3143 * borrows and carries out of the high digit can be ignored.
3144 * 5. Subtract ah*bh from the result, starting at shift.
3145 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3146 * at shift.
3147 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 /* 1. Allocate result space. */
3150 ret = _PyLong_New(asize + bsize);
3151 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003152#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* Fill with trash, to catch reference to uninitialized digits. */
3154 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003155#endif
Tim Peters44121a62002-08-12 06:17:58 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3158 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3159 assert(Py_SIZE(t1) >= 0);
3160 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3161 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3162 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* Zero-out the digits higher than the ah*bh copy. */
3165 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3166 if (i)
3167 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3168 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 /* 3. t2 <- al*bl, and copy into the low digits. */
3171 if ((t2 = k_mul(al, bl)) == NULL) {
3172 Py_DECREF(t1);
3173 goto fail;
3174 }
3175 assert(Py_SIZE(t2) >= 0);
3176 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3177 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 /* Zero out remaining digits. */
3180 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3181 if (i)
3182 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3185 * because it's fresher in cache.
3186 */
3187 i = Py_SIZE(ret) - shift; /* # digits after shift */
3188 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3189 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3192 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3195 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3196 Py_DECREF(ah);
3197 Py_DECREF(al);
3198 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 if (a == b) {
3201 t2 = t1;
3202 Py_INCREF(t2);
3203 }
3204 else if ((t2 = x_add(bh, bl)) == NULL) {
3205 Py_DECREF(t1);
3206 goto fail;
3207 }
3208 Py_DECREF(bh);
3209 Py_DECREF(bl);
3210 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 t3 = k_mul(t1, t2);
3213 Py_DECREF(t1);
3214 Py_DECREF(t2);
3215 if (t3 == NULL) goto fail;
3216 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 /* Add t3. It's not obvious why we can't run out of room here.
3219 * See the (*) comment after this function.
3220 */
3221 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3222 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003225
Mark Dickinson22b20182010-05-10 21:27:53 +00003226 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 Py_XDECREF(ret);
3228 Py_XDECREF(ah);
3229 Py_XDECREF(al);
3230 Py_XDECREF(bh);
3231 Py_XDECREF(bl);
3232 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003233}
3234
Tim Petersd6974a52002-08-13 20:37:51 +00003235/* (*) Why adding t3 can't "run out of room" above.
3236
Tim Petersab86c2b2002-08-15 20:06:00 +00003237Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3238to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003239
Tim Petersab86c2b2002-08-15 20:06:00 +000032401. For any integer i, i = c(i/2) + f(i/2). In particular,
3241 bsize = c(bsize/2) + f(bsize/2).
32422. shift = f(bsize/2)
32433. asize <= bsize
32444. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3245 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003246
Tim Petersab86c2b2002-08-15 20:06:00 +00003247We allocated asize + bsize result digits, and add t3 into them at an offset
3248of shift. This leaves asize+bsize-shift allocated digit positions for t3
3249to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3250asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003251
Tim Petersab86c2b2002-08-15 20:06:00 +00003252bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3253at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003254
Tim Petersab86c2b2002-08-15 20:06:00 +00003255If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3256digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3257most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003258
Tim Petersab86c2b2002-08-15 20:06:00 +00003259The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003260
Tim Petersab86c2b2002-08-15 20:06:00 +00003261 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003262
Tim Petersab86c2b2002-08-15 20:06:00 +00003263and we have asize + c(bsize/2) available digit positions. We need to show
3264this is always enough. An instance of c(bsize/2) cancels out in both, so
3265the question reduces to whether asize digits is enough to hold
3266(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3267then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3268asize 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 +00003269digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003270asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003271c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3272is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3273bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003274
Tim Peters48d52c02002-08-14 17:07:32 +00003275Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3276clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3277ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003278*/
3279
Tim Peters60004642002-08-12 22:01:34 +00003280/* b has at least twice the digits of a, and a is big enough that Karatsuba
3281 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3282 * of slices, each with a->ob_size digits, and multiply the slices by a,
3283 * one at a time. This gives k_mul balanced inputs to work with, and is
3284 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003285 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003286 * single-width slice overlap between successive partial sums).
3287 */
3288static PyLongObject *
3289k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 const Py_ssize_t asize = ABS(Py_SIZE(a));
3292 Py_ssize_t bsize = ABS(Py_SIZE(b));
3293 Py_ssize_t nbdone; /* # of b digits already multiplied */
3294 PyLongObject *ret;
3295 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 assert(asize > KARATSUBA_CUTOFF);
3298 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 /* Allocate result space, and zero it out. */
3301 ret = _PyLong_New(asize + bsize);
3302 if (ret == NULL)
3303 return NULL;
3304 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 /* Successive slices of b are copied into bslice. */
3307 bslice = _PyLong_New(asize);
3308 if (bslice == NULL)
3309 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 nbdone = 0;
3312 while (bsize > 0) {
3313 PyLongObject *product;
3314 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 /* Multiply the next slice of b by a. */
3317 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3318 nbtouse * sizeof(digit));
3319 Py_SIZE(bslice) = nbtouse;
3320 product = k_mul(a, bslice);
3321 if (product == NULL)
3322 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 /* Add into result. */
3325 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3326 product->ob_digit, Py_SIZE(product));
3327 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 bsize -= nbtouse;
3330 nbdone += nbtouse;
3331 }
Tim Peters60004642002-08-12 22:01:34 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 Py_DECREF(bslice);
3334 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003335
Mark Dickinson22b20182010-05-10 21:27:53 +00003336 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 Py_DECREF(ret);
3338 Py_XDECREF(bslice);
3339 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003340}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
3342static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003343long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 /* fast path for single-digit multiplication */
3350 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3351 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003352#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003354#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 /* if we don't have long long then we're almost certainly
3356 using 15-bit digits, so v will fit in a long. In the
3357 unlikely event that we're using 30-bit digits on a platform
3358 without long long, a large v will just cause us to fall
3359 through to the general multiplication code below. */
3360 if (v >= LONG_MIN && v <= LONG_MAX)
3361 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003362#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 z = k_mul(a, b);
3366 /* Negate if exactly one of the inputs is negative. */
3367 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3368 NEGATE(z);
3369 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003370}
3371
Guido van Rossume32e0141992-01-19 16:31:05 +00003372/* The / and % operators are now defined in terms of divmod().
3373 The expression a mod b has the value a - b*floor(a/b).
3374 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003375 |a| by |b|, with the sign of a. This is also expressed
3376 as a - b*trunc(a/b), if trunc truncates towards zero.
3377 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003378 a b a rem b a mod b
3379 13 10 3 3
3380 -13 10 -3 7
3381 13 -10 3 -7
3382 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003383 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003384 have different signs. We then subtract one from the 'div'
3385 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003386
Tim Peters47e52ee2004-08-30 02:44:38 +00003387/* Compute
3388 * *pdiv, *pmod = divmod(v, w)
3389 * NULL can be passed for pdiv or pmod, in which case that part of
3390 * the result is simply thrown away. The caller owns a reference to
3391 * each of these it requests (does not pass NULL for).
3392 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003393static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003394l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 if (long_divrem(v, w, &div, &mod) < 0)
3400 return -1;
3401 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3402 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3403 PyLongObject *temp;
3404 PyLongObject *one;
3405 temp = (PyLongObject *) long_add(mod, w);
3406 Py_DECREF(mod);
3407 mod = temp;
3408 if (mod == NULL) {
3409 Py_DECREF(div);
3410 return -1;
3411 }
3412 one = (PyLongObject *) PyLong_FromLong(1L);
3413 if (one == NULL ||
3414 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3415 Py_DECREF(mod);
3416 Py_DECREF(div);
3417 Py_XDECREF(one);
3418 return -1;
3419 }
3420 Py_DECREF(one);
3421 Py_DECREF(div);
3422 div = temp;
3423 }
3424 if (pdiv != NULL)
3425 *pdiv = div;
3426 else
3427 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 if (pmod != NULL)
3430 *pmod = mod;
3431 else
3432 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003435}
3436
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003437static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003438long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 CHECK_BINOP(a, b);
3443 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3444 div = NULL;
3445 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003446}
3447
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003448/* PyLong/PyLong -> float, with correctly rounded result. */
3449
3450#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3451#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3452
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003453static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003454long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 PyLongObject *a, *b, *x;
3457 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3458 digit mask, low;
3459 int inexact, negate, a_is_small, b_is_small;
3460 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 CHECK_BINOP(v, w);
3463 a = (PyLongObject *)v;
3464 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 /*
3467 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3470 1. choose a suitable integer 'shift'
3471 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3472 3. adjust x for correct rounding
3473 4. convert x to a double dx with the same value
3474 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3479 returns either 0.0 or -0.0, depending on the sign of b. For a and
3480 b both nonzero, ignore signs of a and b, and add the sign back in
3481 at the end. Now write a_bits and b_bits for the bit lengths of a
3482 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3483 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3488 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3489 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3490 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 1. The integer 'shift' is chosen so that x has the right number of
3495 bits for a double, plus two or three extra bits that will be used
3496 in the rounding decisions. Writing a_bits and b_bits for the
3497 number of significant bits in a and b respectively, a
3498 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 This is fine in the usual case, but if a/b is smaller than the
3503 smallest normal float then it can lead to double rounding on an
3504 IEEE 754 platform, giving incorrectly rounded results. So we
3505 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 2. The quantity x is computed by first shifting a (left -shift bits
3510 if shift <= 0, right shift bits if shift > 0) and then dividing by
3511 b. For both the shift and the division, we keep track of whether
3512 the result is inexact, in a flag 'inexact'; this information is
3513 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 With the choice of shift above, together with our assumption that
3516 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3517 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3520 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 For float representability, we need x/2**extra_bits <
3525 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3526 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 To round, we just modify the bottom digit of x in-place; this can
3531 end up giving a digit with value > PyLONG_MASK, but that's not a
3532 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 With the original choices for shift above, extra_bits will always
3535 be 2 or 3. Then rounding under the round-half-to-even rule, we
3536 round up iff the most significant of the extra bits is 1, and
3537 either: (a) the computation of x in step 2 had an inexact result,
3538 or (b) at least one other of the extra bits is 1, or (c) the least
3539 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 4. Conversion to a double is straightforward; all floating-point
3542 operations involved in the conversion are exact, so there's no
3543 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3546 The result will always be exactly representable as a double, except
3547 in the case that it overflows. To avoid dependence on the exact
3548 behaviour of ldexp on overflow, we check for overflow before
3549 applying ldexp. The result of ldexp is adjusted for sign before
3550 returning.
3551 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 /* Reduce to case where a and b are both positive. */
3554 a_size = ABS(Py_SIZE(a));
3555 b_size = ABS(Py_SIZE(b));
3556 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3557 if (b_size == 0) {
3558 PyErr_SetString(PyExc_ZeroDivisionError,
3559 "division by zero");
3560 goto error;
3561 }
3562 if (a_size == 0)
3563 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 /* Fast path for a and b small (exactly representable in a double).
3566 Relies on floating-point division being correctly rounded; results
3567 may be subject to double rounding on x86 machines that operate with
3568 the x87 FPU set to 64-bit precision. */
3569 a_is_small = a_size <= MANT_DIG_DIGITS ||
3570 (a_size == MANT_DIG_DIGITS+1 &&
3571 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3572 b_is_small = b_size <= MANT_DIG_DIGITS ||
3573 (b_size == MANT_DIG_DIGITS+1 &&
3574 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3575 if (a_is_small && b_is_small) {
3576 double da, db;
3577 da = a->ob_digit[--a_size];
3578 while (a_size > 0)
3579 da = da * PyLong_BASE + a->ob_digit[--a_size];
3580 db = b->ob_digit[--b_size];
3581 while (b_size > 0)
3582 db = db * PyLong_BASE + b->ob_digit[--b_size];
3583 result = da / db;
3584 goto success;
3585 }
Tim Peterse2a60002001-09-04 06:17:36 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 /* Catch obvious cases of underflow and overflow */
3588 diff = a_size - b_size;
3589 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3590 /* Extreme overflow */
3591 goto overflow;
3592 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3593 /* Extreme underflow */
3594 goto underflow_or_zero;
3595 /* Next line is now safe from overflowing a Py_ssize_t */
3596 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3597 bits_in_digit(b->ob_digit[b_size - 1]);
3598 /* Now diff = a_bits - b_bits. */
3599 if (diff > DBL_MAX_EXP)
3600 goto overflow;
3601 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3602 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 /* Choose value for shift; see comments for step 1 above. */
3605 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 /* x = abs(a * 2**-shift) */
3610 if (shift <= 0) {
3611 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3612 digit rem;
3613 /* x = a << -shift */
3614 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3615 /* In practice, it's probably impossible to end up
3616 here. Both a and b would have to be enormous,
3617 using close to SIZE_T_MAX bytes of memory each. */
3618 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003619 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 goto error;
3621 }
3622 x = _PyLong_New(a_size + shift_digits + 1);
3623 if (x == NULL)
3624 goto error;
3625 for (i = 0; i < shift_digits; i++)
3626 x->ob_digit[i] = 0;
3627 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3628 a_size, -shift % PyLong_SHIFT);
3629 x->ob_digit[a_size + shift_digits] = rem;
3630 }
3631 else {
3632 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3633 digit rem;
3634 /* x = a >> shift */
3635 assert(a_size >= shift_digits);
3636 x = _PyLong_New(a_size - shift_digits);
3637 if (x == NULL)
3638 goto error;
3639 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3640 a_size - shift_digits, shift % PyLong_SHIFT);
3641 /* set inexact if any of the bits shifted out is nonzero */
3642 if (rem)
3643 inexact = 1;
3644 while (!inexact && shift_digits > 0)
3645 if (a->ob_digit[--shift_digits])
3646 inexact = 1;
3647 }
3648 long_normalize(x);
3649 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3652 reference to x, so it's safe to modify it in-place. */
3653 if (b_size == 1) {
3654 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3655 b->ob_digit[0]);
3656 long_normalize(x);
3657 if (rem)
3658 inexact = 1;
3659 }
3660 else {
3661 PyLongObject *div, *rem;
3662 div = x_divrem(x, b, &rem);
3663 Py_DECREF(x);
3664 x = div;
3665 if (x == NULL)
3666 goto error;
3667 if (Py_SIZE(rem))
3668 inexact = 1;
3669 Py_DECREF(rem);
3670 }
3671 x_size = ABS(Py_SIZE(x));
3672 assert(x_size > 0); /* result of division is never zero */
3673 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 /* The number of extra bits that have to be rounded away. */
3676 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3677 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003679 /* Round by directly modifying the low digit of x. */
3680 mask = (digit)1 << (extra_bits - 1);
3681 low = x->ob_digit[0] | inexact;
3682 if (low & mask && low & (3*mask-1))
3683 low += mask;
3684 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003686 /* Convert x to a double dx; the conversion is exact. */
3687 dx = x->ob_digit[--x_size];
3688 while (x_size > 0)
3689 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3690 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003692 /* Check whether ldexp result will overflow a double. */
3693 if (shift + x_bits >= DBL_MAX_EXP &&
3694 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3695 goto overflow;
3696 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003697
3698 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003700
3701 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003702 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003703
3704 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 PyErr_SetString(PyExc_OverflowError,
3706 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003707 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003709}
3710
3711static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003712long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003716 CHECK_BINOP(a, b);
3717
3718 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3719 mod = NULL;
3720 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003721}
3722
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003723static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003724long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003726 PyLongObject *div, *mod;
3727 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003731 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3732 return NULL;
3733 }
3734 z = PyTuple_New(2);
3735 if (z != NULL) {
3736 PyTuple_SetItem(z, 0, (PyObject *) div);
3737 PyTuple_SetItem(z, 1, (PyObject *) mod);
3738 }
3739 else {
3740 Py_DECREF(div);
3741 Py_DECREF(mod);
3742 }
3743 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003744}
3745
Tim Peters47e52ee2004-08-30 02:44:38 +00003746/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003747static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003748long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3751 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 PyLongObject *z = NULL; /* accumulated result */
3754 Py_ssize_t i, j, k; /* counters */
3755 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 /* 5-ary values. If the exponent is large enough, table is
3758 * precomputed so that table[i] == a**i % c for i in range(32).
3759 */
3760 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3761 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 /* a, b, c = v, w, x */
3764 CHECK_BINOP(v, w);
3765 a = (PyLongObject*)v; Py_INCREF(a);
3766 b = (PyLongObject*)w; Py_INCREF(b);
3767 if (PyLong_Check(x)) {
3768 c = (PyLongObject *)x;
3769 Py_INCREF(x);
3770 }
3771 else if (x == Py_None)
3772 c = NULL;
3773 else {
3774 Py_DECREF(a);
3775 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003776 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 }
Tim Peters4c483c42001-09-05 06:24:58 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3780 if (c) {
3781 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003782 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 goto Error;
3784 }
3785 else {
3786 /* else return a float. This works because we know
3787 that this calls float_pow() which converts its
3788 arguments to double. */
3789 Py_DECREF(a);
3790 Py_DECREF(b);
3791 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3792 }
3793 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 if (c) {
3796 /* if modulus == 0:
3797 raise ValueError() */
3798 if (Py_SIZE(c) == 0) {
3799 PyErr_SetString(PyExc_ValueError,
3800 "pow() 3rd argument cannot be 0");
3801 goto Error;
3802 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 /* if modulus < 0:
3805 negativeOutput = True
3806 modulus = -modulus */
3807 if (Py_SIZE(c) < 0) {
3808 negativeOutput = 1;
3809 temp = (PyLongObject *)_PyLong_Copy(c);
3810 if (temp == NULL)
3811 goto Error;
3812 Py_DECREF(c);
3813 c = temp;
3814 temp = NULL;
3815 NEGATE(c);
3816 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 /* if modulus == 1:
3819 return 0 */
3820 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3821 z = (PyLongObject *)PyLong_FromLong(0L);
3822 goto Done;
3823 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 /* if base < 0:
3826 base = base % modulus
3827 Having the base positive just makes things easier. */
3828 if (Py_SIZE(a) < 0) {
3829 if (l_divmod(a, c, NULL, &temp) < 0)
3830 goto Error;
3831 Py_DECREF(a);
3832 a = temp;
3833 temp = NULL;
3834 }
3835 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003837 /* At this point a, b, and c are guaranteed non-negative UNLESS
3838 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 z = (PyLongObject *)PyLong_FromLong(1L);
3841 if (z == NULL)
3842 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 /* Perform a modular reduction, X = X % c, but leave X alone if c
3845 * is NULL.
3846 */
3847#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003848 do { \
3849 if (c != NULL) { \
3850 if (l_divmod(X, c, NULL, &temp) < 0) \
3851 goto Error; \
3852 Py_XDECREF(X); \
3853 X = temp; \
3854 temp = NULL; \
3855 } \
3856 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 /* Multiply two values, then reduce the result:
3859 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003860#define MULT(X, Y, result) \
3861 do { \
3862 temp = (PyLongObject *)long_mul(X, Y); \
3863 if (temp == NULL) \
3864 goto Error; \
3865 Py_XDECREF(result); \
3866 result = temp; \
3867 temp = NULL; \
3868 REDUCE(result); \
3869 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3872 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3873 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3874 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3875 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003878 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003880 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 }
3882 }
3883 }
3884 else {
3885 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3886 Py_INCREF(z); /* still holds 1L */
3887 table[0] = z;
3888 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003889 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003891 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3892 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3895 const int index = (bi >> j) & 0x1f;
3896 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003897 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003899 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 }
3901 }
3902 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (negativeOutput && (Py_SIZE(z) != 0)) {
3905 temp = (PyLongObject *)long_sub(z, c);
3906 if (temp == NULL)
3907 goto Error;
3908 Py_DECREF(z);
3909 z = temp;
3910 temp = NULL;
3911 }
3912 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003913
Mark Dickinson22b20182010-05-10 21:27:53 +00003914 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 if (z != NULL) {
3916 Py_DECREF(z);
3917 z = NULL;
3918 }
3919 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003920 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3922 for (i = 0; i < 32; ++i)
3923 Py_XDECREF(table[i]);
3924 }
3925 Py_DECREF(a);
3926 Py_DECREF(b);
3927 Py_XDECREF(c);
3928 Py_XDECREF(temp);
3929 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003930}
3931
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003932static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003933long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003935 /* Implement ~x as -(x+1) */
3936 PyLongObject *x;
3937 PyLongObject *w;
3938 if (ABS(Py_SIZE(v)) <=1)
3939 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3940 w = (PyLongObject *)PyLong_FromLong(1L);
3941 if (w == NULL)
3942 return NULL;
3943 x = (PyLongObject *) long_add(v, w);
3944 Py_DECREF(w);
3945 if (x == NULL)
3946 return NULL;
3947 Py_SIZE(x) = -(Py_SIZE(x));
3948 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003949}
3950
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003951static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003952long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 PyLongObject *z;
3955 if (ABS(Py_SIZE(v)) <= 1)
3956 return PyLong_FromLong(-MEDIUM_VALUE(v));
3957 z = (PyLongObject *)_PyLong_Copy(v);
3958 if (z != NULL)
3959 Py_SIZE(z) = -(Py_SIZE(v));
3960 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003961}
3962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003963static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003964long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 if (Py_SIZE(v) < 0)
3967 return long_neg(v);
3968 else
3969 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003970}
3971
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003972static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003973long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003976}
3977
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003978static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003979long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 PyLongObject *z = NULL;
3982 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3983 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 if (Py_SIZE(a) < 0) {
3988 /* Right shifting negative numbers is harder */
3989 PyLongObject *a1, *a2;
3990 a1 = (PyLongObject *) long_invert(a);
3991 if (a1 == NULL)
3992 goto rshift_error;
3993 a2 = (PyLongObject *) long_rshift(a1, b);
3994 Py_DECREF(a1);
3995 if (a2 == NULL)
3996 goto rshift_error;
3997 z = (PyLongObject *) long_invert(a2);
3998 Py_DECREF(a2);
3999 }
4000 else {
4001 shiftby = PyLong_AsSsize_t((PyObject *)b);
4002 if (shiftby == -1L && PyErr_Occurred())
4003 goto rshift_error;
4004 if (shiftby < 0) {
4005 PyErr_SetString(PyExc_ValueError,
4006 "negative shift count");
4007 goto rshift_error;
4008 }
4009 wordshift = shiftby / PyLong_SHIFT;
4010 newsize = ABS(Py_SIZE(a)) - wordshift;
4011 if (newsize <= 0)
4012 return PyLong_FromLong(0);
4013 loshift = shiftby % PyLong_SHIFT;
4014 hishift = PyLong_SHIFT - loshift;
4015 lomask = ((digit)1 << hishift) - 1;
4016 himask = PyLong_MASK ^ lomask;
4017 z = _PyLong_New(newsize);
4018 if (z == NULL)
4019 goto rshift_error;
4020 if (Py_SIZE(a) < 0)
4021 Py_SIZE(z) = -(Py_SIZE(z));
4022 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4023 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4024 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004025 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 }
4027 z = long_normalize(z);
4028 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004029 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004031
Guido van Rossumc6913e71991-11-19 20:26:46 +00004032}
4033
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004034static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004035long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 /* This version due to Tim Peters */
4038 PyLongObject *a = (PyLongObject*)v;
4039 PyLongObject *b = (PyLongObject*)w;
4040 PyLongObject *z = NULL;
4041 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4042 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 shiftby = PyLong_AsSsize_t((PyObject *)b);
4047 if (shiftby == -1L && PyErr_Occurred())
4048 goto lshift_error;
4049 if (shiftby < 0) {
4050 PyErr_SetString(PyExc_ValueError, "negative shift count");
4051 goto lshift_error;
4052 }
4053 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4054 wordshift = shiftby / PyLong_SHIFT;
4055 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004057 oldsize = ABS(Py_SIZE(a));
4058 newsize = oldsize + wordshift;
4059 if (remshift)
4060 ++newsize;
4061 z = _PyLong_New(newsize);
4062 if (z == NULL)
4063 goto lshift_error;
4064 if (Py_SIZE(a) < 0)
4065 NEGATE(z);
4066 for (i = 0; i < wordshift; i++)
4067 z->ob_digit[i] = 0;
4068 accum = 0;
4069 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4070 accum |= (twodigits)a->ob_digit[j] << remshift;
4071 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4072 accum >>= PyLong_SHIFT;
4073 }
4074 if (remshift)
4075 z->ob_digit[newsize-1] = (digit)accum;
4076 else
4077 assert(!accum);
4078 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004079 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004081}
4082
Mark Dickinson27a87a22009-10-25 20:43:34 +00004083/* Compute two's complement of digit vector a[0:m], writing result to
4084 z[0:m]. The digit vector a need not be normalized, but should not
4085 be entirely zero. a and z may point to the same digit vector. */
4086
4087static void
4088v_complement(digit *z, digit *a, Py_ssize_t m)
4089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004090 Py_ssize_t i;
4091 digit carry = 1;
4092 for (i = 0; i < m; ++i) {
4093 carry += a[i] ^ PyLong_MASK;
4094 z[i] = carry & PyLong_MASK;
4095 carry >>= PyLong_SHIFT;
4096 }
4097 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004098}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004099
4100/* Bitwise and/xor/or operations */
4101
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004102static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004103long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004105 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 int nega, negb, negz;
4108 Py_ssize_t size_a, size_b, size_z, i;
4109 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 /* Bitwise operations for negative numbers operate as though
4112 on a two's complement representation. So convert arguments
4113 from sign-magnitude to two's complement, and convert the
4114 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 /* If a is negative, replace it by its two's complement. */
4117 size_a = ABS(Py_SIZE(a));
4118 nega = Py_SIZE(a) < 0;
4119 if (nega) {
4120 z = _PyLong_New(size_a);
4121 if (z == NULL)
4122 return NULL;
4123 v_complement(z->ob_digit, a->ob_digit, size_a);
4124 a = z;
4125 }
4126 else
4127 /* Keep reference count consistent. */
4128 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 /* Same for b. */
4131 size_b = ABS(Py_SIZE(b));
4132 negb = Py_SIZE(b) < 0;
4133 if (negb) {
4134 z = _PyLong_New(size_b);
4135 if (z == NULL) {
4136 Py_DECREF(a);
4137 return NULL;
4138 }
4139 v_complement(z->ob_digit, b->ob_digit, size_b);
4140 b = z;
4141 }
4142 else
4143 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004145 /* Swap a and b if necessary to ensure size_a >= size_b. */
4146 if (size_a < size_b) {
4147 z = a; a = b; b = z;
4148 size_z = size_a; size_a = size_b; size_b = size_z;
4149 negz = nega; nega = negb; negb = negz;
4150 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 /* JRH: The original logic here was to allocate the result value (z)
4153 as the longer of the two operands. However, there are some cases
4154 where the result is guaranteed to be shorter than that: AND of two
4155 positives, OR of two negatives: use the shorter number. AND with
4156 mixed signs: use the positive number. OR with mixed signs: use the
4157 negative number.
4158 */
4159 switch (op) {
4160 case '^':
4161 negz = nega ^ negb;
4162 size_z = size_a;
4163 break;
4164 case '&':
4165 negz = nega & negb;
4166 size_z = negb ? size_a : size_b;
4167 break;
4168 case '|':
4169 negz = nega | negb;
4170 size_z = negb ? size_b : size_a;
4171 break;
4172 default:
4173 PyErr_BadArgument();
4174 return NULL;
4175 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004177 /* We allow an extra digit if z is negative, to make sure that
4178 the final two's complement of z doesn't overflow. */
4179 z = _PyLong_New(size_z + negz);
4180 if (z == NULL) {
4181 Py_DECREF(a);
4182 Py_DECREF(b);
4183 return NULL;
4184 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 /* Compute digits for overlap of a and b. */
4187 switch(op) {
4188 case '&':
4189 for (i = 0; i < size_b; ++i)
4190 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4191 break;
4192 case '|':
4193 for (i = 0; i < size_b; ++i)
4194 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4195 break;
4196 case '^':
4197 for (i = 0; i < size_b; ++i)
4198 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4199 break;
4200 default:
4201 PyErr_BadArgument();
4202 return NULL;
4203 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 /* Copy any remaining digits of a, inverting if necessary. */
4206 if (op == '^' && negb)
4207 for (; i < size_z; ++i)
4208 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4209 else if (i < size_z)
4210 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4211 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 /* Complement result if negative. */
4214 if (negz) {
4215 Py_SIZE(z) = -(Py_SIZE(z));
4216 z->ob_digit[size_z] = PyLong_MASK;
4217 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4218 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 Py_DECREF(a);
4221 Py_DECREF(b);
4222 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004223}
4224
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004225static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004226long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004228 PyObject *c;
4229 CHECK_BINOP(a, b);
4230 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4231 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004232}
4233
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004234static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004235long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004237 PyObject *c;
4238 CHECK_BINOP(a, b);
4239 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4240 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004241}
4242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004243static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004244long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 PyObject *c;
4247 CHECK_BINOP(a, b);
4248 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4249 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004250}
4251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004252static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004253long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 if (PyLong_CheckExact(v))
4256 Py_INCREF(v);
4257 else
4258 v = _PyLong_Copy((PyLongObject *)v);
4259 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004260}
4261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004262static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004263long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 double result;
4266 result = PyLong_AsDouble(v);
4267 if (result == -1.0 && PyErr_Occurred())
4268 return NULL;
4269 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004270}
4271
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004272static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004273long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004274
Tim Peters6d6c1a32001-08-02 04:15:00 +00004275static PyObject *
4276long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4277{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004278 PyObject *obase = NULL, *x = NULL;
4279 long base;
4280 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 if (type != &PyLong_Type)
4284 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004285 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4286 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004288 if (x == NULL) {
4289 if (obase != NULL) {
4290 PyErr_SetString(PyExc_TypeError,
4291 "int() missing string argument");
4292 return NULL;
4293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004295 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004296 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004298
4299 base = PyLong_AsLongAndOverflow(obase, &overflow);
4300 if (base == -1 && PyErr_Occurred())
4301 return NULL;
4302 if (overflow || (base != 0 && base < 2) || base > 36) {
4303 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004304 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004305 return NULL;
4306 }
4307
4308 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004309 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4311 /* Since PyLong_FromString doesn't have a length parameter,
4312 * check here for possible NULs in the string. */
4313 char *string;
4314 Py_ssize_t size = Py_SIZE(x);
4315 if (PyByteArray_Check(x))
4316 string = PyByteArray_AS_STRING(x);
4317 else
4318 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004319 if (strlen(string) != (size_t)size || !size) {
4320 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004321 x is a bytes or buffer, *and* a base is given. */
4322 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004323 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004324 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004325 return NULL;
4326 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004327 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004328 }
4329 else {
4330 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004331 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 return NULL;
4333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334}
4335
Guido van Rossumbef14172001-08-29 15:47:46 +00004336/* Wimpy, slow approach to tp_new calls for subtypes of long:
4337 first create a regular long from whatever arguments we got,
4338 then allocate a subtype instance and initialize it from
4339 the regular long. The regular long is then thrown away.
4340*/
4341static PyObject *
4342long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 PyLongObject *tmp, *newobj;
4345 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 assert(PyType_IsSubtype(type, &PyLong_Type));
4348 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4349 if (tmp == NULL)
4350 return NULL;
4351 assert(PyLong_CheckExact(tmp));
4352 n = Py_SIZE(tmp);
4353 if (n < 0)
4354 n = -n;
4355 newobj = (PyLongObject *)type->tp_alloc(type, n);
4356 if (newobj == NULL) {
4357 Py_DECREF(tmp);
4358 return NULL;
4359 }
4360 assert(PyLong_Check(newobj));
4361 Py_SIZE(newobj) = Py_SIZE(tmp);
4362 for (i = 0; i < n; i++)
4363 newobj->ob_digit[i] = tmp->ob_digit[i];
4364 Py_DECREF(tmp);
4365 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004366}
4367
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004368static PyObject *
4369long_getnewargs(PyLongObject *v)
4370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004372}
4373
Guido van Rossumb43daf72007-08-01 18:08:08 +00004374static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004375long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004377}
4378
4379static PyObject *
4380long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004381 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004382}
4383
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004384static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004385long__format__(PyObject *self, PyObject *args)
4386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004388 _PyUnicodeWriter writer;
4389 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4392 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004393
4394 _PyUnicodeWriter_Init(&writer, 0);
4395 ret = _PyLong_FormatAdvancedWriter(
4396 &writer,
4397 self,
4398 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4399 if (ret == -1) {
4400 _PyUnicodeWriter_Dealloc(&writer);
4401 return NULL;
4402 }
4403 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004404}
4405
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004406/* Return a pair (q, r) such that a = b * q + r, and
4407 abs(r) <= abs(b)/2, with equality possible only if q is even.
4408 In other words, q == a / b, rounded to the nearest integer using
4409 round-half-to-even. */
4410
4411PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004412_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004413{
4414 PyLongObject *quo = NULL, *rem = NULL;
4415 PyObject *one = NULL, *twice_rem, *result, *temp;
4416 int cmp, quo_is_odd, quo_is_neg;
4417
4418 /* Equivalent Python code:
4419
4420 def divmod_near(a, b):
4421 q, r = divmod(a, b)
4422 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4423 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4424 # positive, 2 * r < b if b negative.
4425 greater_than_half = 2*r > b if b > 0 else 2*r < b
4426 exactly_half = 2*r == b
4427 if greater_than_half or exactly_half and q % 2 == 1:
4428 q += 1
4429 r -= b
4430 return q, r
4431
4432 */
4433 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4434 PyErr_SetString(PyExc_TypeError,
4435 "non-integer arguments in division");
4436 return NULL;
4437 }
4438
4439 /* Do a and b have different signs? If so, quotient is negative. */
4440 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4441
4442 one = PyLong_FromLong(1L);
4443 if (one == NULL)
4444 return NULL;
4445
4446 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4447 goto error;
4448
4449 /* compare twice the remainder with the divisor, to see
4450 if we need to adjust the quotient and remainder */
4451 twice_rem = long_lshift((PyObject *)rem, one);
4452 if (twice_rem == NULL)
4453 goto error;
4454 if (quo_is_neg) {
4455 temp = long_neg((PyLongObject*)twice_rem);
4456 Py_DECREF(twice_rem);
4457 twice_rem = temp;
4458 if (twice_rem == NULL)
4459 goto error;
4460 }
4461 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4462 Py_DECREF(twice_rem);
4463
4464 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4465 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4466 /* fix up quotient */
4467 if (quo_is_neg)
4468 temp = long_sub(quo, (PyLongObject *)one);
4469 else
4470 temp = long_add(quo, (PyLongObject *)one);
4471 Py_DECREF(quo);
4472 quo = (PyLongObject *)temp;
4473 if (quo == NULL)
4474 goto error;
4475 /* and remainder */
4476 if (quo_is_neg)
4477 temp = long_add(rem, (PyLongObject *)b);
4478 else
4479 temp = long_sub(rem, (PyLongObject *)b);
4480 Py_DECREF(rem);
4481 rem = (PyLongObject *)temp;
4482 if (rem == NULL)
4483 goto error;
4484 }
4485
4486 result = PyTuple_New(2);
4487 if (result == NULL)
4488 goto error;
4489
4490 /* PyTuple_SET_ITEM steals references */
4491 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4492 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4493 Py_DECREF(one);
4494 return result;
4495
4496 error:
4497 Py_XDECREF(quo);
4498 Py_XDECREF(rem);
4499 Py_XDECREF(one);
4500 return NULL;
4501}
4502
Eric Smith8c663262007-08-25 02:26:07 +00004503static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004504long_round(PyObject *self, PyObject *args)
4505{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004506 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004507
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004508 /* To round an integer m to the nearest 10**n (n positive), we make use of
4509 * the divmod_near operation, defined by:
4510 *
4511 * divmod_near(a, b) = (q, r)
4512 *
4513 * where q is the nearest integer to the quotient a / b (the
4514 * nearest even integer in the case of a tie) and r == a - q * b.
4515 * Hence q * b = a - r is the nearest multiple of b to a,
4516 * preferring even multiples in the case of a tie.
4517 *
4518 * So the nearest multiple of 10**n to m is:
4519 *
4520 * m - divmod_near(m, 10**n)[1].
4521 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4523 return NULL;
4524 if (o_ndigits == NULL)
4525 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004526
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004527 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 if (ndigits == NULL)
4529 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004530
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004531 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004532 if (Py_SIZE(ndigits) >= 0) {
4533 Py_DECREF(ndigits);
4534 return long_long(self);
4535 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004536
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004537 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4538 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004539 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004540 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004542 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004543
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004544 result = PyLong_FromLong(10L);
4545 if (result == NULL) {
4546 Py_DECREF(ndigits);
4547 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004548 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004549
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004550 temp = long_pow(result, ndigits, Py_None);
4551 Py_DECREF(ndigits);
4552 Py_DECREF(result);
4553 result = temp;
4554 if (result == NULL)
4555 return NULL;
4556
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004557 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004558 Py_DECREF(result);
4559 result = temp;
4560 if (result == NULL)
4561 return NULL;
4562
4563 temp = long_sub((PyLongObject *)self,
4564 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4565 Py_DECREF(result);
4566 result = temp;
4567
4568 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004569}
4570
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004571static PyObject *
4572long_sizeof(PyLongObject *v)
4573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4577 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004578}
4579
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004580static PyObject *
4581long_bit_length(PyLongObject *v)
4582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 PyLongObject *result, *x, *y;
4584 Py_ssize_t ndigits, msd_bits = 0;
4585 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 assert(v != NULL);
4588 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004590 ndigits = ABS(Py_SIZE(v));
4591 if (ndigits == 0)
4592 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 msd = v->ob_digit[ndigits-1];
4595 while (msd >= 32) {
4596 msd_bits += 6;
4597 msd >>= 6;
4598 }
4599 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4602 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 /* expression above may overflow; use Python integers instead */
4605 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4606 if (result == NULL)
4607 return NULL;
4608 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4609 if (x == NULL)
4610 goto error;
4611 y = (PyLongObject *)long_mul(result, x);
4612 Py_DECREF(x);
4613 if (y == NULL)
4614 goto error;
4615 Py_DECREF(result);
4616 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4619 if (x == NULL)
4620 goto error;
4621 y = (PyLongObject *)long_add(result, x);
4622 Py_DECREF(x);
4623 if (y == NULL)
4624 goto error;
4625 Py_DECREF(result);
4626 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004629
Mark Dickinson22b20182010-05-10 21:27:53 +00004630 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 Py_DECREF(result);
4632 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004633}
4634
4635PyDoc_STRVAR(long_bit_length_doc,
4636"int.bit_length() -> int\n\
4637\n\
4638Number of bits necessary to represent self in binary.\n\
4639>>> bin(37)\n\
4640'0b100101'\n\
4641>>> (37).bit_length()\n\
46426");
4643
Christian Heimes53876d92008-04-19 00:31:39 +00004644#if 0
4645static PyObject *
4646long_is_finite(PyObject *v)
4647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004649}
4650#endif
4651
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004652
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004653static PyObject *
4654long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 PyObject *byteorder_str;
4657 PyObject *is_signed_obj = NULL;
4658 Py_ssize_t length;
4659 int little_endian;
4660 int is_signed;
4661 PyObject *bytes;
4662 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4665 &length, &byteorder_str,
4666 &is_signed_obj))
4667 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 if (args != NULL && Py_SIZE(args) > 2) {
4670 PyErr_SetString(PyExc_TypeError,
4671 "'signed' is a keyword-only argument");
4672 return NULL;
4673 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4676 little_endian = 1;
4677 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4678 little_endian = 0;
4679 else {
4680 PyErr_SetString(PyExc_ValueError,
4681 "byteorder must be either 'little' or 'big'");
4682 return NULL;
4683 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 if (is_signed_obj != NULL) {
4686 int cmp = PyObject_IsTrue(is_signed_obj);
4687 if (cmp < 0)
4688 return NULL;
4689 is_signed = cmp ? 1 : 0;
4690 }
4691 else {
4692 /* If the signed argument was omitted, use False as the
4693 default. */
4694 is_signed = 0;
4695 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 if (length < 0) {
4698 PyErr_SetString(PyExc_ValueError,
4699 "length argument must be non-negative");
4700 return NULL;
4701 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 bytes = PyBytes_FromStringAndSize(NULL, length);
4704 if (bytes == NULL)
4705 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4708 length, little_endian, is_signed) < 0) {
4709 Py_DECREF(bytes);
4710 return NULL;
4711 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004714}
4715
Mark Dickinson078c2532010-01-30 18:06:17 +00004716PyDoc_STRVAR(long_to_bytes_doc,
4717"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004718\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004719Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004720\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004722raised if the integer is not representable with the given number of\n\
4723bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004724\n\
4725The byteorder argument determines the byte order used to represent the\n\
4726integer. If byteorder is 'big', the most significant byte is at the\n\
4727beginning of the byte array. If byteorder is 'little', the most\n\
4728significant byte is at the end of the byte array. To request the native\n\
4729byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4730\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004731The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004733is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004734
4735static PyObject *
4736long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 PyObject *byteorder_str;
4739 PyObject *is_signed_obj = NULL;
4740 int little_endian;
4741 int is_signed;
4742 PyObject *obj;
4743 PyObject *bytes;
4744 PyObject *long_obj;
4745 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4748 &obj, &byteorder_str,
4749 &is_signed_obj))
4750 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 if (args != NULL && Py_SIZE(args) > 2) {
4753 PyErr_SetString(PyExc_TypeError,
4754 "'signed' is a keyword-only argument");
4755 return NULL;
4756 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4759 little_endian = 1;
4760 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4761 little_endian = 0;
4762 else {
4763 PyErr_SetString(PyExc_ValueError,
4764 "byteorder must be either 'little' or 'big'");
4765 return NULL;
4766 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 if (is_signed_obj != NULL) {
4769 int cmp = PyObject_IsTrue(is_signed_obj);
4770 if (cmp < 0)
4771 return NULL;
4772 is_signed = cmp ? 1 : 0;
4773 }
4774 else {
4775 /* If the signed argument was omitted, use False as the
4776 default. */
4777 is_signed = 0;
4778 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 bytes = PyObject_Bytes(obj);
4781 if (bytes == NULL)
4782 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 long_obj = _PyLong_FromByteArray(
4785 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4786 little_endian, is_signed);
4787 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789 /* If from_bytes() was used on subclass, allocate new subclass
4790 * instance, initialize it with decoded long value and return it.
4791 */
4792 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4793 PyLongObject *newobj;
4794 int i;
4795 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 newobj = (PyLongObject *)type->tp_alloc(type, n);
4798 if (newobj == NULL) {
4799 Py_DECREF(long_obj);
4800 return NULL;
4801 }
4802 assert(PyLong_Check(newobj));
4803 Py_SIZE(newobj) = Py_SIZE(long_obj);
4804 for (i = 0; i < n; i++) {
4805 newobj->ob_digit[i] =
4806 ((PyLongObject *)long_obj)->ob_digit[i];
4807 }
4808 Py_DECREF(long_obj);
4809 return (PyObject *)newobj;
4810 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004813}
4814
Mark Dickinson078c2532010-01-30 18:06:17 +00004815PyDoc_STRVAR(long_from_bytes_doc,
4816"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4817\n\
4818Return the integer represented by the given array of bytes.\n\
4819\n\
4820The bytes argument must either support the buffer protocol or be an\n\
4821iterable object producing bytes. Bytes and bytearray are examples of\n\
4822built-in objects that support the buffer protocol.\n\
4823\n\
4824The byteorder argument determines the byte order used to represent the\n\
4825integer. If byteorder is 'big', the most significant byte is at the\n\
4826beginning of the byte array. If byteorder is 'little', the most\n\
4827significant byte is at the end of the byte array. To request the native\n\
4828byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4829\n\
4830The signed keyword-only argument indicates whether two's complement is\n\
4831used to represent the integer.");
4832
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004833static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4835 "Returns self, the complex conjugate of any int."},
4836 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4837 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004838#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4840 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004841#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004842 {"to_bytes", (PyCFunction)long_to_bytes,
4843 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4844 {"from_bytes", (PyCFunction)long_from_bytes,
4845 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4846 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4847 "Truncating an Integral returns itself."},
4848 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4849 "Flooring an Integral returns itself."},
4850 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4851 "Ceiling of an Integral returns itself."},
4852 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4853 "Rounding an Integral returns itself.\n"
4854 "Rounding with an ndigits argument also returns an integer."},
4855 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4856 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4857 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4858 "Returns size in memory, in bytes"},
4859 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004860};
4861
Guido van Rossumb43daf72007-08-01 18:08:08 +00004862static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004863 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004864 (getter)long_long, (setter)NULL,
4865 "the real part of a complex number",
4866 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004867 {"imag",
4868 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004869 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004870 NULL},
4871 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004872 (getter)long_long, (setter)NULL,
4873 "the numerator of a rational number in lowest terms",
4874 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004875 {"denominator",
4876 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004877 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004878 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004879 {NULL} /* Sentinel */
4880};
4881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004882PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004883"int(x=0) -> integer\n\
4884int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004886Convert a number or string to an integer, or return 0 if no arguments\n\
4887are given. If x is a number, return x.__int__(). For floating point\n\
4888numbers, this truncates towards zero.\n\
4889\n\
4890If x is not a number or if base is given, then x must be a string,\n\
4891bytes, or bytearray instance representing an integer literal in the\n\
4892given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4893by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4894Base 0 means to interpret the base from the string as an integer literal.\n\
4895>>> int('0b100', base=0)\n\
48964");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004897
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004898static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004899 (binaryfunc)long_add, /*nb_add*/
4900 (binaryfunc)long_sub, /*nb_subtract*/
4901 (binaryfunc)long_mul, /*nb_multiply*/
4902 long_mod, /*nb_remainder*/
4903 long_divmod, /*nb_divmod*/
4904 long_pow, /*nb_power*/
4905 (unaryfunc)long_neg, /*nb_negative*/
4906 (unaryfunc)long_long, /*tp_positive*/
4907 (unaryfunc)long_abs, /*tp_absolute*/
4908 (inquiry)long_bool, /*tp_bool*/
4909 (unaryfunc)long_invert, /*nb_invert*/
4910 long_lshift, /*nb_lshift*/
4911 (binaryfunc)long_rshift, /*nb_rshift*/
4912 long_and, /*nb_and*/
4913 long_xor, /*nb_xor*/
4914 long_or, /*nb_or*/
4915 long_long, /*nb_int*/
4916 0, /*nb_reserved*/
4917 long_float, /*nb_float*/
4918 0, /* nb_inplace_add */
4919 0, /* nb_inplace_subtract */
4920 0, /* nb_inplace_multiply */
4921 0, /* nb_inplace_remainder */
4922 0, /* nb_inplace_power */
4923 0, /* nb_inplace_lshift */
4924 0, /* nb_inplace_rshift */
4925 0, /* nb_inplace_and */
4926 0, /* nb_inplace_xor */
4927 0, /* nb_inplace_or */
4928 long_div, /* nb_floor_divide */
4929 long_true_divide, /* nb_true_divide */
4930 0, /* nb_inplace_floor_divide */
4931 0, /* nb_inplace_true_divide */
4932 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004933};
4934
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004935PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004936 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4937 "int", /* tp_name */
4938 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4939 sizeof(digit), /* tp_itemsize */
4940 long_dealloc, /* tp_dealloc */
4941 0, /* tp_print */
4942 0, /* tp_getattr */
4943 0, /* tp_setattr */
4944 0, /* tp_reserved */
4945 long_to_decimal_string, /* tp_repr */
4946 &long_as_number, /* tp_as_number */
4947 0, /* tp_as_sequence */
4948 0, /* tp_as_mapping */
4949 (hashfunc)long_hash, /* tp_hash */
4950 0, /* tp_call */
4951 long_to_decimal_string, /* tp_str */
4952 PyObject_GenericGetAttr, /* tp_getattro */
4953 0, /* tp_setattro */
4954 0, /* tp_as_buffer */
4955 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4956 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4957 long_doc, /* tp_doc */
4958 0, /* tp_traverse */
4959 0, /* tp_clear */
4960 long_richcompare, /* tp_richcompare */
4961 0, /* tp_weaklistoffset */
4962 0, /* tp_iter */
4963 0, /* tp_iternext */
4964 long_methods, /* tp_methods */
4965 0, /* tp_members */
4966 long_getset, /* tp_getset */
4967 0, /* tp_base */
4968 0, /* tp_dict */
4969 0, /* tp_descr_get */
4970 0, /* tp_descr_set */
4971 0, /* tp_dictoffset */
4972 0, /* tp_init */
4973 0, /* tp_alloc */
4974 long_new, /* tp_new */
4975 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004976};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004977
Mark Dickinsonbd792642009-03-18 20:06:12 +00004978static PyTypeObject Int_InfoType;
4979
4980PyDoc_STRVAR(int_info__doc__,
4981"sys.int_info\n\
4982\n\
4983A struct sequence that holds information about Python's\n\
4984internal representation of integers. The attributes are read only.");
4985
4986static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004988 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004990};
4991
4992static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 "sys.int_info", /* name */
4994 int_info__doc__, /* doc */
4995 int_info_fields, /* fields */
4996 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004997};
4998
4999PyObject *
5000PyLong_GetInfo(void)
5001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005002 PyObject* int_info;
5003 int field = 0;
5004 int_info = PyStructSequence_New(&Int_InfoType);
5005 if (int_info == NULL)
5006 return NULL;
5007 PyStructSequence_SET_ITEM(int_info, field++,
5008 PyLong_FromLong(PyLong_SHIFT));
5009 PyStructSequence_SET_ITEM(int_info, field++,
5010 PyLong_FromLong(sizeof(digit)));
5011 if (PyErr_Occurred()) {
5012 Py_CLEAR(int_info);
5013 return NULL;
5014 }
5015 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005016}
5017
Guido van Rossumddefaf32007-01-14 03:31:43 +00005018int
5019_PyLong_Init(void)
5020{
5021#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 int ival, size;
5023 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005025 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5026 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5027 if (Py_TYPE(v) == &PyLong_Type) {
5028 /* The element is already initialized, most likely
5029 * the Python interpreter was initialized before.
5030 */
5031 Py_ssize_t refcnt;
5032 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5035 _Py_NewReference(op);
5036 /* _Py_NewReference sets the ref count to 1 but
5037 * the ref count might be larger. Set the refcnt
5038 * to the original refcnt + 1 */
5039 Py_REFCNT(op) = refcnt + 1;
5040 assert(Py_SIZE(op) == size);
5041 assert(v->ob_digit[0] == abs(ival));
5042 }
5043 else {
5044 PyObject_INIT(v, &PyLong_Type);
5045 }
5046 Py_SIZE(v) = size;
5047 v->ob_digit[0] = abs(ival);
5048 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005049#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 /* initialize int_info */
5051 if (Int_InfoType.tp_name == 0)
5052 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005055}
5056
5057void
5058PyLong_Fini(void)
5059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 /* Integers are currently statically allocated. Py_DECREF is not
5061 needed, but Python must forget about the reference or multiple
5062 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005063#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 int i;
5065 PyLongObject *v = small_ints;
5066 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5067 _Py_DEC_REFTOTAL;
5068 _Py_ForgetReference((PyObject*)v);
5069 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005070#endif
5071}