blob: 7e12b3488484296f15ffe65d36c9b441891ed3dd [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
33int quick_int_allocs, quick_neg_int_allocs;
34#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
Mark Dickinson8d48b432011-10-23 20:47:14 +0100323/* Get a C long int from a long int object or any object that has an __int__
324 method.
325
326 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
327 the result. Otherwise *overflow is 0.
328
329 For other errors (e.g., TypeError), return -1 and set an error condition.
330 In this case *overflow will be 0.
331*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This version by Tim Peters */
337 register PyLongObject *v;
338 unsigned long x, prev;
339 long res;
340 Py_ssize_t i;
341 int sign;
342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *overflow = 0;
345 if (vv == NULL) {
346 PyErr_BadInternalCall();
347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 nb = vv->ob_type->tp_as_number;
353 if (nb == NULL || nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError,
355 "an integer is required");
356 return -1;
357 }
358 vv = (*nb->nb_int) (vv);
359 if (vv == NULL)
360 return -1;
361 do_decref = 1;
362 if (!PyLong_Check(vv)) {
363 Py_DECREF(vv);
364 PyErr_SetString(PyExc_TypeError,
365 "nb_int should return int object");
366 return -1;
367 }
368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 res = -1;
371 v = (PyLongObject *)vv;
372 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 switch (i) {
375 case -1:
376 res = -(sdigit)v->ob_digit[0];
377 break;
378 case 0:
379 res = 0;
380 break;
381 case 1:
382 res = v->ob_digit[0];
383 break;
384 default:
385 sign = 1;
386 x = 0;
387 if (i < 0) {
388 sign = -1;
389 i = -(i);
390 }
391 while (--i >= 0) {
392 prev = x;
393 x = (x << PyLong_SHIFT) | v->ob_digit[i];
394 if ((x >> PyLong_SHIFT) != prev) {
395 *overflow = sign;
396 goto exit;
397 }
398 }
399 /* Haven't lost any bits, but casting to long requires extra
400 * care (see comment above).
401 */
402 if (x <= (unsigned long)LONG_MAX) {
403 res = (long)x * sign;
404 }
405 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
406 res = LONG_MIN;
407 }
408 else {
409 *overflow = sign;
410 /* res is already set to -1 */
411 }
412 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (do_decref) {
415 Py_DECREF(vv);
416 }
417 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000418}
419
Mark Dickinson8d48b432011-10-23 20:47:14 +0100420/* Get a C long int from a long int object or any object that has an __int__
421 method. Return -1 and set an error if overflow occurs. */
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000424PyLong_AsLong(PyObject *obj)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int overflow;
427 long result = PyLong_AsLongAndOverflow(obj, &overflow);
428 if (overflow) {
429 /* XXX: could be cute and give a different
430 message for overflow == -1 */
431 PyErr_SetString(PyExc_OverflowError,
432 "Python int too large to convert to C long");
433 }
434 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000435}
436
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000437/* Get a Py_ssize_t from a long int object.
438 Returns -1 and sets an error condition if overflow occurs. */
439
440Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000441PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 register PyLongObject *v;
443 size_t x, prev;
444 Py_ssize_t i;
445 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (vv == NULL) {
448 PyErr_BadInternalCall();
449 return -1;
450 }
451 if (!PyLong_Check(vv)) {
452 PyErr_SetString(PyExc_TypeError, "an integer is required");
453 return -1;
454 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 v = (PyLongObject *)vv;
457 i = Py_SIZE(v);
458 switch (i) {
459 case -1: return -(sdigit)v->ob_digit[0];
460 case 0: return 0;
461 case 1: return v->ob_digit[0];
462 }
463 sign = 1;
464 x = 0;
465 if (i < 0) {
466 sign = -1;
467 i = -(i);
468 }
469 while (--i >= 0) {
470 prev = x;
471 x = (x << PyLong_SHIFT) | v->ob_digit[i];
472 if ((x >> PyLong_SHIFT) != prev)
473 goto overflow;
474 }
475 /* Haven't lost any bits, but casting to a signed type requires
476 * extra care (see comment above).
477 */
478 if (x <= (size_t)PY_SSIZE_T_MAX) {
479 return (Py_ssize_t)x * sign;
480 }
481 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
482 return PY_SSIZE_T_MIN;
483 }
484 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485
Mark Dickinson22b20182010-05-10 21:27:53 +0000486 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyErr_SetString(PyExc_OverflowError,
488 "Python int too large to convert to C ssize_t");
489 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490}
491
Guido van Rossumd8c80482002-08-13 00:24:58 +0000492/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000493 Returns -1 and sets an error condition if overflow occurs. */
494
495unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000496PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 register PyLongObject *v;
499 unsigned long x, prev;
500 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (vv == NULL) {
503 PyErr_BadInternalCall();
504 return (unsigned long)-1;
505 }
506 if (!PyLong_Check(vv)) {
507 PyErr_SetString(PyExc_TypeError, "an integer is required");
508 return (unsigned long)-1;
509 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 v = (PyLongObject *)vv;
512 i = Py_SIZE(v);
513 x = 0;
514 if (i < 0) {
515 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000516 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 return (unsigned long) -1;
518 }
519 switch (i) {
520 case 0: return 0;
521 case 1: return v->ob_digit[0];
522 }
523 while (--i >= 0) {
524 prev = x;
525 x = (x << PyLong_SHIFT) | v->ob_digit[i];
526 if ((x >> PyLong_SHIFT) != prev) {
527 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000528 "python int too large to convert "
529 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 return (unsigned long) -1;
531 }
532 }
533 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000534}
535
Stefan Krahb77c6c62011-09-12 16:22:47 +0200536/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
537 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000538
539size_t
540PyLong_AsSize_t(PyObject *vv)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 register PyLongObject *v;
543 size_t x, prev;
544 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (vv == NULL) {
547 PyErr_BadInternalCall();
548 return (size_t) -1;
549 }
550 if (!PyLong_Check(vv)) {
551 PyErr_SetString(PyExc_TypeError, "an integer is required");
552 return (size_t)-1;
553 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 v = (PyLongObject *)vv;
556 i = Py_SIZE(v);
557 x = 0;
558 if (i < 0) {
559 PyErr_SetString(PyExc_OverflowError,
560 "can't convert negative value to size_t");
561 return (size_t) -1;
562 }
563 switch (i) {
564 case 0: return 0;
565 case 1: return v->ob_digit[0];
566 }
567 while (--i >= 0) {
568 prev = x;
569 x = (x << PyLong_SHIFT) | v->ob_digit[i];
570 if ((x >> PyLong_SHIFT) != prev) {
571 PyErr_SetString(PyExc_OverflowError,
572 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200573 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 }
575 }
576 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000577}
578
Thomas Hellera4ea6032003-04-17 18:55:45 +0000579/* Get a C unsigned long int from a long int object, ignoring the high bits.
580 Returns -1 and sets an error condition if an error occurs. */
581
Guido van Rossumddefaf32007-01-14 03:31:43 +0000582static unsigned long
583_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 register PyLongObject *v;
586 unsigned long x;
587 Py_ssize_t i;
588 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (vv == NULL || !PyLong_Check(vv)) {
591 PyErr_BadInternalCall();
592 return (unsigned long) -1;
593 }
594 v = (PyLongObject *)vv;
595 i = Py_SIZE(v);
596 switch (i) {
597 case 0: return 0;
598 case 1: return v->ob_digit[0];
599 }
600 sign = 1;
601 x = 0;
602 if (i < 0) {
603 sign = -1;
604 i = -i;
605 }
606 while (--i >= 0) {
607 x = (x << PyLong_SHIFT) | v->ob_digit[i];
608 }
609 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000610}
611
Guido van Rossumddefaf32007-01-14 03:31:43 +0000612unsigned long
613PyLong_AsUnsignedLongMask(register PyObject *op)
614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyNumberMethods *nb;
616 PyLongObject *lo;
617 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (op && PyLong_Check(op))
620 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
623 nb->nb_int == NULL) {
624 PyErr_SetString(PyExc_TypeError, "an integer is required");
625 return (unsigned long)-1;
626 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 lo = (PyLongObject*) (*nb->nb_int) (op);
629 if (lo == NULL)
630 return (unsigned long)-1;
631 if (PyLong_Check(lo)) {
632 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
633 Py_DECREF(lo);
634 if (PyErr_Occurred())
635 return (unsigned long)-1;
636 return val;
637 }
638 else
639 {
640 Py_DECREF(lo);
641 PyErr_SetString(PyExc_TypeError,
642 "nb_int should return int object");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645}
646
Tim Peters5b8132f2003-01-31 15:52:05 +0000647int
648_PyLong_Sign(PyObject *vv)
649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 assert(v != NULL);
653 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000656}
657
Tim Petersbaefd9e2003-01-28 20:37:45 +0000658size_t
659_PyLong_NumBits(PyObject *vv)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyLongObject *v = (PyLongObject *)vv;
662 size_t result = 0;
663 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 assert(v != NULL);
666 assert(PyLong_Check(v));
667 ndigits = ABS(Py_SIZE(v));
668 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
669 if (ndigits > 0) {
670 digit msd = v->ob_digit[ndigits - 1];
Tim Petersbaefd9e2003-01-28 20:37:45 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 result = (ndigits - 1) * PyLong_SHIFT;
673 if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
674 goto Overflow;
675 do {
676 ++result;
677 if (result == 0)
678 goto Overflow;
679 msd >>= 1;
680 } while (msd);
681 }
682 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000683
Mark Dickinson22b20182010-05-10 21:27:53 +0000684 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
686 "to express in a platform size_t");
687 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000688}
689
Tim Peters2a9b3672001-06-11 21:23:58 +0000690PyObject *
691_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000693{
Mark Dickinson22b20182010-05-10 21:27:53 +0000694 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 int incr; /* direction to move pstartbyte */
696 const unsigned char* pendbyte; /* MSB of bytes */
697 size_t numsignificantbytes; /* number of bytes that matter */
698 Py_ssize_t ndigits; /* number of Python long digits */
699 PyLongObject* v; /* result */
700 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (n == 0)
703 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (little_endian) {
706 pstartbyte = bytes;
707 pendbyte = bytes + n - 1;
708 incr = 1;
709 }
710 else {
711 pstartbyte = bytes + n - 1;
712 pendbyte = bytes;
713 incr = -1;
714 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (is_signed)
717 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200720 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 is positive, and leading 0xff bytes if negative. */
722 {
723 size_t i;
724 const unsigned char* p = pendbyte;
725 const int pincr = -incr; /* search MSB to LSB */
726 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 for (i = 0; i < n; ++i, p += pincr) {
729 if (*p != insignficant)
730 break;
731 }
732 numsignificantbytes = n - i;
733 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
734 actually has 2 significant bytes. OTOH, 0xff0001 ==
735 -0x00ffff, so we wouldn't *need* to bump it there; but we
736 do for 0xffff = -0x0001. To be safe without bothering to
737 check every case, bump it regardless. */
738 if (is_signed && numsignificantbytes < n)
739 ++numsignificantbytes;
740 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* How many Python long digits do we need? We have
743 8*numsignificantbytes bits, and each Python long digit has
744 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
745 /* catch overflow before it happens */
746 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
747 PyErr_SetString(PyExc_OverflowError,
748 "byte array too long to convert to int");
749 return NULL;
750 }
751 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
752 v = _PyLong_New(ndigits);
753 if (v == NULL)
754 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Copy the bits over. The tricky parts are computing 2's-comp on
757 the fly for signed numbers, and dealing with the mismatch between
758 8-bit bytes and (probably) 15-bit Python digits.*/
759 {
760 size_t i;
761 twodigits carry = 1; /* for 2's-comp calculation */
762 twodigits accum = 0; /* sliding register */
763 unsigned int accumbits = 0; /* number of bits in accum */
764 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
767 twodigits thisbyte = *p;
768 /* Compute correction for 2's comp, if needed. */
769 if (is_signed) {
770 thisbyte = (0xff ^ thisbyte) + carry;
771 carry = thisbyte >> 8;
772 thisbyte &= 0xff;
773 }
774 /* Because we're going LSB to MSB, thisbyte is
775 more significant than what's already in accum,
776 so needs to be prepended to accum. */
777 accum |= (twodigits)thisbyte << accumbits;
778 accumbits += 8;
779 if (accumbits >= PyLong_SHIFT) {
780 /* There's enough to fill a Python digit. */
781 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000782 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 ++idigit;
784 accum >>= PyLong_SHIFT;
785 accumbits -= PyLong_SHIFT;
786 assert(accumbits < PyLong_SHIFT);
787 }
788 }
789 assert(accumbits < PyLong_SHIFT);
790 if (accumbits) {
791 assert(idigit < ndigits);
792 v->ob_digit[idigit] = (digit)accum;
793 ++idigit;
794 }
795 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 Py_SIZE(v) = is_signed ? -idigit : idigit;
798 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000799}
800
801int
802_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 unsigned char* bytes, size_t n,
804 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000807 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000809 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
811 digit carry; /* for computing 2's-comp */
812 size_t j; /* # bytes filled */
813 unsigned char* p; /* pointer to next byte in bytes */
814 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (Py_SIZE(v) < 0) {
819 ndigits = -(Py_SIZE(v));
820 if (!is_signed) {
821 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000822 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return -1;
824 }
825 do_twos_comp = 1;
826 }
827 else {
828 ndigits = Py_SIZE(v);
829 do_twos_comp = 0;
830 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (little_endian) {
833 p = bytes;
834 pincr = 1;
835 }
836 else {
837 p = bytes + n - 1;
838 pincr = -1;
839 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 /* Copy over all the Python digits.
842 It's crucial that every Python digit except for the MSD contribute
843 exactly PyLong_SHIFT bits to the total, so first assert that the long is
844 normalized. */
845 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
846 j = 0;
847 accum = 0;
848 accumbits = 0;
849 carry = do_twos_comp ? 1 : 0;
850 for (i = 0; i < ndigits; ++i) {
851 digit thisdigit = v->ob_digit[i];
852 if (do_twos_comp) {
853 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
854 carry = thisdigit >> PyLong_SHIFT;
855 thisdigit &= PyLong_MASK;
856 }
857 /* Because we're going LSB to MSB, thisdigit is more
858 significant than what's already in accum, so needs to be
859 prepended to accum. */
860 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 /* The most-significant digit may be (probably is) at least
863 partly empty. */
864 if (i == ndigits - 1) {
865 /* Count # of sign bits -- they needn't be stored,
866 * although for signed conversion we need later to
867 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000868 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 while (s != 0) {
870 s >>= 1;
871 accumbits++;
872 }
873 }
874 else
875 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Store as many bytes as possible. */
878 while (accumbits >= 8) {
879 if (j >= n)
880 goto Overflow;
881 ++j;
882 *p = (unsigned char)(accum & 0xff);
883 p += pincr;
884 accumbits -= 8;
885 accum >>= 8;
886 }
887 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Store the straggler (if any). */
890 assert(accumbits < 8);
891 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
892 if (accumbits > 0) {
893 if (j >= n)
894 goto Overflow;
895 ++j;
896 if (do_twos_comp) {
897 /* Fill leading bits of the byte with sign bits
898 (appropriately pretending that the long had an
899 infinite supply of sign bits). */
900 accum |= (~(twodigits)0) << accumbits;
901 }
902 *p = (unsigned char)(accum & 0xff);
903 p += pincr;
904 }
905 else if (j == n && n > 0 && is_signed) {
906 /* The main loop filled the byte array exactly, so the code
907 just above didn't get to ensure there's a sign bit, and the
908 loop below wouldn't add one either. Make sure a sign bit
909 exists. */
910 unsigned char msb = *(p - pincr);
911 int sign_bit_set = msb >= 0x80;
912 assert(accumbits == 0);
913 if (sign_bit_set == do_twos_comp)
914 return 0;
915 else
916 goto Overflow;
917 }
Tim Peters05607ad2001-06-13 21:01:27 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* Fill remaining bytes with copies of the sign bit. */
920 {
921 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
922 for ( ; j < n; ++j, p += pincr)
923 *p = signbyte;
924 }
Tim Peters05607ad2001-06-13 21:01:27 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000927
Mark Dickinson22b20182010-05-10 21:27:53 +0000928 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
930 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000931
Tim Peters2a9b3672001-06-11 21:23:58 +0000932}
933
Mark Dickinson8d48b432011-10-23 20:47:14 +0100934/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000935
936PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000937PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000938{
Tim Peters70128a12001-06-16 08:48:40 +0000939#ifndef HAVE_LONG_LONG
940# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
941#endif
942#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000943# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000944#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* special-case null pointer */
946 if (!p)
947 return PyLong_FromLong(0);
948 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Tim Peters70128a12001-06-16 08:48:40 +0000949
Guido van Rossum78694d91998-09-18 14:14:13 +0000950}
951
Mark Dickinson8d48b432011-10-23 20:47:14 +0100952/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000953
954void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000955PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000956{
Tim Peters70128a12001-06-16 08:48:40 +0000957#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
961 x = PyLong_AsLong(vv);
962 else
963 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000964#else
Tim Peters70128a12001-06-16 08:48:40 +0000965
966#ifndef HAVE_LONG_LONG
967# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
968#endif
969#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000970# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000971#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
975 x = PyLong_AsLongLong(vv);
976 else
977 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000978
979#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (x == -1 && PyErr_Occurred())
982 return NULL;
983 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000984}
985
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000986#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +0000987
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000988/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +0000989 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000990 */
991
Tim Peterscf37dfc2001-06-14 18:42:50 +0000992#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +0000993#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +0000994
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000996
997PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000998PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyLongObject *v;
1001 unsigned PY_LONG_LONG abs_ival;
1002 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1003 int ndigits = 0;
1004 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 CHECK_SMALL_INT(ival);
1007 if (ival < 0) {
1008 /* avoid signed overflow on negation; see comments
1009 in PyLong_FromLong above. */
1010 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1011 negative = 1;
1012 }
1013 else {
1014 abs_ival = (unsigned PY_LONG_LONG)ival;
1015 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 /* Count the number of Python digits.
1018 We used to pick 5 ("big enough for anything"), but that's a
1019 waste of time and space given that 5*15 = 75 bits are rarely
1020 needed. */
1021 t = abs_ival;
1022 while (t) {
1023 ++ndigits;
1024 t >>= PyLong_SHIFT;
1025 }
1026 v = _PyLong_New(ndigits);
1027 if (v != NULL) {
1028 digit *p = v->ob_digit;
1029 Py_SIZE(v) = negative ? -ndigits : ndigits;
1030 t = abs_ival;
1031 while (t) {
1032 *p++ = (digit)(t & PyLong_MASK);
1033 t >>= PyLong_SHIFT;
1034 }
1035 }
1036 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001037}
1038
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001039/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001040
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001042PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyLongObject *v;
1045 unsigned PY_LONG_LONG t;
1046 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (ival < PyLong_BASE)
1049 return PyLong_FromLong((long)ival);
1050 /* Count the number of Python digits. */
1051 t = (unsigned PY_LONG_LONG)ival;
1052 while (t) {
1053 ++ndigits;
1054 t >>= PyLong_SHIFT;
1055 }
1056 v = _PyLong_New(ndigits);
1057 if (v != NULL) {
1058 digit *p = v->ob_digit;
1059 Py_SIZE(v) = ndigits;
1060 while (ival) {
1061 *p++ = (digit)(ival & PyLong_MASK);
1062 ival >>= PyLong_SHIFT;
1063 }
1064 }
1065 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066}
1067
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068/* Create a new long int object from a C Py_ssize_t. */
1069
1070PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001071PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyLongObject *v;
1074 size_t abs_ival;
1075 size_t t; /* unsigned so >> doesn't propagate sign bit */
1076 int ndigits = 0;
1077 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 CHECK_SMALL_INT(ival);
1080 if (ival < 0) {
1081 /* avoid signed overflow when ival = SIZE_T_MIN */
1082 abs_ival = (size_t)(-1-ival)+1;
1083 negative = 1;
1084 }
1085 else {
1086 abs_ival = (size_t)ival;
1087 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* Count the number of Python digits. */
1090 t = abs_ival;
1091 while (t) {
1092 ++ndigits;
1093 t >>= PyLong_SHIFT;
1094 }
1095 v = _PyLong_New(ndigits);
1096 if (v != NULL) {
1097 digit *p = v->ob_digit;
1098 Py_SIZE(v) = negative ? -ndigits : ndigits;
1099 t = abs_ival;
1100 while (t) {
1101 *p++ = (digit)(t & PyLong_MASK);
1102 t >>= PyLong_SHIFT;
1103 }
1104 }
1105 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106}
1107
1108/* Create a new long int object from a C size_t. */
1109
1110PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001111PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyLongObject *v;
1114 size_t t;
1115 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (ival < PyLong_BASE)
1118 return PyLong_FromLong((long)ival);
1119 /* Count the number of Python digits. */
1120 t = ival;
1121 while (t) {
1122 ++ndigits;
1123 t >>= PyLong_SHIFT;
1124 }
1125 v = _PyLong_New(ndigits);
1126 if (v != NULL) {
1127 digit *p = v->ob_digit;
1128 Py_SIZE(v) = ndigits;
1129 while (ival) {
1130 *p++ = (digit)(ival & PyLong_MASK);
1131 ival >>= PyLong_SHIFT;
1132 }
1133 }
1134 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001135}
1136
Mark Dickinson8d48b432011-10-23 20:47:14 +01001137/* Get a C long long int from a long int object or any object that has an
1138 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001139
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001140PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001141PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyLongObject *v;
1144 PY_LONG_LONG bytes;
1145 int one = 1;
1146 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (vv == NULL) {
1149 PyErr_BadInternalCall();
1150 return -1;
1151 }
1152 if (!PyLong_Check(vv)) {
1153 PyNumberMethods *nb;
1154 PyObject *io;
1155 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1156 nb->nb_int == NULL) {
1157 PyErr_SetString(PyExc_TypeError, "an integer is required");
1158 return -1;
1159 }
1160 io = (*nb->nb_int) (vv);
1161 if (io == NULL)
1162 return -1;
1163 if (PyLong_Check(io)) {
1164 bytes = PyLong_AsLongLong(io);
1165 Py_DECREF(io);
1166 return bytes;
1167 }
1168 Py_DECREF(io);
1169 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1170 return -1;
1171 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 v = (PyLongObject*)vv;
1174 switch(Py_SIZE(v)) {
1175 case -1: return -(sdigit)v->ob_digit[0];
1176 case 0: return 0;
1177 case 1: return v->ob_digit[0];
1178 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001179 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1180 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1183 if (res < 0)
1184 return (PY_LONG_LONG)-1;
1185 else
1186 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001187}
1188
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001189/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001190 Return -1 and set an error if overflow occurs. */
1191
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001192unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001193PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyLongObject *v;
1196 unsigned PY_LONG_LONG bytes;
1197 int one = 1;
1198 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001199
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001200 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyErr_BadInternalCall();
1202 return (unsigned PY_LONG_LONG)-1;
1203 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001204 if (!PyLong_Check(vv)) {
1205 PyErr_SetString(PyExc_TypeError, "an integer is required");
1206 return (unsigned PY_LONG_LONG)-1;
1207 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 v = (PyLongObject*)vv;
1210 switch(Py_SIZE(v)) {
1211 case 0: return 0;
1212 case 1: return v->ob_digit[0];
1213 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001214
Mark Dickinson22b20182010-05-10 21:27:53 +00001215 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1216 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1219 if (res < 0)
1220 return (unsigned PY_LONG_LONG)res;
1221 else
1222 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001223}
Tim Petersd1a7da62001-06-13 00:35:57 +00001224
Thomas Hellera4ea6032003-04-17 18:55:45 +00001225/* Get a C unsigned long int from a long int object, ignoring the high bits.
1226 Returns -1 and sets an error condition if an error occurs. */
1227
Guido van Rossumddefaf32007-01-14 03:31:43 +00001228static unsigned PY_LONG_LONG
1229_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 register PyLongObject *v;
1232 unsigned PY_LONG_LONG x;
1233 Py_ssize_t i;
1234 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 if (vv == NULL || !PyLong_Check(vv)) {
1237 PyErr_BadInternalCall();
1238 return (unsigned long) -1;
1239 }
1240 v = (PyLongObject *)vv;
1241 switch(Py_SIZE(v)) {
1242 case 0: return 0;
1243 case 1: return v->ob_digit[0];
1244 }
1245 i = Py_SIZE(v);
1246 sign = 1;
1247 x = 0;
1248 if (i < 0) {
1249 sign = -1;
1250 i = -i;
1251 }
1252 while (--i >= 0) {
1253 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1254 }
1255 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001256}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001257
1258unsigned PY_LONG_LONG
1259PyLong_AsUnsignedLongLongMask(register PyObject *op)
1260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyNumberMethods *nb;
1262 PyLongObject *lo;
1263 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (op && PyLong_Check(op))
1266 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1269 nb->nb_int == NULL) {
1270 PyErr_SetString(PyExc_TypeError, "an integer is required");
1271 return (unsigned PY_LONG_LONG)-1;
1272 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 lo = (PyLongObject*) (*nb->nb_int) (op);
1275 if (lo == NULL)
1276 return (unsigned PY_LONG_LONG)-1;
1277 if (PyLong_Check(lo)) {
1278 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1279 Py_DECREF(lo);
1280 if (PyErr_Occurred())
1281 return (unsigned PY_LONG_LONG)-1;
1282 return val;
1283 }
1284 else
1285 {
1286 Py_DECREF(lo);
1287 PyErr_SetString(PyExc_TypeError,
1288 "nb_int should return int object");
1289 return (unsigned PY_LONG_LONG)-1;
1290 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001291}
Tim Petersd1a7da62001-06-13 00:35:57 +00001292#undef IS_LITTLE_ENDIAN
1293
Mark Dickinson8d48b432011-10-23 20:47:14 +01001294/* Get a C long long int from a long int object or any object that has an
1295 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001296
Mark Dickinson8d48b432011-10-23 20:47:14 +01001297 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1298 the result. Otherwise *overflow is 0.
1299
1300 For other errors (e.g., TypeError), return -1 and set an error condition.
1301 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001302*/
1303
1304PY_LONG_LONG
1305PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* This version by Tim Peters */
1308 register PyLongObject *v;
1309 unsigned PY_LONG_LONG x, prev;
1310 PY_LONG_LONG res;
1311 Py_ssize_t i;
1312 int sign;
1313 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 *overflow = 0;
1316 if (vv == NULL) {
1317 PyErr_BadInternalCall();
1318 return -1;
1319 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!PyLong_Check(vv)) {
1322 PyNumberMethods *nb;
1323 nb = vv->ob_type->tp_as_number;
1324 if (nb == NULL || nb->nb_int == NULL) {
1325 PyErr_SetString(PyExc_TypeError,
1326 "an integer is required");
1327 return -1;
1328 }
1329 vv = (*nb->nb_int) (vv);
1330 if (vv == NULL)
1331 return -1;
1332 do_decref = 1;
1333 if (!PyLong_Check(vv)) {
1334 Py_DECREF(vv);
1335 PyErr_SetString(PyExc_TypeError,
1336 "nb_int should return int object");
1337 return -1;
1338 }
1339 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 res = -1;
1342 v = (PyLongObject *)vv;
1343 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 switch (i) {
1346 case -1:
1347 res = -(sdigit)v->ob_digit[0];
1348 break;
1349 case 0:
1350 res = 0;
1351 break;
1352 case 1:
1353 res = v->ob_digit[0];
1354 break;
1355 default:
1356 sign = 1;
1357 x = 0;
1358 if (i < 0) {
1359 sign = -1;
1360 i = -(i);
1361 }
1362 while (--i >= 0) {
1363 prev = x;
1364 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1365 if ((x >> PyLong_SHIFT) != prev) {
1366 *overflow = sign;
1367 goto exit;
1368 }
1369 }
1370 /* Haven't lost any bits, but casting to long requires extra
1371 * care (see comment above).
1372 */
1373 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1374 res = (PY_LONG_LONG)x * sign;
1375 }
1376 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1377 res = PY_LLONG_MIN;
1378 }
1379 else {
1380 *overflow = sign;
1381 /* res is already set to -1 */
1382 }
1383 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001384 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (do_decref) {
1386 Py_DECREF(vv);
1387 }
1388 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001389}
1390
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001391#endif /* HAVE_LONG_LONG */
1392
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001393#define CHECK_BINOP(v,w) \
1394 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001395 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1396 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001397 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001398
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001399/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1400 2**k if d is nonzero, else 0. */
1401
1402static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1404 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001405};
1406
1407static int
1408bits_in_digit(digit d)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 int d_bits = 0;
1411 while (d >= 32) {
1412 d_bits += 6;
1413 d >>= 6;
1414 }
1415 d_bits += (int)BitLengthTable[d];
1416 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001417}
1418
Tim Peters877a2122002-08-12 05:09:36 +00001419/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1420 * is modified in place, by adding y to it. Carries are propagated as far as
1421 * x[m-1], and the remaining carry (0 or 1) is returned.
1422 */
1423static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001424v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 Py_ssize_t i;
1427 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 assert(m >= n);
1430 for (i = 0; i < n; ++i) {
1431 carry += x[i] + y[i];
1432 x[i] = carry & PyLong_MASK;
1433 carry >>= PyLong_SHIFT;
1434 assert((carry & 1) == carry);
1435 }
1436 for (; carry && i < m; ++i) {
1437 carry += x[i];
1438 x[i] = carry & PyLong_MASK;
1439 carry >>= PyLong_SHIFT;
1440 assert((carry & 1) == carry);
1441 }
1442 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001443}
1444
1445/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1446 * is modified in place, by subtracting y from it. Borrows are propagated as
1447 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1448 */
1449static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001450v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 Py_ssize_t i;
1453 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 assert(m >= n);
1456 for (i = 0; i < n; ++i) {
1457 borrow = x[i] - y[i] - borrow;
1458 x[i] = borrow & PyLong_MASK;
1459 borrow >>= PyLong_SHIFT;
1460 borrow &= 1; /* keep only 1 sign bit */
1461 }
1462 for (; borrow && i < m; ++i) {
1463 borrow = x[i] - borrow;
1464 x[i] = borrow & PyLong_MASK;
1465 borrow >>= PyLong_SHIFT;
1466 borrow &= 1;
1467 }
1468 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001469}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001470
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001471/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1472 * result in z[0:m], and return the d bits shifted out of the top.
1473 */
1474static digit
1475v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 Py_ssize_t i;
1478 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 assert(0 <= d && d < PyLong_SHIFT);
1481 for (i=0; i < m; i++) {
1482 twodigits acc = (twodigits)a[i] << d | carry;
1483 z[i] = (digit)acc & PyLong_MASK;
1484 carry = (digit)(acc >> PyLong_SHIFT);
1485 }
1486 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001487}
1488
1489/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1490 * result in z[0:m], and return the d bits shifted out of the bottom.
1491 */
1492static digit
1493v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 Py_ssize_t i;
1496 digit carry = 0;
1497 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 assert(0 <= d && d < PyLong_SHIFT);
1500 for (i=m; i-- > 0;) {
1501 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1502 carry = (digit)acc & mask;
1503 z[i] = (digit)(acc >> d);
1504 }
1505 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001506}
1507
Tim Peters212e6142001-07-14 12:23:19 +00001508/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1509 in pout, and returning the remainder. pin and pout point at the LSD.
1510 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001511 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001512 immutable. */
1513
1514static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001515inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 assert(n > 0 && n <= PyLong_MASK);
1520 pin += size;
1521 pout += size;
1522 while (--size >= 0) {
1523 digit hi;
1524 rem = (rem << PyLong_SHIFT) | *--pin;
1525 *--pout = hi = (digit)(rem / n);
1526 rem -= (twodigits)hi * n;
1527 }
1528 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001529}
1530
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001531/* Divide a long integer by a digit, returning both the quotient
1532 (as function result) and the remainder (through *prem).
1533 The sign of a is ignored; n should not be zero. */
1534
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001535static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001536divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 const Py_ssize_t size = ABS(Py_SIZE(a));
1539 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 assert(n > 0 && n <= PyLong_MASK);
1542 z = _PyLong_New(size);
1543 if (z == NULL)
1544 return NULL;
1545 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1546 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001547}
1548
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001549/* Convert a long integer to a base 10 string. Returns a new non-shared
1550 string. (Return value is non-shared so that callers can modify the
1551 returned value if necessary.) */
1552
Victor Stinnerd3f08822012-05-29 12:57:52 +02001553static int
1554long_to_decimal_string_internal(PyObject *aa,
1555 PyObject **p_output,
1556 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 PyLongObject *scratch, *a;
1559 PyObject *str;
1560 Py_ssize_t size, strlen, size_a, i, j;
1561 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001563 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 a = (PyLongObject *)aa;
1566 if (a == NULL || !PyLong_Check(a)) {
1567 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 }
1570 size_a = ABS(Py_SIZE(a));
1571 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* quick and dirty upper bound for the number of digits
1574 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 But log2(a) < size_a * PyLong_SHIFT, and
1579 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1580 > 3 * _PyLong_DECIMAL_SHIFT
1581 */
1582 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1583 PyErr_SetString(PyExc_OverflowError,
1584 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001585 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 }
1587 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1588 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1589 scratch = _PyLong_New(size);
1590 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001591 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* convert array of base _PyLong_BASE digits in pin to an array of
1594 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1595 Volume 2 (3rd edn), section 4.4, Method 1b). */
1596 pin = a->ob_digit;
1597 pout = scratch->ob_digit;
1598 size = 0;
1599 for (i = size_a; --i >= 0; ) {
1600 digit hi = pin[i];
1601 for (j = 0; j < size; j++) {
1602 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1603 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1604 pout[j] = (digit)(z - (twodigits)hi *
1605 _PyLong_DECIMAL_BASE);
1606 }
1607 while (hi) {
1608 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1609 hi /= _PyLong_DECIMAL_BASE;
1610 }
1611 /* check for keyboard interrupt */
1612 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001613 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001614 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001615 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
1617 /* pout should have at least one digit, so that the case when a = 0
1618 works correctly */
1619 if (size == 0)
1620 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* calculate exact length of output string, and allocate */
1623 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1624 tenpow = 10;
1625 rem = pout[size-1];
1626 while (rem >= tenpow) {
1627 tenpow *= 10;
1628 strlen++;
1629 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001630 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001631 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1632 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001633 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001634 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001635 kind = writer->kind;
1636 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001638 else {
1639 str = PyUnicode_New(strlen, '9');
1640 if (str == NULL) {
1641 Py_DECREF(scratch);
1642 return -1;
1643 }
1644 kind = PyUnicode_KIND(str);
1645 }
1646
1647#define WRITE_DIGITS(TYPE) \
1648 do { \
1649 if (writer) \
1650 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1651 else \
1652 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1653 \
1654 *p = '\0'; \
1655 /* pout[0] through pout[size-2] contribute exactly \
1656 _PyLong_DECIMAL_SHIFT digits each */ \
1657 for (i=0; i < size - 1; i++) { \
1658 rem = pout[i]; \
1659 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1660 *--p = '0' + rem % 10; \
1661 rem /= 10; \
1662 } \
1663 } \
1664 /* pout[size-1]: always produce at least one decimal digit */ \
1665 rem = pout[i]; \
1666 do { \
1667 *--p = '0' + rem % 10; \
1668 rem /= 10; \
1669 } while (rem != 0); \
1670 \
1671 /* and sign */ \
1672 if (negative) \
1673 *--p = '-'; \
1674 \
1675 /* check we've counted correctly */ \
1676 if (writer) \
1677 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1678 else \
1679 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1680 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001683 if (kind == PyUnicode_1BYTE_KIND) {
1684 Py_UCS1 *p;
1685 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001687 else if (kind == PyUnicode_2BYTE_KIND) {
1688 Py_UCS2 *p;
1689 WRITE_DIGITS(Py_UCS2);
1690 }
1691 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001692 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001693 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001694 WRITE_DIGITS(Py_UCS4);
1695 }
1696#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001699 if (writer) {
1700 writer->pos += strlen;
1701 }
1702 else {
1703 assert(_PyUnicode_CheckConsistency(str, 1));
1704 *p_output = (PyObject *)str;
1705 }
1706 return 0;
1707}
1708
1709static PyObject *
1710long_to_decimal_string(PyObject *aa)
1711{
1712 PyObject *v;
1713 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1714 return NULL;
1715 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001716}
1717
Mark Dickinsoncd068122009-09-18 14:53:08 +00001718/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 which should be one of 2, 8 or 16. Return a string object.
1720 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1721 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001722
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723static int
1724long_format_binary(PyObject *aa, int base, int alternate,
1725 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001728 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001729 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001731 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001732 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001734
Victor Stinnerd3f08822012-05-29 12:57:52 +02001735 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (a == NULL || !PyLong_Check(a)) {
1737 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001738 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 }
1740 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001741 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 /* Compute a rough upper bound for the length of the string */
1744 switch (base) {
1745 case 16:
1746 bits = 4;
1747 break;
1748 case 8:
1749 bits = 3;
1750 break;
1751 case 2:
1752 bits = 1;
1753 break;
1754 default:
1755 assert(0); /* shouldn't ever get here */
1756 bits = 0; /* to silence gcc warning */
1757 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001758
Mark Dickinsone2846542012-04-20 21:21:24 +01001759 /* Compute exact length 'sz' of output string. */
1760 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001761 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001762 }
1763 else {
1764 Py_ssize_t size_a_in_bits;
1765 /* Ensure overflow doesn't occur during computation of sz. */
1766 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1767 PyErr_SetString(PyExc_OverflowError,
1768 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001769 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001770 }
1771 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1772 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001773 /* Allow 1 character for a '-' sign. */
1774 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1775 }
1776 if (alternate) {
1777 /* 2 characters for prefix */
1778 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001779 }
1780
Victor Stinnerd3f08822012-05-29 12:57:52 +02001781 if (writer) {
1782 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1783 return -1;
1784 kind = writer->kind;
1785 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
1787 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001788 v = PyUnicode_New(sz, 'x');
1789 if (v == NULL)
1790 return -1;
1791 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001793
Victor Stinnerd3f08822012-05-29 12:57:52 +02001794#define WRITE_DIGITS(TYPE) \
1795 do { \
1796 if (writer) \
1797 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1798 else \
1799 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1800 \
1801 if (size_a == 0) { \
1802 *--p = '0'; \
1803 } \
1804 else { \
1805 /* JRH: special case for power-of-2 bases */ \
1806 twodigits accum = 0; \
1807 int accumbits = 0; /* # of bits in accum */ \
1808 Py_ssize_t i; \
1809 for (i = 0; i < size_a; ++i) { \
1810 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1811 accumbits += PyLong_SHIFT; \
1812 assert(accumbits >= bits); \
1813 do { \
1814 char cdigit; \
1815 cdigit = (char)(accum & (base - 1)); \
1816 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1817 *--p = cdigit; \
1818 accumbits -= bits; \
1819 accum >>= bits; \
1820 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1821 } \
1822 } \
1823 \
1824 if (alternate) { \
1825 if (base == 16) \
1826 *--p = 'x'; \
1827 else if (base == 8) \
1828 *--p = 'o'; \
1829 else /* (base == 2) */ \
1830 *--p = 'b'; \
1831 *--p = '0'; \
1832 } \
1833 if (negative) \
1834 *--p = '-'; \
1835 if (writer) \
1836 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1837 else \
1838 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1839 } while (0)
1840
1841 if (kind == PyUnicode_1BYTE_KIND) {
1842 Py_UCS1 *p;
1843 WRITE_DIGITS(Py_UCS1);
1844 }
1845 else if (kind == PyUnicode_2BYTE_KIND) {
1846 Py_UCS2 *p;
1847 WRITE_DIGITS(Py_UCS2);
1848 }
1849 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001850 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001851 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 WRITE_DIGITS(Py_UCS4);
1853 }
1854#undef WRITE_DIGITS
1855
1856 if (writer) {
1857 writer->pos += sz;
1858 }
1859 else {
1860 assert(_PyUnicode_CheckConsistency(v, 1));
1861 *p_output = v;
1862 }
1863 return 0;
1864}
1865
1866PyObject *
1867_PyLong_Format(PyObject *obj, int base)
1868{
1869 PyObject *str;
1870 int err;
1871 if (base == 10)
1872 err = long_to_decimal_string_internal(obj, &str, NULL);
1873 else
1874 err = long_format_binary(obj, base, 1, &str, NULL);
1875 if (err == -1)
1876 return NULL;
1877 return str;
1878}
1879
1880int
1881_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1882 PyObject *obj,
1883 int base, int alternate)
1884{
1885 if (base == 10)
1886 return long_to_decimal_string_internal(obj, NULL, writer);
1887 else
1888 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001889}
1890
Thomas Wouters477c8d52006-05-27 19:21:47 +00001891/* Table of digit values for 8-bit string -> integer conversion.
1892 * '0' maps to 0, ..., '9' maps to 9.
1893 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1894 * All other indices map to 37.
1895 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001896 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001897 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001898unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1900 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1901 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1902 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1903 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1904 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1905 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1906 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1907 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1908 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1909 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1910 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1911 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1912 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1913 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1914 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001915};
1916
1917/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001918 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1919 * non-digit (which may be *str!). A normalized long is returned.
1920 * The point to this routine is that it takes time linear in the number of
1921 * string characters.
1922 */
1923static PyLongObject *
1924long_from_binary_base(char **str, int base)
1925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 char *p = *str;
1927 char *start = p;
1928 int bits_per_char;
1929 Py_ssize_t n;
1930 PyLongObject *z;
1931 twodigits accum;
1932 int bits_in_accum;
1933 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1936 n = base;
1937 for (bits_per_char = -1; n; ++bits_per_char)
1938 n >>= 1;
1939 /* n <- total # of bits needed, while setting p to end-of-string */
1940 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1941 ++p;
1942 *str = p;
1943 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1944 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1945 if (n / bits_per_char < p - start) {
1946 PyErr_SetString(PyExc_ValueError,
1947 "int string too large to convert");
1948 return NULL;
1949 }
1950 n = n / PyLong_SHIFT;
1951 z = _PyLong_New(n);
1952 if (z == NULL)
1953 return NULL;
1954 /* Read string from right, and fill in long from left; i.e.,
1955 * from least to most significant in both.
1956 */
1957 accum = 0;
1958 bits_in_accum = 0;
1959 pdigit = z->ob_digit;
1960 while (--p >= start) {
1961 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1962 assert(k >= 0 && k < base);
1963 accum |= (twodigits)k << bits_in_accum;
1964 bits_in_accum += bits_per_char;
1965 if (bits_in_accum >= PyLong_SHIFT) {
1966 *pdigit++ = (digit)(accum & PyLong_MASK);
1967 assert(pdigit - z->ob_digit <= n);
1968 accum >>= PyLong_SHIFT;
1969 bits_in_accum -= PyLong_SHIFT;
1970 assert(bits_in_accum < PyLong_SHIFT);
1971 }
1972 }
1973 if (bits_in_accum) {
1974 assert(bits_in_accum <= PyLong_SHIFT);
1975 *pdigit++ = (digit)accum;
1976 assert(pdigit - z->ob_digit <= n);
1977 }
1978 while (pdigit - z->ob_digit < n)
1979 *pdigit++ = 0;
1980 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001981}
1982
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001983PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001984PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 int sign = 1, error_if_nonzero = 0;
1987 char *start, *orig_str = str;
1988 PyLongObject *z = NULL;
1989 PyObject *strobj;
1990 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 if ((base != 0 && base < 2) || base > 36) {
1993 PyErr_SetString(PyExc_ValueError,
1994 "int() arg 2 must be >= 2 and <= 36");
1995 return NULL;
1996 }
1997 while (*str != '\0' && isspace(Py_CHARMASK(*str)))
1998 str++;
1999 if (*str == '+')
2000 ++str;
2001 else if (*str == '-') {
2002 ++str;
2003 sign = -1;
2004 }
2005 if (base == 0) {
2006 if (str[0] != '0')
2007 base = 10;
2008 else if (str[1] == 'x' || str[1] == 'X')
2009 base = 16;
2010 else if (str[1] == 'o' || str[1] == 'O')
2011 base = 8;
2012 else if (str[1] == 'b' || str[1] == 'B')
2013 base = 2;
2014 else {
2015 /* "old" (C-style) octal literal, now invalid.
2016 it might still be zero though */
2017 error_if_nonzero = 1;
2018 base = 10;
2019 }
2020 }
2021 if (str[0] == '0' &&
2022 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2023 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2024 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2025 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 start = str;
2028 if ((base & (base - 1)) == 0)
2029 z = long_from_binary_base(&str, base);
2030 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031/***
2032Binary bases can be converted in time linear in the number of digits, because
2033Python's representation base is binary. Other bases (including decimal!) use
2034the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002035
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036First some math: the largest integer that can be expressed in N base-B digits
2037is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2038case number of Python digits needed to hold it is the smallest integer n s.t.
2039
2040 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2041 BASE**n >= B**N [taking logs to base BASE]
2042 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2043
2044The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2045this quickly. A Python long with that much space is reserved near the start,
2046and the result is computed into it.
2047
2048The input string is actually treated as being in base base**i (i.e., i digits
2049are processed at a time), where two more static arrays hold:
2050
2051 convwidth_base[base] = the largest integer i such that base**i <= BASE
2052 convmultmax_base[base] = base ** convwidth_base[base]
2053
2054The first of these is the largest i such that i consecutive input digits
2055must fit in a single Python digit. The second is effectively the input
2056base we're really using.
2057
2058Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2059convmultmax_base[base], the result is "simply"
2060
2061 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2062
2063where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002064
2065Error analysis: as above, the number of Python digits `n` needed is worst-
2066case
2067
2068 n >= N * log(B)/log(BASE)
2069
2070where `N` is the number of input digits in base `B`. This is computed via
2071
2072 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2073
2074below. Two numeric concerns are how much space this can waste, and whether
2075the computed result can be too small. To be concrete, assume BASE = 2**15,
2076which is the default (and it's unlikely anyone changes that).
2077
2078Waste isn't a problem: provided the first input digit isn't 0, the difference
2079between the worst-case input with N digits and the smallest input with N
2080digits is about a factor of B, but B is small compared to BASE so at most
2081one allocated Python digit can remain unused on that count. If
2082N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2083and adding 1 returns a result 1 larger than necessary. However, that can't
2084happen: whenever B is a power of 2, long_from_binary_base() is called
2085instead, and it's impossible for B**i to be an integer power of 2**15 when
2086B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2087an exact integer when B is not a power of 2, since B**i has a prime factor
2088other than 2 in that case, but (2**15)**j's only prime factor is 2).
2089
2090The computed result can be too small if the true value of N*log(B)/log(BASE)
2091is a little bit larger than an exact integer, but due to roundoff errors (in
2092computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2093yields a numeric result a little less than that integer. Unfortunately, "how
2094close can a transcendental function get to an integer over some range?"
2095questions are generally theoretically intractable. Computer analysis via
2096continued fractions is practical: expand log(B)/log(BASE) via continued
2097fractions, giving a sequence i/j of "the best" rational approximations. Then
2098j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2099we can get very close to being in trouble, but very rarely. For example,
210076573 is a denominator in one of the continued-fraction approximations to
2101log(10)/log(2**15), and indeed:
2102
2103 >>> log(10)/log(2**15)*76573
2104 16958.000000654003
2105
2106is very close to an integer. If we were working with IEEE single-precision,
2107rounding errors could kill us. Finding worst cases in IEEE double-precision
2108requires better-than-double-precision log() functions, and Tim didn't bother.
2109Instead the code checks to see whether the allocated space is enough as each
2110new Python digit is added, and copies the whole thing to a larger long if not.
2111This should happen extremely rarely, and in fact I don't have a test case
2112that triggers it(!). Instead the code was tested by artificially allocating
2113just 1 digit at the start, so that the copying code was exercised for every
2114digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 register twodigits c; /* current input character */
2117 Py_ssize_t size_z;
2118 int i;
2119 int convwidth;
2120 twodigits convmultmax, convmult;
2121 digit *pz, *pzstop;
2122 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 static double log_base_BASE[37] = {0.0e0,};
2125 static int convwidth_base[37] = {0,};
2126 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (log_base_BASE[base] == 0.0) {
2129 twodigits convmax = base;
2130 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002131
Mark Dickinson22b20182010-05-10 21:27:53 +00002132 log_base_BASE[base] = (log((double)base) /
2133 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 for (;;) {
2135 twodigits next = convmax * base;
2136 if (next > PyLong_BASE)
2137 break;
2138 convmax = next;
2139 ++i;
2140 }
2141 convmultmax_base[base] = convmax;
2142 assert(i > 0);
2143 convwidth_base[base] = i;
2144 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 /* Find length of the string of numeric characters. */
2147 scan = str;
2148 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2149 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Create a long object that can contain the largest possible
2152 * integer with this base and length. Note that there's no
2153 * need to initialize z->ob_digit -- no slot is read up before
2154 * being stored into.
2155 */
2156 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2157 /* Uncomment next line to test exceedingly rare copy code */
2158 /* size_z = 1; */
2159 assert(size_z > 0);
2160 z = _PyLong_New(size_z);
2161 if (z == NULL)
2162 return NULL;
2163 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* `convwidth` consecutive input digits are treated as a single
2166 * digit in base `convmultmax`.
2167 */
2168 convwidth = convwidth_base[base];
2169 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* Work ;-) */
2172 while (str < scan) {
2173 /* grab up to convwidth digits from the input string */
2174 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2175 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2176 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002177 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 assert(c < PyLong_BASE);
2179 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 convmult = convmultmax;
2182 /* Calculate the shift only if we couldn't get
2183 * convwidth digits.
2184 */
2185 if (i != convwidth) {
2186 convmult = base;
2187 for ( ; i > 1; --i)
2188 convmult *= base;
2189 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* Multiply z by convmult, and add c. */
2192 pz = z->ob_digit;
2193 pzstop = pz + Py_SIZE(z);
2194 for (; pz < pzstop; ++pz) {
2195 c += (twodigits)*pz * convmult;
2196 *pz = (digit)(c & PyLong_MASK);
2197 c >>= PyLong_SHIFT;
2198 }
2199 /* carry off the current end? */
2200 if (c) {
2201 assert(c < PyLong_BASE);
2202 if (Py_SIZE(z) < size_z) {
2203 *pz = (digit)c;
2204 ++Py_SIZE(z);
2205 }
2206 else {
2207 PyLongObject *tmp;
2208 /* Extremely rare. Get more space. */
2209 assert(Py_SIZE(z) == size_z);
2210 tmp = _PyLong_New(size_z + 1);
2211 if (tmp == NULL) {
2212 Py_DECREF(z);
2213 return NULL;
2214 }
2215 memcpy(tmp->ob_digit,
2216 z->ob_digit,
2217 sizeof(digit) * size_z);
2218 Py_DECREF(z);
2219 z = tmp;
2220 z->ob_digit[size_z] = (digit)c;
2221 ++size_z;
2222 }
2223 }
2224 }
2225 }
2226 if (z == NULL)
2227 return NULL;
2228 if (error_if_nonzero) {
2229 /* reset the base to 0, else the exception message
2230 doesn't make too much sense */
2231 base = 0;
2232 if (Py_SIZE(z) != 0)
2233 goto onError;
2234 /* there might still be other problems, therefore base
2235 remains zero here for the same reason */
2236 }
2237 if (str == start)
2238 goto onError;
2239 if (sign < 0)
2240 Py_SIZE(z) = -(Py_SIZE(z));
2241 while (*str && isspace(Py_CHARMASK(*str)))
2242 str++;
2243 if (*str != '\0')
2244 goto onError;
2245 if (pend)
2246 *pend = str;
2247 long_normalize(z);
2248 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002249
Mark Dickinson22b20182010-05-10 21:27:53 +00002250 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 Py_XDECREF(z);
2252 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2253 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2254 if (strobj == NULL)
2255 return NULL;
2256 PyErr_Format(PyExc_ValueError,
2257 "invalid literal for int() with base %d: %R",
2258 base, strobj);
2259 Py_DECREF(strobj);
2260 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002261}
2262
2263PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002264PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002265{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002266 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2267 if (unicode == NULL)
2268 return NULL;
2269 v = PyLong_FromUnicodeObject(unicode, base);
2270 Py_DECREF(unicode);
2271 return v;
2272}
2273
2274PyObject *
2275PyLong_FromUnicodeObject(PyObject *u, int base)
2276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002278 PyObject *asciidig;
2279 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002280 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002282 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002283 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002285 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002286 if (buffer == NULL) {
2287 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return NULL;
2289 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002290 result = PyLong_FromString(buffer, &end, base);
2291 if (result != NULL && end != buffer + buflen) {
2292 PyErr_SetString(PyExc_ValueError,
2293 "null byte in argument for int()");
2294 Py_DECREF(result);
2295 result = NULL;
2296 }
2297 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002299}
2300
Tim Peters9f688bf2000-07-07 15:53:28 +00002301/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002302static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002304static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002305
2306/* Long division with remainder, top-level routine */
2307
Guido van Rossume32e0141992-01-19 16:31:05 +00002308static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002309long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2313 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (size_b == 0) {
2316 PyErr_SetString(PyExc_ZeroDivisionError,
2317 "integer division or modulo by zero");
2318 return -1;
2319 }
2320 if (size_a < size_b ||
2321 (size_a == size_b &&
2322 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2323 /* |a| < |b|. */
2324 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2325 if (*pdiv == NULL)
2326 return -1;
2327 Py_INCREF(a);
2328 *prem = (PyLongObject *) a;
2329 return 0;
2330 }
2331 if (size_b == 1) {
2332 digit rem = 0;
2333 z = divrem1(a, b->ob_digit[0], &rem);
2334 if (z == NULL)
2335 return -1;
2336 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2337 if (*prem == NULL) {
2338 Py_DECREF(z);
2339 return -1;
2340 }
2341 }
2342 else {
2343 z = x_divrem(a, b, prem);
2344 if (z == NULL)
2345 return -1;
2346 }
2347 /* Set the signs.
2348 The quotient z has the sign of a*b;
2349 the remainder r has the sign of a,
2350 so a = b*z + r. */
2351 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2352 NEGATE(z);
2353 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2354 NEGATE(*prem);
2355 *pdiv = maybe_small_long(z);
2356 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002357}
2358
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002359/* Unsigned long division with remainder -- the algorithm. The arguments v1
2360 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002363x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 PyLongObject *v, *w, *a;
2366 Py_ssize_t i, k, size_v, size_w;
2367 int d;
2368 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2369 twodigits vv;
2370 sdigit zhi;
2371 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2374 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2375 handle the special case when the initial estimate q for a quotient
2376 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2377 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* allocate space; w will also be used to hold the final remainder */
2380 size_v = ABS(Py_SIZE(v1));
2381 size_w = ABS(Py_SIZE(w1));
2382 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2383 v = _PyLong_New(size_v+1);
2384 if (v == NULL) {
2385 *prem = NULL;
2386 return NULL;
2387 }
2388 w = _PyLong_New(size_w);
2389 if (w == NULL) {
2390 Py_DECREF(v);
2391 *prem = NULL;
2392 return NULL;
2393 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2396 shift v1 left by the same amount. Results go into w and v. */
2397 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2398 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2399 assert(carry == 0);
2400 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2401 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2402 v->ob_digit[size_v] = carry;
2403 size_v++;
2404 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2407 at most (and usually exactly) k = size_v - size_w digits. */
2408 k = size_v - size_w;
2409 assert(k >= 0);
2410 a = _PyLong_New(k);
2411 if (a == NULL) {
2412 Py_DECREF(w);
2413 Py_DECREF(v);
2414 *prem = NULL;
2415 return NULL;
2416 }
2417 v0 = v->ob_digit;
2418 w0 = w->ob_digit;
2419 wm1 = w0[size_w-1];
2420 wm2 = w0[size_w-2];
2421 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2422 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2423 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002426 Py_DECREF(a);
2427 Py_DECREF(w);
2428 Py_DECREF(v);
2429 *prem = NULL;
2430 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002431 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* estimate quotient digit q; may overestimate by 1 (rare) */
2434 vtop = vk[size_w];
2435 assert(vtop <= wm1);
2436 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2437 q = (digit)(vv / wm1);
2438 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2439 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2440 | vk[size_w-2])) {
2441 --q;
2442 r += wm1;
2443 if (r >= PyLong_BASE)
2444 break;
2445 }
2446 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2449 zhi = 0;
2450 for (i = 0; i < size_w; ++i) {
2451 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2452 -PyLong_BASE * q <= z < PyLong_BASE */
2453 z = (sdigit)vk[i] + zhi -
2454 (stwodigits)q * (stwodigits)w0[i];
2455 vk[i] = (digit)z & PyLong_MASK;
2456 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002457 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* add w back if q was too large (this branch taken rarely) */
2461 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2462 if ((sdigit)vtop + zhi < 0) {
2463 carry = 0;
2464 for (i = 0; i < size_w; ++i) {
2465 carry += vk[i] + w0[i];
2466 vk[i] = carry & PyLong_MASK;
2467 carry >>= PyLong_SHIFT;
2468 }
2469 --q;
2470 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* store quotient digit */
2473 assert(q < PyLong_BASE);
2474 *--ak = q;
2475 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* unshift remainder; we reuse w to store the result */
2478 carry = v_rshift(w0, v0, size_w, d);
2479 assert(carry==0);
2480 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 *prem = long_normalize(w);
2483 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002484}
2485
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002486/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2487 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2488 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2489 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2490 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2491 -1.0. */
2492
2493/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2494#if DBL_MANT_DIG == 53
2495#define EXP2_DBL_MANT_DIG 9007199254740992.0
2496#else
2497#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2498#endif
2499
2500double
2501_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2504 /* See below for why x_digits is always large enough. */
2505 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2506 double dx;
2507 /* Correction term for round-half-to-even rounding. For a digit x,
2508 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2509 multiple of 4, rounding ties to a multiple of 8. */
2510 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 a_size = ABS(Py_SIZE(a));
2513 if (a_size == 0) {
2514 /* Special case for 0: significand 0.0, exponent 0. */
2515 *e = 0;
2516 return 0.0;
2517 }
2518 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2519 /* The following is an overflow-free version of the check
2520 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2521 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2522 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2523 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002524 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2528 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 Number of digits needed for result: write // for floor division.
2531 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2540 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2543 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2544 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 in both cases.
2551 */
2552 if (a_bits <= DBL_MANT_DIG + 2) {
2553 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2554 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2555 x_size = 0;
2556 while (x_size < shift_digits)
2557 x_digits[x_size++] = 0;
2558 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2559 (int)shift_bits);
2560 x_size += a_size;
2561 x_digits[x_size++] = rem;
2562 }
2563 else {
2564 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2565 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2566 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2567 a_size - shift_digits, (int)shift_bits);
2568 x_size = a_size - shift_digits;
2569 /* For correct rounding below, we need the least significant
2570 bit of x to be 'sticky' for this shift: if any of the bits
2571 shifted out was nonzero, we set the least significant bit
2572 of x. */
2573 if (rem)
2574 x_digits[0] |= 1;
2575 else
2576 while (shift_digits > 0)
2577 if (a->ob_digit[--shift_digits]) {
2578 x_digits[0] |= 1;
2579 break;
2580 }
2581 }
Victor Stinner63941882011-09-29 00:42:28 +02002582 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /* Round, and convert to double. */
2585 x_digits[0] += half_even_correction[x_digits[0] & 7];
2586 dx = x_digits[--x_size];
2587 while (x_size > 0)
2588 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 /* Rescale; make correction if result is 1.0. */
2591 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2592 if (dx == 1.0) {
2593 if (a_bits == PY_SSIZE_T_MAX)
2594 goto overflow;
2595 dx = 0.5;
2596 a_bits += 1;
2597 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 *e = a_bits;
2600 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002601
2602 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 /* exponent > PY_SSIZE_T_MAX */
2604 PyErr_SetString(PyExc_OverflowError,
2605 "huge integer: number of bits overflows a Py_ssize_t");
2606 *e = 0;
2607 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002608}
2609
2610/* Get a C double from a long int object. Rounds to the nearest double,
2611 using the round-half-to-even rule in the case of a tie. */
2612
2613double
2614PyLong_AsDouble(PyObject *v)
2615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 Py_ssize_t exponent;
2617 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002618
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002619 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 PyErr_BadInternalCall();
2621 return -1.0;
2622 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002623 if (!PyLong_Check(v)) {
2624 PyErr_SetString(PyExc_TypeError, "an integer is required");
2625 return -1.0;
2626 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2628 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2629 PyErr_SetString(PyExc_OverflowError,
2630 "long int too large to convert to float");
2631 return -1.0;
2632 }
2633 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002634}
2635
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002636/* Methods */
2637
2638static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002639long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002642}
2643
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002644static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002645long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 if (Py_SIZE(a) != Py_SIZE(b)) {
2650 sign = Py_SIZE(a) - Py_SIZE(b);
2651 }
2652 else {
2653 Py_ssize_t i = ABS(Py_SIZE(a));
2654 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2655 ;
2656 if (i < 0)
2657 sign = 0;
2658 else {
2659 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2660 if (Py_SIZE(a) < 0)
2661 sign = -sign;
2662 }
2663 }
2664 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002665}
2666
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002667#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002669
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002670static PyObject *
2671long_richcompare(PyObject *self, PyObject *other, int op)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 int result;
2674 PyObject *v;
2675 CHECK_BINOP(self, other);
2676 if (self == other)
2677 result = 0;
2678 else
2679 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2680 /* Convert the return value to a Boolean */
2681 switch (op) {
2682 case Py_EQ:
2683 v = TEST_COND(result == 0);
2684 break;
2685 case Py_NE:
2686 v = TEST_COND(result != 0);
2687 break;
2688 case Py_LE:
2689 v = TEST_COND(result <= 0);
2690 break;
2691 case Py_GE:
2692 v = TEST_COND(result >= 0);
2693 break;
2694 case Py_LT:
2695 v = TEST_COND(result == -1);
2696 break;
2697 case Py_GT:
2698 v = TEST_COND(result == 1);
2699 break;
2700 default:
2701 PyErr_BadArgument();
2702 return NULL;
2703 }
2704 Py_INCREF(v);
2705 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002706}
2707
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002708static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002709long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002710{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002711 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 Py_ssize_t i;
2713 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 i = Py_SIZE(v);
2716 switch(i) {
2717 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2718 case 0: return 0;
2719 case 1: return v->ob_digit[0];
2720 }
2721 sign = 1;
2722 x = 0;
2723 if (i < 0) {
2724 sign = -1;
2725 i = -(i);
2726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002728 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2729 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2730 _PyHASH_MODULUS.
2731
2732 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2733 amounts to a rotation of the bits of x. To see this, write
2734
2735 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2736
2737 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2738 PyLong_SHIFT bits of x (those that are shifted out of the
2739 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2740 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2741 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2742 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2743 congruent to y modulo _PyHASH_MODULUS. So
2744
2745 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2746
2747 The right-hand side is just the result of rotating the
2748 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2749 not all _PyHASH_BITS bits of x are 1s, the same is true
2750 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2751 the reduction of x*2**PyLong_SHIFT modulo
2752 _PyHASH_MODULUS. */
2753 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2754 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002756 if (x >= _PyHASH_MODULUS)
2757 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 }
2759 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002760 if (x == (Py_uhash_t)-1)
2761 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002762 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002763}
2764
2765
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002766/* Add the absolute values of two long integers. */
2767
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002768static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002769x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2772 PyLongObject *z;
2773 Py_ssize_t i;
2774 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 /* Ensure a is the larger of the two: */
2777 if (size_a < size_b) {
2778 { PyLongObject *temp = a; a = b; b = temp; }
2779 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002780 size_a = size_b;
2781 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 }
2783 z = _PyLong_New(size_a+1);
2784 if (z == NULL)
2785 return NULL;
2786 for (i = 0; i < size_b; ++i) {
2787 carry += a->ob_digit[i] + b->ob_digit[i];
2788 z->ob_digit[i] = carry & PyLong_MASK;
2789 carry >>= PyLong_SHIFT;
2790 }
2791 for (; i < size_a; ++i) {
2792 carry += a->ob_digit[i];
2793 z->ob_digit[i] = carry & PyLong_MASK;
2794 carry >>= PyLong_SHIFT;
2795 }
2796 z->ob_digit[i] = carry;
2797 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002798}
2799
2800/* Subtract the absolute values of two integers. */
2801
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002802static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002803x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2806 PyLongObject *z;
2807 Py_ssize_t i;
2808 int sign = 1;
2809 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 /* Ensure a is the larger of the two: */
2812 if (size_a < size_b) {
2813 sign = -1;
2814 { PyLongObject *temp = a; a = b; b = temp; }
2815 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002816 size_a = size_b;
2817 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 }
2819 else if (size_a == size_b) {
2820 /* Find highest digit where a and b differ: */
2821 i = size_a;
2822 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2823 ;
2824 if (i < 0)
2825 return (PyLongObject *)PyLong_FromLong(0);
2826 if (a->ob_digit[i] < b->ob_digit[i]) {
2827 sign = -1;
2828 { PyLongObject *temp = a; a = b; b = temp; }
2829 }
2830 size_a = size_b = i+1;
2831 }
2832 z = _PyLong_New(size_a);
2833 if (z == NULL)
2834 return NULL;
2835 for (i = 0; i < size_b; ++i) {
2836 /* The following assumes unsigned arithmetic
2837 works module 2**N for some N>PyLong_SHIFT. */
2838 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2839 z->ob_digit[i] = borrow & PyLong_MASK;
2840 borrow >>= PyLong_SHIFT;
2841 borrow &= 1; /* Keep only one sign bit */
2842 }
2843 for (; i < size_a; ++i) {
2844 borrow = a->ob_digit[i] - borrow;
2845 z->ob_digit[i] = borrow & PyLong_MASK;
2846 borrow >>= PyLong_SHIFT;
2847 borrow &= 1; /* Keep only one sign bit */
2848 }
2849 assert(borrow == 0);
2850 if (sign < 0)
2851 NEGATE(z);
2852 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002853}
2854
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002855static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002856long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2863 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2864 MEDIUM_VALUE(b));
2865 return result;
2866 }
2867 if (Py_SIZE(a) < 0) {
2868 if (Py_SIZE(b) < 0) {
2869 z = x_add(a, b);
2870 if (z != NULL && Py_SIZE(z) != 0)
2871 Py_SIZE(z) = -(Py_SIZE(z));
2872 }
2873 else
2874 z = x_sub(b, a);
2875 }
2876 else {
2877 if (Py_SIZE(b) < 0)
2878 z = x_sub(a, b);
2879 else
2880 z = x_add(a, b);
2881 }
2882 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002883}
2884
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002885static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002886long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2893 PyObject* r;
2894 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2895 return r;
2896 }
2897 if (Py_SIZE(a) < 0) {
2898 if (Py_SIZE(b) < 0)
2899 z = x_sub(a, b);
2900 else
2901 z = x_add(a, b);
2902 if (z != NULL && Py_SIZE(z) != 0)
2903 Py_SIZE(z) = -(Py_SIZE(z));
2904 }
2905 else {
2906 if (Py_SIZE(b) < 0)
2907 z = x_add(a, b);
2908 else
2909 z = x_sub(a, b);
2910 }
2911 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002912}
2913
Tim Peters5af4e6c2002-08-12 02:31:19 +00002914/* Grade school multiplication, ignoring the signs.
2915 * Returns the absolute value of the product, or NULL if error.
2916 */
2917static PyLongObject *
2918x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 PyLongObject *z;
2921 Py_ssize_t size_a = ABS(Py_SIZE(a));
2922 Py_ssize_t size_b = ABS(Py_SIZE(b));
2923 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 z = _PyLong_New(size_a + size_b);
2926 if (z == NULL)
2927 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2930 if (a == b) {
2931 /* Efficient squaring per HAC, Algorithm 14.16:
2932 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2933 * Gives slightly less than a 2x speedup when a == b,
2934 * via exploiting that each entry in the multiplication
2935 * pyramid appears twice (except for the size_a squares).
2936 */
2937 for (i = 0; i < size_a; ++i) {
2938 twodigits carry;
2939 twodigits f = a->ob_digit[i];
2940 digit *pz = z->ob_digit + (i << 1);
2941 digit *pa = a->ob_digit + i + 1;
2942 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002945 Py_DECREF(z);
2946 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002947 });
Tim Peters0973b992004-08-29 22:16:50 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 carry = *pz + f * f;
2950 *pz++ = (digit)(carry & PyLong_MASK);
2951 carry >>= PyLong_SHIFT;
2952 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 /* Now f is added in twice in each column of the
2955 * pyramid it appears. Same as adding f<<1 once.
2956 */
2957 f <<= 1;
2958 while (pa < paend) {
2959 carry += *pz + *pa++ * f;
2960 *pz++ = (digit)(carry & PyLong_MASK);
2961 carry >>= PyLong_SHIFT;
2962 assert(carry <= (PyLong_MASK << 1));
2963 }
2964 if (carry) {
2965 carry += *pz;
2966 *pz++ = (digit)(carry & PyLong_MASK);
2967 carry >>= PyLong_SHIFT;
2968 }
2969 if (carry)
2970 *pz += (digit)(carry & PyLong_MASK);
2971 assert((carry >> PyLong_SHIFT) == 0);
2972 }
2973 }
2974 else { /* a is not the same as b -- gradeschool long mult */
2975 for (i = 0; i < size_a; ++i) {
2976 twodigits carry = 0;
2977 twodigits f = a->ob_digit[i];
2978 digit *pz = z->ob_digit + i;
2979 digit *pb = b->ob_digit;
2980 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002983 Py_DECREF(z);
2984 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002985 });
Tim Peters0973b992004-08-29 22:16:50 +00002986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 while (pb < pbend) {
2988 carry += *pz + *pb++ * f;
2989 *pz++ = (digit)(carry & PyLong_MASK);
2990 carry >>= PyLong_SHIFT;
2991 assert(carry <= PyLong_MASK);
2992 }
2993 if (carry)
2994 *pz += (digit)(carry & PyLong_MASK);
2995 assert((carry >> PyLong_SHIFT) == 0);
2996 }
2997 }
2998 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999}
3000
3001/* A helper for Karatsuba multiplication (k_mul).
3002 Takes a long "n" and an integer "size" representing the place to
3003 split, and sets low and high such that abs(n) == (high << size) + low,
3004 viewing the shift as being by digits. The sign bit is ignored, and
3005 the return values are >= 0.
3006 Returns 0 on success, -1 on failure.
3007*/
3008static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003009kmul_split(PyLongObject *n,
3010 Py_ssize_t size,
3011 PyLongObject **high,
3012 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 PyLongObject *hi, *lo;
3015 Py_ssize_t size_lo, size_hi;
3016 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 size_lo = MIN(size_n, size);
3019 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003021 if ((hi = _PyLong_New(size_hi)) == NULL)
3022 return -1;
3023 if ((lo = _PyLong_New(size_lo)) == NULL) {
3024 Py_DECREF(hi);
3025 return -1;
3026 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3029 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003031 *high = long_normalize(hi);
3032 *low = long_normalize(lo);
3033 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034}
3035
Tim Peters60004642002-08-12 22:01:34 +00003036static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3037
Tim Peters5af4e6c2002-08-12 02:31:19 +00003038/* Karatsuba multiplication. Ignores the input signs, and returns the
3039 * absolute value of the product (or NULL if error).
3040 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3041 */
3042static PyLongObject *
3043k_mul(PyLongObject *a, PyLongObject *b)
3044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 Py_ssize_t asize = ABS(Py_SIZE(a));
3046 Py_ssize_t bsize = ABS(Py_SIZE(b));
3047 PyLongObject *ah = NULL;
3048 PyLongObject *al = NULL;
3049 PyLongObject *bh = NULL;
3050 PyLongObject *bl = NULL;
3051 PyLongObject *ret = NULL;
3052 PyLongObject *t1, *t2, *t3;
3053 Py_ssize_t shift; /* the number of digits we split off */
3054 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3057 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3058 * Then the original product is
3059 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3060 * By picking X to be a power of 2, "*X" is just shifting, and it's
3061 * been reduced to 3 multiplies on numbers half the size.
3062 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 /* We want to split based on the larger number; fiddle so that b
3065 * is largest.
3066 */
3067 if (asize > bsize) {
3068 t1 = a;
3069 a = b;
3070 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 i = asize;
3073 asize = bsize;
3074 bsize = i;
3075 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 /* Use gradeschool math when either number is too small. */
3078 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3079 if (asize <= i) {
3080 if (asize == 0)
3081 return (PyLongObject *)PyLong_FromLong(0);
3082 else
3083 return x_mul(a, b);
3084 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 /* If a is small compared to b, splitting on b gives a degenerate
3087 * case with ah==0, and Karatsuba may be (even much) less efficient
3088 * than "grade school" then. However, we can still win, by viewing
3089 * b as a string of "big digits", each of width a->ob_size. That
3090 * leads to a sequence of balanced calls to k_mul.
3091 */
3092 if (2 * asize <= bsize)
3093 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 /* Split a & b into hi & lo pieces. */
3096 shift = bsize >> 1;
3097 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3098 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 if (a == b) {
3101 bh = ah;
3102 bl = al;
3103 Py_INCREF(bh);
3104 Py_INCREF(bl);
3105 }
3106 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 /* The plan:
3109 * 1. Allocate result space (asize + bsize digits: that's always
3110 * enough).
3111 * 2. Compute ah*bh, and copy into result at 2*shift.
3112 * 3. Compute al*bl, and copy into result at 0. Note that this
3113 * can't overlap with #2.
3114 * 4. Subtract al*bl from the result, starting at shift. This may
3115 * underflow (borrow out of the high digit), but we don't care:
3116 * we're effectively doing unsigned arithmetic mod
3117 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3118 * borrows and carries out of the high digit can be ignored.
3119 * 5. Subtract ah*bh from the result, starting at shift.
3120 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3121 * at shift.
3122 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 /* 1. Allocate result space. */
3125 ret = _PyLong_New(asize + bsize);
3126 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003127#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 /* Fill with trash, to catch reference to uninitialized digits. */
3129 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003130#endif
Tim Peters44121a62002-08-12 06:17:58 +00003131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3133 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3134 assert(Py_SIZE(t1) >= 0);
3135 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3136 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3137 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 /* Zero-out the digits higher than the ah*bh copy. */
3140 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3141 if (i)
3142 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3143 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 /* 3. t2 <- al*bl, and copy into the low digits. */
3146 if ((t2 = k_mul(al, bl)) == NULL) {
3147 Py_DECREF(t1);
3148 goto fail;
3149 }
3150 assert(Py_SIZE(t2) >= 0);
3151 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3152 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 /* Zero out remaining digits. */
3155 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3156 if (i)
3157 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3160 * because it's fresher in cache.
3161 */
3162 i = Py_SIZE(ret) - shift; /* # digits after shift */
3163 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3164 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3167 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3170 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3171 Py_DECREF(ah);
3172 Py_DECREF(al);
3173 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 if (a == b) {
3176 t2 = t1;
3177 Py_INCREF(t2);
3178 }
3179 else if ((t2 = x_add(bh, bl)) == NULL) {
3180 Py_DECREF(t1);
3181 goto fail;
3182 }
3183 Py_DECREF(bh);
3184 Py_DECREF(bl);
3185 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 t3 = k_mul(t1, t2);
3188 Py_DECREF(t1);
3189 Py_DECREF(t2);
3190 if (t3 == NULL) goto fail;
3191 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* Add t3. It's not obvious why we can't run out of room here.
3194 * See the (*) comment after this function.
3195 */
3196 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3197 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003200
Mark Dickinson22b20182010-05-10 21:27:53 +00003201 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 Py_XDECREF(ret);
3203 Py_XDECREF(ah);
3204 Py_XDECREF(al);
3205 Py_XDECREF(bh);
3206 Py_XDECREF(bl);
3207 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003208}
3209
Tim Petersd6974a52002-08-13 20:37:51 +00003210/* (*) Why adding t3 can't "run out of room" above.
3211
Tim Petersab86c2b2002-08-15 20:06:00 +00003212Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3213to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003214
Tim Petersab86c2b2002-08-15 20:06:00 +000032151. For any integer i, i = c(i/2) + f(i/2). In particular,
3216 bsize = c(bsize/2) + f(bsize/2).
32172. shift = f(bsize/2)
32183. asize <= bsize
32194. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3220 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003221
Tim Petersab86c2b2002-08-15 20:06:00 +00003222We allocated asize + bsize result digits, and add t3 into them at an offset
3223of shift. This leaves asize+bsize-shift allocated digit positions for t3
3224to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3225asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003226
Tim Petersab86c2b2002-08-15 20:06:00 +00003227bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3228at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003229
Tim Petersab86c2b2002-08-15 20:06:00 +00003230If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3231digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3232most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003233
Tim Petersab86c2b2002-08-15 20:06:00 +00003234The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003235
Tim Petersab86c2b2002-08-15 20:06:00 +00003236 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003237
Tim Petersab86c2b2002-08-15 20:06:00 +00003238and we have asize + c(bsize/2) available digit positions. We need to show
3239this is always enough. An instance of c(bsize/2) cancels out in both, so
3240the question reduces to whether asize digits is enough to hold
3241(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3242then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3243asize 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 +00003244digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003245asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003246c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3247is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3248bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003249
Tim Peters48d52c02002-08-14 17:07:32 +00003250Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3251clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3252ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003253*/
3254
Tim Peters60004642002-08-12 22:01:34 +00003255/* b has at least twice the digits of a, and a is big enough that Karatsuba
3256 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3257 * of slices, each with a->ob_size digits, and multiply the slices by a,
3258 * one at a time. This gives k_mul balanced inputs to work with, and is
3259 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003260 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003261 * single-width slice overlap between successive partial sums).
3262 */
3263static PyLongObject *
3264k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 const Py_ssize_t asize = ABS(Py_SIZE(a));
3267 Py_ssize_t bsize = ABS(Py_SIZE(b));
3268 Py_ssize_t nbdone; /* # of b digits already multiplied */
3269 PyLongObject *ret;
3270 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 assert(asize > KARATSUBA_CUTOFF);
3273 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 /* Allocate result space, and zero it out. */
3276 ret = _PyLong_New(asize + bsize);
3277 if (ret == NULL)
3278 return NULL;
3279 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* Successive slices of b are copied into bslice. */
3282 bslice = _PyLong_New(asize);
3283 if (bslice == NULL)
3284 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 nbdone = 0;
3287 while (bsize > 0) {
3288 PyLongObject *product;
3289 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 /* Multiply the next slice of b by a. */
3292 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3293 nbtouse * sizeof(digit));
3294 Py_SIZE(bslice) = nbtouse;
3295 product = k_mul(a, bslice);
3296 if (product == NULL)
3297 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 /* Add into result. */
3300 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3301 product->ob_digit, Py_SIZE(product));
3302 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 bsize -= nbtouse;
3305 nbdone += nbtouse;
3306 }
Tim Peters60004642002-08-12 22:01:34 +00003307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 Py_DECREF(bslice);
3309 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003310
Mark Dickinson22b20182010-05-10 21:27:53 +00003311 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 Py_DECREF(ret);
3313 Py_XDECREF(bslice);
3314 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003315}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003316
3317static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003318long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 /* fast path for single-digit multiplication */
3325 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3326 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003327#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003329#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003330 /* if we don't have long long then we're almost certainly
3331 using 15-bit digits, so v will fit in a long. In the
3332 unlikely event that we're using 30-bit digits on a platform
3333 without long long, a large v will just cause us to fall
3334 through to the general multiplication code below. */
3335 if (v >= LONG_MIN && v <= LONG_MAX)
3336 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003337#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 z = k_mul(a, b);
3341 /* Negate if exactly one of the inputs is negative. */
3342 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3343 NEGATE(z);
3344 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003345}
3346
Guido van Rossume32e0141992-01-19 16:31:05 +00003347/* The / and % operators are now defined in terms of divmod().
3348 The expression a mod b has the value a - b*floor(a/b).
3349 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003350 |a| by |b|, with the sign of a. This is also expressed
3351 as a - b*trunc(a/b), if trunc truncates towards zero.
3352 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 a b a rem b a mod b
3354 13 10 3 3
3355 -13 10 -3 7
3356 13 -10 3 -7
3357 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003358 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003359 have different signs. We then subtract one from the 'div'
3360 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003361
Tim Peters47e52ee2004-08-30 02:44:38 +00003362/* Compute
3363 * *pdiv, *pmod = divmod(v, w)
3364 * NULL can be passed for pdiv or pmod, in which case that part of
3365 * the result is simply thrown away. The caller owns a reference to
3366 * each of these it requests (does not pass NULL for).
3367 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003368static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003369l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 if (long_divrem(v, w, &div, &mod) < 0)
3375 return -1;
3376 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3377 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3378 PyLongObject *temp;
3379 PyLongObject *one;
3380 temp = (PyLongObject *) long_add(mod, w);
3381 Py_DECREF(mod);
3382 mod = temp;
3383 if (mod == NULL) {
3384 Py_DECREF(div);
3385 return -1;
3386 }
3387 one = (PyLongObject *) PyLong_FromLong(1L);
3388 if (one == NULL ||
3389 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3390 Py_DECREF(mod);
3391 Py_DECREF(div);
3392 Py_XDECREF(one);
3393 return -1;
3394 }
3395 Py_DECREF(one);
3396 Py_DECREF(div);
3397 div = temp;
3398 }
3399 if (pdiv != NULL)
3400 *pdiv = div;
3401 else
3402 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 if (pmod != NULL)
3405 *pmod = mod;
3406 else
3407 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003410}
3411
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003412static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003413long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 CHECK_BINOP(a, b);
3418 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3419 div = NULL;
3420 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003421}
3422
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003423/* PyLong/PyLong -> float, with correctly rounded result. */
3424
3425#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3426#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3427
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003428static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003429long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 PyLongObject *a, *b, *x;
3432 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3433 digit mask, low;
3434 int inexact, negate, a_is_small, b_is_small;
3435 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 CHECK_BINOP(v, w);
3438 a = (PyLongObject *)v;
3439 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 /*
3442 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3445 1. choose a suitable integer 'shift'
3446 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3447 3. adjust x for correct rounding
3448 4. convert x to a double dx with the same value
3449 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3454 returns either 0.0 or -0.0, depending on the sign of b. For a and
3455 b both nonzero, ignore signs of a and b, and add the sign back in
3456 at the end. Now write a_bits and b_bits for the bit lengths of a
3457 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3458 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3463 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3464 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3465 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003469 1. The integer 'shift' is chosen so that x has the right number of
3470 bits for a double, plus two or three extra bits that will be used
3471 in the rounding decisions. Writing a_bits and b_bits for the
3472 number of significant bits in a and b respectively, a
3473 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003477 This is fine in the usual case, but if a/b is smaller than the
3478 smallest normal float then it can lead to double rounding on an
3479 IEEE 754 platform, giving incorrectly rounded results. So we
3480 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 2. The quantity x is computed by first shifting a (left -shift bits
3485 if shift <= 0, right shift bits if shift > 0) and then dividing by
3486 b. For both the shift and the division, we keep track of whether
3487 the result is inexact, in a flag 'inexact'; this information is
3488 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 With the choice of shift above, together with our assumption that
3491 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3492 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3495 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003499 For float representability, we need x/2**extra_bits <
3500 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3501 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 To round, we just modify the bottom digit of x in-place; this can
3506 end up giving a digit with value > PyLONG_MASK, but that's not a
3507 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 With the original choices for shift above, extra_bits will always
3510 be 2 or 3. Then rounding under the round-half-to-even rule, we
3511 round up iff the most significant of the extra bits is 1, and
3512 either: (a) the computation of x in step 2 had an inexact result,
3513 or (b) at least one other of the extra bits is 1, or (c) the least
3514 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 4. Conversion to a double is straightforward; all floating-point
3517 operations involved in the conversion are exact, so there's no
3518 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3521 The result will always be exactly representable as a double, except
3522 in the case that it overflows. To avoid dependence on the exact
3523 behaviour of ldexp on overflow, we check for overflow before
3524 applying ldexp. The result of ldexp is adjusted for sign before
3525 returning.
3526 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /* Reduce to case where a and b are both positive. */
3529 a_size = ABS(Py_SIZE(a));
3530 b_size = ABS(Py_SIZE(b));
3531 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3532 if (b_size == 0) {
3533 PyErr_SetString(PyExc_ZeroDivisionError,
3534 "division by zero");
3535 goto error;
3536 }
3537 if (a_size == 0)
3538 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 /* Fast path for a and b small (exactly representable in a double).
3541 Relies on floating-point division being correctly rounded; results
3542 may be subject to double rounding on x86 machines that operate with
3543 the x87 FPU set to 64-bit precision. */
3544 a_is_small = a_size <= MANT_DIG_DIGITS ||
3545 (a_size == MANT_DIG_DIGITS+1 &&
3546 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3547 b_is_small = b_size <= MANT_DIG_DIGITS ||
3548 (b_size == MANT_DIG_DIGITS+1 &&
3549 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3550 if (a_is_small && b_is_small) {
3551 double da, db;
3552 da = a->ob_digit[--a_size];
3553 while (a_size > 0)
3554 da = da * PyLong_BASE + a->ob_digit[--a_size];
3555 db = b->ob_digit[--b_size];
3556 while (b_size > 0)
3557 db = db * PyLong_BASE + b->ob_digit[--b_size];
3558 result = da / db;
3559 goto success;
3560 }
Tim Peterse2a60002001-09-04 06:17:36 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 /* Catch obvious cases of underflow and overflow */
3563 diff = a_size - b_size;
3564 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3565 /* Extreme overflow */
3566 goto overflow;
3567 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3568 /* Extreme underflow */
3569 goto underflow_or_zero;
3570 /* Next line is now safe from overflowing a Py_ssize_t */
3571 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3572 bits_in_digit(b->ob_digit[b_size - 1]);
3573 /* Now diff = a_bits - b_bits. */
3574 if (diff > DBL_MAX_EXP)
3575 goto overflow;
3576 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3577 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 /* Choose value for shift; see comments for step 1 above. */
3580 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 /* x = abs(a * 2**-shift) */
3585 if (shift <= 0) {
3586 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3587 digit rem;
3588 /* x = a << -shift */
3589 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3590 /* In practice, it's probably impossible to end up
3591 here. Both a and b would have to be enormous,
3592 using close to SIZE_T_MAX bytes of memory each. */
3593 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003594 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 goto error;
3596 }
3597 x = _PyLong_New(a_size + shift_digits + 1);
3598 if (x == NULL)
3599 goto error;
3600 for (i = 0; i < shift_digits; i++)
3601 x->ob_digit[i] = 0;
3602 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3603 a_size, -shift % PyLong_SHIFT);
3604 x->ob_digit[a_size + shift_digits] = rem;
3605 }
3606 else {
3607 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3608 digit rem;
3609 /* x = a >> shift */
3610 assert(a_size >= shift_digits);
3611 x = _PyLong_New(a_size - shift_digits);
3612 if (x == NULL)
3613 goto error;
3614 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3615 a_size - shift_digits, shift % PyLong_SHIFT);
3616 /* set inexact if any of the bits shifted out is nonzero */
3617 if (rem)
3618 inexact = 1;
3619 while (!inexact && shift_digits > 0)
3620 if (a->ob_digit[--shift_digits])
3621 inexact = 1;
3622 }
3623 long_normalize(x);
3624 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3627 reference to x, so it's safe to modify it in-place. */
3628 if (b_size == 1) {
3629 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3630 b->ob_digit[0]);
3631 long_normalize(x);
3632 if (rem)
3633 inexact = 1;
3634 }
3635 else {
3636 PyLongObject *div, *rem;
3637 div = x_divrem(x, b, &rem);
3638 Py_DECREF(x);
3639 x = div;
3640 if (x == NULL)
3641 goto error;
3642 if (Py_SIZE(rem))
3643 inexact = 1;
3644 Py_DECREF(rem);
3645 }
3646 x_size = ABS(Py_SIZE(x));
3647 assert(x_size > 0); /* result of division is never zero */
3648 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 /* The number of extra bits that have to be rounded away. */
3651 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3652 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 /* Round by directly modifying the low digit of x. */
3655 mask = (digit)1 << (extra_bits - 1);
3656 low = x->ob_digit[0] | inexact;
3657 if (low & mask && low & (3*mask-1))
3658 low += mask;
3659 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003661 /* Convert x to a double dx; the conversion is exact. */
3662 dx = x->ob_digit[--x_size];
3663 while (x_size > 0)
3664 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3665 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 /* Check whether ldexp result will overflow a double. */
3668 if (shift + x_bits >= DBL_MAX_EXP &&
3669 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3670 goto overflow;
3671 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003672
3673 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003675
3676 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003678
3679 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 PyErr_SetString(PyExc_OverflowError,
3681 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003682 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003684}
3685
3686static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003687long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003689 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 CHECK_BINOP(a, b);
3692
3693 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3694 mod = NULL;
3695 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003696}
3697
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003698static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003699long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003701 PyLongObject *div, *mod;
3702 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003706 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3707 return NULL;
3708 }
3709 z = PyTuple_New(2);
3710 if (z != NULL) {
3711 PyTuple_SetItem(z, 0, (PyObject *) div);
3712 PyTuple_SetItem(z, 1, (PyObject *) mod);
3713 }
3714 else {
3715 Py_DECREF(div);
3716 Py_DECREF(mod);
3717 }
3718 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003719}
3720
Tim Peters47e52ee2004-08-30 02:44:38 +00003721/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003722static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003723long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3726 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 PyLongObject *z = NULL; /* accumulated result */
3729 Py_ssize_t i, j, k; /* counters */
3730 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 /* 5-ary values. If the exponent is large enough, table is
3733 * precomputed so that table[i] == a**i % c for i in range(32).
3734 */
3735 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3736 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 /* a, b, c = v, w, x */
3739 CHECK_BINOP(v, w);
3740 a = (PyLongObject*)v; Py_INCREF(a);
3741 b = (PyLongObject*)w; Py_INCREF(b);
3742 if (PyLong_Check(x)) {
3743 c = (PyLongObject *)x;
3744 Py_INCREF(x);
3745 }
3746 else if (x == Py_None)
3747 c = NULL;
3748 else {
3749 Py_DECREF(a);
3750 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003751 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 }
Tim Peters4c483c42001-09-05 06:24:58 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3755 if (c) {
3756 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003757 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 goto Error;
3759 }
3760 else {
3761 /* else return a float. This works because we know
3762 that this calls float_pow() which converts its
3763 arguments to double. */
3764 Py_DECREF(a);
3765 Py_DECREF(b);
3766 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3767 }
3768 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 if (c) {
3771 /* if modulus == 0:
3772 raise ValueError() */
3773 if (Py_SIZE(c) == 0) {
3774 PyErr_SetString(PyExc_ValueError,
3775 "pow() 3rd argument cannot be 0");
3776 goto Error;
3777 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 /* if modulus < 0:
3780 negativeOutput = True
3781 modulus = -modulus */
3782 if (Py_SIZE(c) < 0) {
3783 negativeOutput = 1;
3784 temp = (PyLongObject *)_PyLong_Copy(c);
3785 if (temp == NULL)
3786 goto Error;
3787 Py_DECREF(c);
3788 c = temp;
3789 temp = NULL;
3790 NEGATE(c);
3791 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 /* if modulus == 1:
3794 return 0 */
3795 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3796 z = (PyLongObject *)PyLong_FromLong(0L);
3797 goto Done;
3798 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 /* if base < 0:
3801 base = base % modulus
3802 Having the base positive just makes things easier. */
3803 if (Py_SIZE(a) < 0) {
3804 if (l_divmod(a, c, NULL, &temp) < 0)
3805 goto Error;
3806 Py_DECREF(a);
3807 a = temp;
3808 temp = NULL;
3809 }
3810 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 /* At this point a, b, and c are guaranteed non-negative UNLESS
3813 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 z = (PyLongObject *)PyLong_FromLong(1L);
3816 if (z == NULL)
3817 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 /* Perform a modular reduction, X = X % c, but leave X alone if c
3820 * is NULL.
3821 */
3822#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003823 do { \
3824 if (c != NULL) { \
3825 if (l_divmod(X, c, NULL, &temp) < 0) \
3826 goto Error; \
3827 Py_XDECREF(X); \
3828 X = temp; \
3829 temp = NULL; \
3830 } \
3831 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 /* Multiply two values, then reduce the result:
3834 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003835#define MULT(X, Y, result) \
3836 do { \
3837 temp = (PyLongObject *)long_mul(X, Y); \
3838 if (temp == NULL) \
3839 goto Error; \
3840 Py_XDECREF(result); \
3841 result = temp; \
3842 temp = NULL; \
3843 REDUCE(result); \
3844 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3847 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3848 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3849 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3850 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003852 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003853 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003854 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003855 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 }
3857 }
3858 }
3859 else {
3860 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3861 Py_INCREF(z); /* still holds 1L */
3862 table[0] = z;
3863 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003864 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3867 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003869 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3870 const int index = (bi >> j) & 0x1f;
3871 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003872 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003873 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003874 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003875 }
3876 }
3877 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 if (negativeOutput && (Py_SIZE(z) != 0)) {
3880 temp = (PyLongObject *)long_sub(z, c);
3881 if (temp == NULL)
3882 goto Error;
3883 Py_DECREF(z);
3884 z = temp;
3885 temp = NULL;
3886 }
3887 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003888
Mark Dickinson22b20182010-05-10 21:27:53 +00003889 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 if (z != NULL) {
3891 Py_DECREF(z);
3892 z = NULL;
3893 }
3894 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003895 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3897 for (i = 0; i < 32; ++i)
3898 Py_XDECREF(table[i]);
3899 }
3900 Py_DECREF(a);
3901 Py_DECREF(b);
3902 Py_XDECREF(c);
3903 Py_XDECREF(temp);
3904 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003905}
3906
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003907static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003908long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 /* Implement ~x as -(x+1) */
3911 PyLongObject *x;
3912 PyLongObject *w;
3913 if (ABS(Py_SIZE(v)) <=1)
3914 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3915 w = (PyLongObject *)PyLong_FromLong(1L);
3916 if (w == NULL)
3917 return NULL;
3918 x = (PyLongObject *) long_add(v, w);
3919 Py_DECREF(w);
3920 if (x == NULL)
3921 return NULL;
3922 Py_SIZE(x) = -(Py_SIZE(x));
3923 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003924}
3925
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003926static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003927long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 PyLongObject *z;
3930 if (ABS(Py_SIZE(v)) <= 1)
3931 return PyLong_FromLong(-MEDIUM_VALUE(v));
3932 z = (PyLongObject *)_PyLong_Copy(v);
3933 if (z != NULL)
3934 Py_SIZE(z) = -(Py_SIZE(v));
3935 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003936}
3937
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003938static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003939long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 if (Py_SIZE(v) < 0)
3942 return long_neg(v);
3943 else
3944 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003945}
3946
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003947static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003948long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003951}
3952
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003953static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003954long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 PyLongObject *z = NULL;
3957 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3958 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 if (Py_SIZE(a) < 0) {
3963 /* Right shifting negative numbers is harder */
3964 PyLongObject *a1, *a2;
3965 a1 = (PyLongObject *) long_invert(a);
3966 if (a1 == NULL)
3967 goto rshift_error;
3968 a2 = (PyLongObject *) long_rshift(a1, b);
3969 Py_DECREF(a1);
3970 if (a2 == NULL)
3971 goto rshift_error;
3972 z = (PyLongObject *) long_invert(a2);
3973 Py_DECREF(a2);
3974 }
3975 else {
3976 shiftby = PyLong_AsSsize_t((PyObject *)b);
3977 if (shiftby == -1L && PyErr_Occurred())
3978 goto rshift_error;
3979 if (shiftby < 0) {
3980 PyErr_SetString(PyExc_ValueError,
3981 "negative shift count");
3982 goto rshift_error;
3983 }
3984 wordshift = shiftby / PyLong_SHIFT;
3985 newsize = ABS(Py_SIZE(a)) - wordshift;
3986 if (newsize <= 0)
3987 return PyLong_FromLong(0);
3988 loshift = shiftby % PyLong_SHIFT;
3989 hishift = PyLong_SHIFT - loshift;
3990 lomask = ((digit)1 << hishift) - 1;
3991 himask = PyLong_MASK ^ lomask;
3992 z = _PyLong_New(newsize);
3993 if (z == NULL)
3994 goto rshift_error;
3995 if (Py_SIZE(a) < 0)
3996 Py_SIZE(z) = -(Py_SIZE(z));
3997 for (i = 0, j = wordshift; i < newsize; i++, j++) {
3998 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
3999 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004000 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 }
4002 z = long_normalize(z);
4003 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004004 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004005 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004006
Guido van Rossumc6913e71991-11-19 20:26:46 +00004007}
4008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004009static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004010long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004012 /* This version due to Tim Peters */
4013 PyLongObject *a = (PyLongObject*)v;
4014 PyLongObject *b = (PyLongObject*)w;
4015 PyLongObject *z = NULL;
4016 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4017 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 shiftby = PyLong_AsSsize_t((PyObject *)b);
4022 if (shiftby == -1L && PyErr_Occurred())
4023 goto lshift_error;
4024 if (shiftby < 0) {
4025 PyErr_SetString(PyExc_ValueError, "negative shift count");
4026 goto lshift_error;
4027 }
4028 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4029 wordshift = shiftby / PyLong_SHIFT;
4030 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 oldsize = ABS(Py_SIZE(a));
4033 newsize = oldsize + wordshift;
4034 if (remshift)
4035 ++newsize;
4036 z = _PyLong_New(newsize);
4037 if (z == NULL)
4038 goto lshift_error;
4039 if (Py_SIZE(a) < 0)
4040 NEGATE(z);
4041 for (i = 0; i < wordshift; i++)
4042 z->ob_digit[i] = 0;
4043 accum = 0;
4044 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4045 accum |= (twodigits)a->ob_digit[j] << remshift;
4046 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4047 accum >>= PyLong_SHIFT;
4048 }
4049 if (remshift)
4050 z->ob_digit[newsize-1] = (digit)accum;
4051 else
4052 assert(!accum);
4053 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004054 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004056}
4057
Mark Dickinson27a87a22009-10-25 20:43:34 +00004058/* Compute two's complement of digit vector a[0:m], writing result to
4059 z[0:m]. The digit vector a need not be normalized, but should not
4060 be entirely zero. a and z may point to the same digit vector. */
4061
4062static void
4063v_complement(digit *z, digit *a, Py_ssize_t m)
4064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004065 Py_ssize_t i;
4066 digit carry = 1;
4067 for (i = 0; i < m; ++i) {
4068 carry += a[i] ^ PyLong_MASK;
4069 z[i] = carry & PyLong_MASK;
4070 carry >>= PyLong_SHIFT;
4071 }
4072 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004073}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004074
4075/* Bitwise and/xor/or operations */
4076
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004077static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004078long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004080 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 int nega, negb, negz;
4083 Py_ssize_t size_a, size_b, size_z, i;
4084 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 /* Bitwise operations for negative numbers operate as though
4087 on a two's complement representation. So convert arguments
4088 from sign-magnitude to two's complement, and convert the
4089 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004091 /* If a is negative, replace it by its two's complement. */
4092 size_a = ABS(Py_SIZE(a));
4093 nega = Py_SIZE(a) < 0;
4094 if (nega) {
4095 z = _PyLong_New(size_a);
4096 if (z == NULL)
4097 return NULL;
4098 v_complement(z->ob_digit, a->ob_digit, size_a);
4099 a = z;
4100 }
4101 else
4102 /* Keep reference count consistent. */
4103 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 /* Same for b. */
4106 size_b = ABS(Py_SIZE(b));
4107 negb = Py_SIZE(b) < 0;
4108 if (negb) {
4109 z = _PyLong_New(size_b);
4110 if (z == NULL) {
4111 Py_DECREF(a);
4112 return NULL;
4113 }
4114 v_complement(z->ob_digit, b->ob_digit, size_b);
4115 b = z;
4116 }
4117 else
4118 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 /* Swap a and b if necessary to ensure size_a >= size_b. */
4121 if (size_a < size_b) {
4122 z = a; a = b; b = z;
4123 size_z = size_a; size_a = size_b; size_b = size_z;
4124 negz = nega; nega = negb; negb = negz;
4125 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004127 /* JRH: The original logic here was to allocate the result value (z)
4128 as the longer of the two operands. However, there are some cases
4129 where the result is guaranteed to be shorter than that: AND of two
4130 positives, OR of two negatives: use the shorter number. AND with
4131 mixed signs: use the positive number. OR with mixed signs: use the
4132 negative number.
4133 */
4134 switch (op) {
4135 case '^':
4136 negz = nega ^ negb;
4137 size_z = size_a;
4138 break;
4139 case '&':
4140 negz = nega & negb;
4141 size_z = negb ? size_a : size_b;
4142 break;
4143 case '|':
4144 negz = nega | negb;
4145 size_z = negb ? size_b : size_a;
4146 break;
4147 default:
4148 PyErr_BadArgument();
4149 return NULL;
4150 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004152 /* We allow an extra digit if z is negative, to make sure that
4153 the final two's complement of z doesn't overflow. */
4154 z = _PyLong_New(size_z + negz);
4155 if (z == NULL) {
4156 Py_DECREF(a);
4157 Py_DECREF(b);
4158 return NULL;
4159 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* Compute digits for overlap of a and b. */
4162 switch(op) {
4163 case '&':
4164 for (i = 0; i < size_b; ++i)
4165 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4166 break;
4167 case '|':
4168 for (i = 0; i < size_b; ++i)
4169 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4170 break;
4171 case '^':
4172 for (i = 0; i < size_b; ++i)
4173 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4174 break;
4175 default:
4176 PyErr_BadArgument();
4177 return NULL;
4178 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 /* Copy any remaining digits of a, inverting if necessary. */
4181 if (op == '^' && negb)
4182 for (; i < size_z; ++i)
4183 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4184 else if (i < size_z)
4185 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4186 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 /* Complement result if negative. */
4189 if (negz) {
4190 Py_SIZE(z) = -(Py_SIZE(z));
4191 z->ob_digit[size_z] = PyLong_MASK;
4192 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4193 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 Py_DECREF(a);
4196 Py_DECREF(b);
4197 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004198}
4199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004200static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004201long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004203 PyObject *c;
4204 CHECK_BINOP(a, b);
4205 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4206 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004207}
4208
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004209static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004210long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 PyObject *c;
4213 CHECK_BINOP(a, b);
4214 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4215 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004216}
4217
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004218static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004219long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 PyObject *c;
4222 CHECK_BINOP(a, b);
4223 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4224 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004225}
4226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004227static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004228long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004230 if (PyLong_CheckExact(v))
4231 Py_INCREF(v);
4232 else
4233 v = _PyLong_Copy((PyLongObject *)v);
4234 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004235}
4236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004237static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004238long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004240 double result;
4241 result = PyLong_AsDouble(v);
4242 if (result == -1.0 && PyErr_Occurred())
4243 return NULL;
4244 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004245}
4246
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004247static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004248long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004249
Tim Peters6d6c1a32001-08-02 04:15:00 +00004250static PyObject *
4251long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4252{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004253 PyObject *obase = NULL, *x = NULL;
4254 long base;
4255 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004256 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004258 if (type != &PyLong_Type)
4259 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004260 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4261 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004262 return NULL;
4263 if (x == NULL)
4264 return PyLong_FromLong(0L);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004265 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004266 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004267
4268 base = PyLong_AsLongAndOverflow(obase, &overflow);
4269 if (base == -1 && PyErr_Occurred())
4270 return NULL;
4271 if (overflow || (base != 0 && base < 2) || base > 36) {
4272 PyErr_SetString(PyExc_ValueError,
4273 "int() arg 2 must be >= 2 and <= 36");
4274 return NULL;
4275 }
4276
4277 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004278 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4280 /* Since PyLong_FromString doesn't have a length parameter,
4281 * check here for possible NULs in the string. */
4282 char *string;
4283 Py_ssize_t size = Py_SIZE(x);
4284 if (PyByteArray_Check(x))
4285 string = PyByteArray_AS_STRING(x);
4286 else
4287 string = PyBytes_AS_STRING(x);
4288 if (strlen(string) != (size_t)size) {
4289 /* We only see this if there's a null byte in x,
4290 x is a bytes or buffer, *and* a base is given. */
4291 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004292 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004293 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004294 return NULL;
4295 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004296 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 }
4298 else {
4299 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004300 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004301 return NULL;
4302 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004303}
4304
Guido van Rossumbef14172001-08-29 15:47:46 +00004305/* Wimpy, slow approach to tp_new calls for subtypes of long:
4306 first create a regular long from whatever arguments we got,
4307 then allocate a subtype instance and initialize it from
4308 the regular long. The regular long is then thrown away.
4309*/
4310static PyObject *
4311long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 PyLongObject *tmp, *newobj;
4314 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 assert(PyType_IsSubtype(type, &PyLong_Type));
4317 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4318 if (tmp == NULL)
4319 return NULL;
4320 assert(PyLong_CheckExact(tmp));
4321 n = Py_SIZE(tmp);
4322 if (n < 0)
4323 n = -n;
4324 newobj = (PyLongObject *)type->tp_alloc(type, n);
4325 if (newobj == NULL) {
4326 Py_DECREF(tmp);
4327 return NULL;
4328 }
4329 assert(PyLong_Check(newobj));
4330 Py_SIZE(newobj) = Py_SIZE(tmp);
4331 for (i = 0; i < n; i++)
4332 newobj->ob_digit[i] = tmp->ob_digit[i];
4333 Py_DECREF(tmp);
4334 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004335}
4336
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004337static PyObject *
4338long_getnewargs(PyLongObject *v)
4339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004341}
4342
Guido van Rossumb43daf72007-08-01 18:08:08 +00004343static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004344long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004346}
4347
4348static PyObject *
4349long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004351}
4352
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004353static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004354long__format__(PyObject *self, PyObject *args)
4355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004357 _PyUnicodeWriter writer;
4358 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4361 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004362
4363 _PyUnicodeWriter_Init(&writer, 0);
4364 ret = _PyLong_FormatAdvancedWriter(
4365 &writer,
4366 self,
4367 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4368 if (ret == -1) {
4369 _PyUnicodeWriter_Dealloc(&writer);
4370 return NULL;
4371 }
4372 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004373}
4374
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004375/* Return a pair (q, r) such that a = b * q + r, and
4376 abs(r) <= abs(b)/2, with equality possible only if q is even.
4377 In other words, q == a / b, rounded to the nearest integer using
4378 round-half-to-even. */
4379
4380PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004381_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004382{
4383 PyLongObject *quo = NULL, *rem = NULL;
4384 PyObject *one = NULL, *twice_rem, *result, *temp;
4385 int cmp, quo_is_odd, quo_is_neg;
4386
4387 /* Equivalent Python code:
4388
4389 def divmod_near(a, b):
4390 q, r = divmod(a, b)
4391 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4392 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4393 # positive, 2 * r < b if b negative.
4394 greater_than_half = 2*r > b if b > 0 else 2*r < b
4395 exactly_half = 2*r == b
4396 if greater_than_half or exactly_half and q % 2 == 1:
4397 q += 1
4398 r -= b
4399 return q, r
4400
4401 */
4402 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4403 PyErr_SetString(PyExc_TypeError,
4404 "non-integer arguments in division");
4405 return NULL;
4406 }
4407
4408 /* Do a and b have different signs? If so, quotient is negative. */
4409 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4410
4411 one = PyLong_FromLong(1L);
4412 if (one == NULL)
4413 return NULL;
4414
4415 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4416 goto error;
4417
4418 /* compare twice the remainder with the divisor, to see
4419 if we need to adjust the quotient and remainder */
4420 twice_rem = long_lshift((PyObject *)rem, one);
4421 if (twice_rem == NULL)
4422 goto error;
4423 if (quo_is_neg) {
4424 temp = long_neg((PyLongObject*)twice_rem);
4425 Py_DECREF(twice_rem);
4426 twice_rem = temp;
4427 if (twice_rem == NULL)
4428 goto error;
4429 }
4430 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4431 Py_DECREF(twice_rem);
4432
4433 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4434 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4435 /* fix up quotient */
4436 if (quo_is_neg)
4437 temp = long_sub(quo, (PyLongObject *)one);
4438 else
4439 temp = long_add(quo, (PyLongObject *)one);
4440 Py_DECREF(quo);
4441 quo = (PyLongObject *)temp;
4442 if (quo == NULL)
4443 goto error;
4444 /* and remainder */
4445 if (quo_is_neg)
4446 temp = long_add(rem, (PyLongObject *)b);
4447 else
4448 temp = long_sub(rem, (PyLongObject *)b);
4449 Py_DECREF(rem);
4450 rem = (PyLongObject *)temp;
4451 if (rem == NULL)
4452 goto error;
4453 }
4454
4455 result = PyTuple_New(2);
4456 if (result == NULL)
4457 goto error;
4458
4459 /* PyTuple_SET_ITEM steals references */
4460 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4461 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4462 Py_DECREF(one);
4463 return result;
4464
4465 error:
4466 Py_XDECREF(quo);
4467 Py_XDECREF(rem);
4468 Py_XDECREF(one);
4469 return NULL;
4470}
4471
Eric Smith8c663262007-08-25 02:26:07 +00004472static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004473long_round(PyObject *self, PyObject *args)
4474{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004475 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004476
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004477 /* To round an integer m to the nearest 10**n (n positive), we make use of
4478 * the divmod_near operation, defined by:
4479 *
4480 * divmod_near(a, b) = (q, r)
4481 *
4482 * where q is the nearest integer to the quotient a / b (the
4483 * nearest even integer in the case of a tie) and r == a - q * b.
4484 * Hence q * b = a - r is the nearest multiple of b to a,
4485 * preferring even multiples in the case of a tie.
4486 *
4487 * So the nearest multiple of 10**n to m is:
4488 *
4489 * m - divmod_near(m, 10**n)[1].
4490 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4492 return NULL;
4493 if (o_ndigits == NULL)
4494 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004495
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004496 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 if (ndigits == NULL)
4498 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004499
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004500 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 if (Py_SIZE(ndigits) >= 0) {
4502 Py_DECREF(ndigits);
4503 return long_long(self);
4504 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004505
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004506 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4507 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004509 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004511 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004512
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004513 result = PyLong_FromLong(10L);
4514 if (result == NULL) {
4515 Py_DECREF(ndigits);
4516 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004518
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004519 temp = long_pow(result, ndigits, Py_None);
4520 Py_DECREF(ndigits);
4521 Py_DECREF(result);
4522 result = temp;
4523 if (result == NULL)
4524 return NULL;
4525
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004526 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004527 Py_DECREF(result);
4528 result = temp;
4529 if (result == NULL)
4530 return NULL;
4531
4532 temp = long_sub((PyLongObject *)self,
4533 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4534 Py_DECREF(result);
4535 result = temp;
4536
4537 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004538}
4539
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004540static PyObject *
4541long_sizeof(PyLongObject *v)
4542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004545 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4546 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004547}
4548
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004549static PyObject *
4550long_bit_length(PyLongObject *v)
4551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 PyLongObject *result, *x, *y;
4553 Py_ssize_t ndigits, msd_bits = 0;
4554 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004556 assert(v != NULL);
4557 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004559 ndigits = ABS(Py_SIZE(v));
4560 if (ndigits == 0)
4561 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 msd = v->ob_digit[ndigits-1];
4564 while (msd >= 32) {
4565 msd_bits += 6;
4566 msd >>= 6;
4567 }
4568 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4571 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 /* expression above may overflow; use Python integers instead */
4574 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4575 if (result == NULL)
4576 return NULL;
4577 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4578 if (x == NULL)
4579 goto error;
4580 y = (PyLongObject *)long_mul(result, x);
4581 Py_DECREF(x);
4582 if (y == NULL)
4583 goto error;
4584 Py_DECREF(result);
4585 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4588 if (x == NULL)
4589 goto error;
4590 y = (PyLongObject *)long_add(result, x);
4591 Py_DECREF(x);
4592 if (y == NULL)
4593 goto error;
4594 Py_DECREF(result);
4595 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004598
Mark Dickinson22b20182010-05-10 21:27:53 +00004599 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 Py_DECREF(result);
4601 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004602}
4603
4604PyDoc_STRVAR(long_bit_length_doc,
4605"int.bit_length() -> int\n\
4606\n\
4607Number of bits necessary to represent self in binary.\n\
4608>>> bin(37)\n\
4609'0b100101'\n\
4610>>> (37).bit_length()\n\
46116");
4612
Christian Heimes53876d92008-04-19 00:31:39 +00004613#if 0
4614static PyObject *
4615long_is_finite(PyObject *v)
4616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004618}
4619#endif
4620
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004621
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004622static PyObject *
4623long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 PyObject *byteorder_str;
4626 PyObject *is_signed_obj = NULL;
4627 Py_ssize_t length;
4628 int little_endian;
4629 int is_signed;
4630 PyObject *bytes;
4631 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4634 &length, &byteorder_str,
4635 &is_signed_obj))
4636 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 if (args != NULL && Py_SIZE(args) > 2) {
4639 PyErr_SetString(PyExc_TypeError,
4640 "'signed' is a keyword-only argument");
4641 return NULL;
4642 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4645 little_endian = 1;
4646 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4647 little_endian = 0;
4648 else {
4649 PyErr_SetString(PyExc_ValueError,
4650 "byteorder must be either 'little' or 'big'");
4651 return NULL;
4652 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 if (is_signed_obj != NULL) {
4655 int cmp = PyObject_IsTrue(is_signed_obj);
4656 if (cmp < 0)
4657 return NULL;
4658 is_signed = cmp ? 1 : 0;
4659 }
4660 else {
4661 /* If the signed argument was omitted, use False as the
4662 default. */
4663 is_signed = 0;
4664 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 if (length < 0) {
4667 PyErr_SetString(PyExc_ValueError,
4668 "length argument must be non-negative");
4669 return NULL;
4670 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 bytes = PyBytes_FromStringAndSize(NULL, length);
4673 if (bytes == NULL)
4674 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4677 length, little_endian, is_signed) < 0) {
4678 Py_DECREF(bytes);
4679 return NULL;
4680 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004683}
4684
Mark Dickinson078c2532010-01-30 18:06:17 +00004685PyDoc_STRVAR(long_to_bytes_doc,
4686"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004687\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004688Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004689\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004691raised if the integer is not representable with the given number of\n\
4692bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004693\n\
4694The byteorder argument determines the byte order used to represent the\n\
4695integer. If byteorder is 'big', the most significant byte is at the\n\
4696beginning of the byte array. If byteorder is 'little', the most\n\
4697significant byte is at the end of the byte array. To request the native\n\
4698byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4699\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004700The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004702is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004703
4704static PyObject *
4705long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004707 PyObject *byteorder_str;
4708 PyObject *is_signed_obj = NULL;
4709 int little_endian;
4710 int is_signed;
4711 PyObject *obj;
4712 PyObject *bytes;
4713 PyObject *long_obj;
4714 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4717 &obj, &byteorder_str,
4718 &is_signed_obj))
4719 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (args != NULL && Py_SIZE(args) > 2) {
4722 PyErr_SetString(PyExc_TypeError,
4723 "'signed' is a keyword-only argument");
4724 return NULL;
4725 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4728 little_endian = 1;
4729 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4730 little_endian = 0;
4731 else {
4732 PyErr_SetString(PyExc_ValueError,
4733 "byteorder must be either 'little' or 'big'");
4734 return NULL;
4735 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 if (is_signed_obj != NULL) {
4738 int cmp = PyObject_IsTrue(is_signed_obj);
4739 if (cmp < 0)
4740 return NULL;
4741 is_signed = cmp ? 1 : 0;
4742 }
4743 else {
4744 /* If the signed argument was omitted, use False as the
4745 default. */
4746 is_signed = 0;
4747 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004749 bytes = PyObject_Bytes(obj);
4750 if (bytes == NULL)
4751 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 long_obj = _PyLong_FromByteArray(
4754 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4755 little_endian, is_signed);
4756 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 /* If from_bytes() was used on subclass, allocate new subclass
4759 * instance, initialize it with decoded long value and return it.
4760 */
4761 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4762 PyLongObject *newobj;
4763 int i;
4764 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004766 newobj = (PyLongObject *)type->tp_alloc(type, n);
4767 if (newobj == NULL) {
4768 Py_DECREF(long_obj);
4769 return NULL;
4770 }
4771 assert(PyLong_Check(newobj));
4772 Py_SIZE(newobj) = Py_SIZE(long_obj);
4773 for (i = 0; i < n; i++) {
4774 newobj->ob_digit[i] =
4775 ((PyLongObject *)long_obj)->ob_digit[i];
4776 }
4777 Py_DECREF(long_obj);
4778 return (PyObject *)newobj;
4779 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004781 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004782}
4783
Mark Dickinson078c2532010-01-30 18:06:17 +00004784PyDoc_STRVAR(long_from_bytes_doc,
4785"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4786\n\
4787Return the integer represented by the given array of bytes.\n\
4788\n\
4789The bytes argument must either support the buffer protocol or be an\n\
4790iterable object producing bytes. Bytes and bytearray are examples of\n\
4791built-in objects that support the buffer protocol.\n\
4792\n\
4793The byteorder argument determines the byte order used to represent the\n\
4794integer. If byteorder is 'big', the most significant byte is at the\n\
4795beginning of the byte array. If byteorder is 'little', the most\n\
4796significant byte is at the end of the byte array. To request the native\n\
4797byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4798\n\
4799The signed keyword-only argument indicates whether two's complement is\n\
4800used to represent the integer.");
4801
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004802static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4804 "Returns self, the complex conjugate of any int."},
4805 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4806 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004807#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4809 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004810#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004811 {"to_bytes", (PyCFunction)long_to_bytes,
4812 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4813 {"from_bytes", (PyCFunction)long_from_bytes,
4814 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4815 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4816 "Truncating an Integral returns itself."},
4817 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4818 "Flooring an Integral returns itself."},
4819 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4820 "Ceiling of an Integral returns itself."},
4821 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4822 "Rounding an Integral returns itself.\n"
4823 "Rounding with an ndigits argument also returns an integer."},
4824 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4825 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4826 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4827 "Returns size in memory, in bytes"},
4828 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004829};
4830
Guido van Rossumb43daf72007-08-01 18:08:08 +00004831static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004832 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004833 (getter)long_long, (setter)NULL,
4834 "the real part of a complex number",
4835 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004836 {"imag",
4837 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004838 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004839 NULL},
4840 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004841 (getter)long_long, (setter)NULL,
4842 "the numerator of a rational number in lowest terms",
4843 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004844 {"denominator",
4845 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004846 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004847 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004848 {NULL} /* Sentinel */
4849};
4850
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004851PyDoc_STRVAR(long_doc,
Guido van Rossumddefaf32007-01-14 03:31:43 +00004852"int(x[, base]) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004853\n\
Guido van Rossumddefaf32007-01-14 03:31:43 +00004854Convert a string or number to an integer, if possible. A floating\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004855point argument will be truncated towards zero (this does not include a\n\
4856string representation of a floating point number!) When converting a\n\
4857string, use the optional base. It is an error to supply a base when\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004858converting a non-string.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004859
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004860static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004861 (binaryfunc)long_add, /*nb_add*/
4862 (binaryfunc)long_sub, /*nb_subtract*/
4863 (binaryfunc)long_mul, /*nb_multiply*/
4864 long_mod, /*nb_remainder*/
4865 long_divmod, /*nb_divmod*/
4866 long_pow, /*nb_power*/
4867 (unaryfunc)long_neg, /*nb_negative*/
4868 (unaryfunc)long_long, /*tp_positive*/
4869 (unaryfunc)long_abs, /*tp_absolute*/
4870 (inquiry)long_bool, /*tp_bool*/
4871 (unaryfunc)long_invert, /*nb_invert*/
4872 long_lshift, /*nb_lshift*/
4873 (binaryfunc)long_rshift, /*nb_rshift*/
4874 long_and, /*nb_and*/
4875 long_xor, /*nb_xor*/
4876 long_or, /*nb_or*/
4877 long_long, /*nb_int*/
4878 0, /*nb_reserved*/
4879 long_float, /*nb_float*/
4880 0, /* nb_inplace_add */
4881 0, /* nb_inplace_subtract */
4882 0, /* nb_inplace_multiply */
4883 0, /* nb_inplace_remainder */
4884 0, /* nb_inplace_power */
4885 0, /* nb_inplace_lshift */
4886 0, /* nb_inplace_rshift */
4887 0, /* nb_inplace_and */
4888 0, /* nb_inplace_xor */
4889 0, /* nb_inplace_or */
4890 long_div, /* nb_floor_divide */
4891 long_true_divide, /* nb_true_divide */
4892 0, /* nb_inplace_floor_divide */
4893 0, /* nb_inplace_true_divide */
4894 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004895};
4896
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004897PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004898 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4899 "int", /* tp_name */
4900 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4901 sizeof(digit), /* tp_itemsize */
4902 long_dealloc, /* tp_dealloc */
4903 0, /* tp_print */
4904 0, /* tp_getattr */
4905 0, /* tp_setattr */
4906 0, /* tp_reserved */
4907 long_to_decimal_string, /* tp_repr */
4908 &long_as_number, /* tp_as_number */
4909 0, /* tp_as_sequence */
4910 0, /* tp_as_mapping */
4911 (hashfunc)long_hash, /* tp_hash */
4912 0, /* tp_call */
4913 long_to_decimal_string, /* tp_str */
4914 PyObject_GenericGetAttr, /* tp_getattro */
4915 0, /* tp_setattro */
4916 0, /* tp_as_buffer */
4917 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4918 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4919 long_doc, /* tp_doc */
4920 0, /* tp_traverse */
4921 0, /* tp_clear */
4922 long_richcompare, /* tp_richcompare */
4923 0, /* tp_weaklistoffset */
4924 0, /* tp_iter */
4925 0, /* tp_iternext */
4926 long_methods, /* tp_methods */
4927 0, /* tp_members */
4928 long_getset, /* tp_getset */
4929 0, /* tp_base */
4930 0, /* tp_dict */
4931 0, /* tp_descr_get */
4932 0, /* tp_descr_set */
4933 0, /* tp_dictoffset */
4934 0, /* tp_init */
4935 0, /* tp_alloc */
4936 long_new, /* tp_new */
4937 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004938};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004939
Mark Dickinsonbd792642009-03-18 20:06:12 +00004940static PyTypeObject Int_InfoType;
4941
4942PyDoc_STRVAR(int_info__doc__,
4943"sys.int_info\n\
4944\n\
4945A struct sequence that holds information about Python's\n\
4946internal representation of integers. The attributes are read only.");
4947
4948static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004949 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004950 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004952};
4953
4954static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004955 "sys.int_info", /* name */
4956 int_info__doc__, /* doc */
4957 int_info_fields, /* fields */
4958 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004959};
4960
4961PyObject *
4962PyLong_GetInfo(void)
4963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 PyObject* int_info;
4965 int field = 0;
4966 int_info = PyStructSequence_New(&Int_InfoType);
4967 if (int_info == NULL)
4968 return NULL;
4969 PyStructSequence_SET_ITEM(int_info, field++,
4970 PyLong_FromLong(PyLong_SHIFT));
4971 PyStructSequence_SET_ITEM(int_info, field++,
4972 PyLong_FromLong(sizeof(digit)));
4973 if (PyErr_Occurred()) {
4974 Py_CLEAR(int_info);
4975 return NULL;
4976 }
4977 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00004978}
4979
Guido van Rossumddefaf32007-01-14 03:31:43 +00004980int
4981_PyLong_Init(void)
4982{
4983#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 int ival, size;
4985 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
4988 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
4989 if (Py_TYPE(v) == &PyLong_Type) {
4990 /* The element is already initialized, most likely
4991 * the Python interpreter was initialized before.
4992 */
4993 Py_ssize_t refcnt;
4994 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00004995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004996 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
4997 _Py_NewReference(op);
4998 /* _Py_NewReference sets the ref count to 1 but
4999 * the ref count might be larger. Set the refcnt
5000 * to the original refcnt + 1 */
5001 Py_REFCNT(op) = refcnt + 1;
5002 assert(Py_SIZE(op) == size);
5003 assert(v->ob_digit[0] == abs(ival));
5004 }
5005 else {
5006 PyObject_INIT(v, &PyLong_Type);
5007 }
5008 Py_SIZE(v) = size;
5009 v->ob_digit[0] = abs(ival);
5010 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005011#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005012 /* initialize int_info */
5013 if (Int_InfoType.tp_name == 0)
5014 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005017}
5018
5019void
5020PyLong_Fini(void)
5021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 /* Integers are currently statically allocated. Py_DECREF is not
5023 needed, but Python must forget about the reference or multiple
5024 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 int i;
5027 PyLongObject *v = small_ints;
5028 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5029 _Py_DEC_REFTOTAL;
5030 _Py_ForgetReference((PyObject*)v);
5031 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005032#endif
5033}