blob: cdaea027751b14372356c40c55ff8bc37de50038 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020#define MEDIUM_VALUE(x) (Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
21 (Py_SIZE(x) == 0 ? (sdigit)0 : \
22 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000023#define ABS(x) ((x) < 0 ? -(x) : (x))
24
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
40 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 if (ival >= 0)
43 quick_int_allocs++;
44 else
45 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048}
49#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
51 return get_small_int((sdigit)ival); \
52 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000055maybe_small_long(PyLongObject *v)
56{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 if (v && ABS(Py_SIZE(v)) <= 1) {
58 sdigit ival = MEDIUM_VALUE(v);
59 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
60 Py_DECREF(v);
61 return (PyLongObject *)get_small_int(ival);
62 }
63 }
64 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000065}
Guido van Rossumddefaf32007-01-14 03:31:43 +000066#else
67#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#endif
70
Guido van Rossumddefaf32007-01-14 03:31:43 +000071/* If a freshly-allocated long is already shared, it must
72 be a small integer, so negating it must go to PyLong_FromLong */
73#define NEGATE(x) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 do if (Py_REFCNT(x) == 1) Py_SIZE(x) = -Py_SIZE(x); \
75 else { PyObject* tmp=PyLong_FromLong(-MEDIUM_VALUE(x)); \
76 Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
77 while(0)
Tim Peters5af4e6c2002-08-12 02:31:19 +000078/* For long multiplication, use the O(N**2) school algorithm unless
79 * both operands contain more than KARATSUBA_CUTOFF digits (this
80 * being an internal Python long digit, in base BASE).
81 */
Tim Peters0973b992004-08-29 22:16:50 +000082#define KARATSUBA_CUTOFF 70
83#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000084
Tim Peters47e52ee2004-08-30 02:44:38 +000085/* For exponentiation, use the binary left-to-right algorithm
86 * unless the exponent contains more than FIVEARY_CUTOFF digits.
87 * In that case, do 5 bits at a time. The potential drawback is that
88 * a table of 2**5 intermediate results is computed.
89 */
90#define FIVEARY_CUTOFF 8
91
Tim Peters5af4e6c2002-08-12 02:31:19 +000092#undef MIN
93#undef MAX
94#define MAX(x, y) ((x) < (y) ? (y) : (x))
95#define MIN(x, y) ((x) > (y) ? (y) : (x))
96
Mark Dickinsoncdd01d22010-05-10 21:37:34 +000097#define SIGCHECK(PyTryBlock) \
98 do { \
99 if (PyErr_CheckSignals()) PyTryBlock \
100 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000101
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000102/* Normalize (remove leading zeros from) a long int object.
103 Doesn't attempt to free the storage--in most cases, due to the nature
104 of the algorithms used, this could save at most be one word anyway. */
105
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000107long_normalize(register PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 Py_ssize_t j = ABS(Py_SIZE(v));
110 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 while (i > 0 && v->ob_digit[i-1] == 0)
113 --i;
114 if (i != j)
115 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
116 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000117}
118
119/* Allocate a new long int object with size digits.
120 Return NULL and set exception if we run out of memory. */
121
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000122#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000126_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyLongObject *result;
129 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
130 sizeof(digit)*size. Previous incarnations of this code used
131 sizeof(PyVarObject) instead of the offsetof, but this risks being
132 incorrect in the presence of padding between the PyVarObject header
133 and the digits. */
134 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
135 PyErr_SetString(PyExc_OverflowError,
136 "too many digits in integer");
137 return NULL;
138 }
139 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
140 size*sizeof(digit));
141 if (!result) {
142 PyErr_NoMemory();
143 return NULL;
144 }
145 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000146}
147
Tim Peters64b5ce32001-09-10 20:52:51 +0000148PyObject *
149_PyLong_Copy(PyLongObject *src)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyLongObject *result;
152 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 assert(src != NULL);
155 i = Py_SIZE(src);
156 if (i < 0)
157 i = -(i);
158 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100159 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 CHECK_SMALL_INT(ival);
161 }
162 result = _PyLong_New(i);
163 if (result != NULL) {
164 Py_SIZE(result) = Py_SIZE(src);
165 while (--i >= 0)
166 result->ob_digit[i] = src->ob_digit[i];
167 }
168 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000169}
170
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000171/* Create a new long int object from a C long int */
172
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000174PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PyLongObject *v;
177 unsigned long abs_ival;
178 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
179 int ndigits = 0;
180 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (ival < 0) {
185 /* negate: can't write this as abs_ival = -ival since that
186 invokes undefined behaviour when ival is LONG_MIN */
187 abs_ival = 0U-(unsigned long)ival;
188 sign = -1;
189 }
190 else {
191 abs_ival = (unsigned long)ival;
192 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 /* Fast path for single-digit ints */
195 if (!(abs_ival >> PyLong_SHIFT)) {
196 v = _PyLong_New(1);
197 if (v) {
198 Py_SIZE(v) = sign;
199 v->ob_digit[0] = Py_SAFE_DOWNCAST(
200 abs_ival, unsigned long, digit);
201 }
202 return (PyObject*)v;
203 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000204
Mark Dickinson249b8982009-04-27 19:41:00 +0000205#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* 2 digits */
207 if (!(abs_ival >> 2*PyLong_SHIFT)) {
208 v = _PyLong_New(2);
209 if (v) {
210 Py_SIZE(v) = 2*sign;
211 v->ob_digit[0] = Py_SAFE_DOWNCAST(
212 abs_ival & PyLong_MASK, unsigned long, digit);
213 v->ob_digit[1] = Py_SAFE_DOWNCAST(
214 abs_ival >> PyLong_SHIFT, unsigned long, digit);
215 }
216 return (PyObject*)v;
217 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000218#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 /* Larger numbers: loop to determine number of digits */
221 t = abs_ival;
222 while (t) {
223 ++ndigits;
224 t >>= PyLong_SHIFT;
225 }
226 v = _PyLong_New(ndigits);
227 if (v != NULL) {
228 digit *p = v->ob_digit;
229 Py_SIZE(v) = ndigits*sign;
230 t = abs_ival;
231 while (t) {
232 *p++ = Py_SAFE_DOWNCAST(
233 t & PyLong_MASK, unsigned long, digit);
234 t >>= PyLong_SHIFT;
235 }
236 }
237 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000238}
239
Guido van Rossum53756b11997-01-03 17:14:46 +0000240/* Create a new long int object from a C unsigned long int */
241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long t;
247 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (ival < PyLong_BASE)
250 return PyLong_FromLong(ival);
251 /* Count the number of Python digits. */
252 t = (unsigned long)ival;
253 while (t) {
254 ++ndigits;
255 t >>= PyLong_SHIFT;
256 }
257 v = _PyLong_New(ndigits);
258 if (v != NULL) {
259 digit *p = v->ob_digit;
260 Py_SIZE(v) = ndigits;
261 while (ival) {
262 *p++ = (digit)(ival & PyLong_MASK);
263 ival >>= PyLong_SHIFT;
264 }
265 }
266 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000267}
268
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000269/* Create a new long int object from a C double */
270
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000271PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000272PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyLongObject *v;
275 double frac;
276 int i, ndig, expo, neg;
277 neg = 0;
278 if (Py_IS_INFINITY(dval)) {
279 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000280 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return NULL;
282 }
283 if (Py_IS_NAN(dval)) {
284 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000285 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return NULL;
287 }
288 if (dval < 0.0) {
289 neg = 1;
290 dval = -dval;
291 }
292 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
293 if (expo <= 0)
294 return PyLong_FromLong(0L);
295 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
296 v = _PyLong_New(ndig);
297 if (v == NULL)
298 return NULL;
299 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
300 for (i = ndig; --i >= 0; ) {
301 digit bits = (digit)frac;
302 v->ob_digit[i] = bits;
303 frac = frac - (double)bits;
304 frac = ldexp(frac, PyLong_SHIFT);
305 }
306 if (neg)
307 Py_SIZE(v) = -(Py_SIZE(v));
308 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000309}
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
312 * anything about what happens when a signed integer operation overflows,
313 * and some compilers think they're doing you a favor by being "clever"
314 * then. The bit pattern for the largest postive signed long is
315 * (unsigned long)LONG_MAX, and for the smallest negative signed long
316 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
317 * However, some other compilers warn about applying unary minus to an
318 * unsigned operand. Hence the weird "0-".
319 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
321#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322
Mark Dickinson8d48b432011-10-23 20:47:14 +0100323/* Get a C long int from a long int object or any object that has an __int__
324 method.
325
326 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
327 the result. Otherwise *overflow is 0.
328
329 For other errors (e.g., TypeError), return -1 and set an error condition.
330 In this case *overflow will be 0.
331*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000332
333long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000334PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* This version by Tim Peters */
337 register PyLongObject *v;
338 unsigned long x, prev;
339 long res;
340 Py_ssize_t i;
341 int sign;
342 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 *overflow = 0;
345 if (vv == NULL) {
346 PyErr_BadInternalCall();
347 return -1;
348 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!PyLong_Check(vv)) {
351 PyNumberMethods *nb;
352 nb = vv->ob_type->tp_as_number;
353 if (nb == NULL || nb->nb_int == NULL) {
354 PyErr_SetString(PyExc_TypeError,
355 "an integer is required");
356 return -1;
357 }
358 vv = (*nb->nb_int) (vv);
359 if (vv == NULL)
360 return -1;
361 do_decref = 1;
362 if (!PyLong_Check(vv)) {
363 Py_DECREF(vv);
364 PyErr_SetString(PyExc_TypeError,
365 "nb_int should return int object");
366 return -1;
367 }
368 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 res = -1;
371 v = (PyLongObject *)vv;
372 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 switch (i) {
375 case -1:
376 res = -(sdigit)v->ob_digit[0];
377 break;
378 case 0:
379 res = 0;
380 break;
381 case 1:
382 res = v->ob_digit[0];
383 break;
384 default:
385 sign = 1;
386 x = 0;
387 if (i < 0) {
388 sign = -1;
389 i = -(i);
390 }
391 while (--i >= 0) {
392 prev = x;
393 x = (x << PyLong_SHIFT) | v->ob_digit[i];
394 if ((x >> PyLong_SHIFT) != prev) {
395 *overflow = sign;
396 goto exit;
397 }
398 }
399 /* Haven't lost any bits, but casting to long requires extra
400 * care (see comment above).
401 */
402 if (x <= (unsigned long)LONG_MAX) {
403 res = (long)x * sign;
404 }
405 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
406 res = LONG_MIN;
407 }
408 else {
409 *overflow = sign;
410 /* res is already set to -1 */
411 }
412 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (do_decref) {
415 Py_DECREF(vv);
416 }
417 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000418}
419
Mark Dickinson8d48b432011-10-23 20:47:14 +0100420/* Get a C long int from a long int object or any object that has an __int__
421 method. Return -1 and set an error if overflow occurs. */
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000424PyLong_AsLong(PyObject *obj)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int overflow;
427 long result = PyLong_AsLongAndOverflow(obj, &overflow);
428 if (overflow) {
429 /* XXX: could be cute and give a different
430 message for overflow == -1 */
431 PyErr_SetString(PyExc_OverflowError,
432 "Python int too large to convert to C long");
433 }
434 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000435}
436
Serhiy Storchaka78980432013-01-15 01:12:17 +0200437/* Get a C int from a long int object or any object that has an __int__
438 method. Return -1 and set an error if overflow occurs. */
439
440int
441_PyLong_AsInt(PyObject *obj)
442{
443 int overflow;
444 long result = PyLong_AsLongAndOverflow(obj, &overflow);
445 if (overflow || result > INT_MAX || result < INT_MIN) {
446 /* XXX: could be cute and give a different
447 message for overflow == -1 */
448 PyErr_SetString(PyExc_OverflowError,
449 "Python int too large to convert to C int");
450 return -1;
451 }
452 return (int)result;
453}
454
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000455/* Get a Py_ssize_t from a long int object.
456 Returns -1 and sets an error condition if overflow occurs. */
457
458Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000459PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 register PyLongObject *v;
461 size_t x, prev;
462 Py_ssize_t i;
463 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (vv == NULL) {
466 PyErr_BadInternalCall();
467 return -1;
468 }
469 if (!PyLong_Check(vv)) {
470 PyErr_SetString(PyExc_TypeError, "an integer is required");
471 return -1;
472 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 v = (PyLongObject *)vv;
475 i = Py_SIZE(v);
476 switch (i) {
477 case -1: return -(sdigit)v->ob_digit[0];
478 case 0: return 0;
479 case 1: return v->ob_digit[0];
480 }
481 sign = 1;
482 x = 0;
483 if (i < 0) {
484 sign = -1;
485 i = -(i);
486 }
487 while (--i >= 0) {
488 prev = x;
489 x = (x << PyLong_SHIFT) | v->ob_digit[i];
490 if ((x >> PyLong_SHIFT) != prev)
491 goto overflow;
492 }
493 /* Haven't lost any bits, but casting to a signed type requires
494 * extra care (see comment above).
495 */
496 if (x <= (size_t)PY_SSIZE_T_MAX) {
497 return (Py_ssize_t)x * sign;
498 }
499 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
500 return PY_SSIZE_T_MIN;
501 }
502 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000503
Mark Dickinson22b20182010-05-10 21:27:53 +0000504 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyErr_SetString(PyExc_OverflowError,
506 "Python int too large to convert to C ssize_t");
507 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000508}
509
Guido van Rossumd8c80482002-08-13 00:24:58 +0000510/* Get a C unsigned long int from a long int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000511 Returns -1 and sets an error condition if overflow occurs. */
512
513unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000514PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 register PyLongObject *v;
517 unsigned long x, prev;
518 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (vv == NULL) {
521 PyErr_BadInternalCall();
522 return (unsigned long)-1;
523 }
524 if (!PyLong_Check(vv)) {
525 PyErr_SetString(PyExc_TypeError, "an integer is required");
526 return (unsigned long)-1;
527 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 v = (PyLongObject *)vv;
530 i = Py_SIZE(v);
531 x = 0;
532 if (i < 0) {
533 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000534 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return (unsigned long) -1;
536 }
537 switch (i) {
538 case 0: return 0;
539 case 1: return v->ob_digit[0];
540 }
541 while (--i >= 0) {
542 prev = x;
543 x = (x << PyLong_SHIFT) | v->ob_digit[i];
544 if ((x >> PyLong_SHIFT) != prev) {
545 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000546 "python int too large to convert "
547 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 return (unsigned long) -1;
549 }
550 }
551 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000552}
553
Stefan Krahb77c6c62011-09-12 16:22:47 +0200554/* Get a C size_t from a long int object. Returns (size_t)-1 and sets
555 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000556
557size_t
558PyLong_AsSize_t(PyObject *vv)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 register PyLongObject *v;
561 size_t x, prev;
562 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 if (vv == NULL) {
565 PyErr_BadInternalCall();
566 return (size_t) -1;
567 }
568 if (!PyLong_Check(vv)) {
569 PyErr_SetString(PyExc_TypeError, "an integer is required");
570 return (size_t)-1;
571 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 v = (PyLongObject *)vv;
574 i = Py_SIZE(v);
575 x = 0;
576 if (i < 0) {
577 PyErr_SetString(PyExc_OverflowError,
578 "can't convert negative value to size_t");
579 return (size_t) -1;
580 }
581 switch (i) {
582 case 0: return 0;
583 case 1: return v->ob_digit[0];
584 }
585 while (--i >= 0) {
586 prev = x;
587 x = (x << PyLong_SHIFT) | v->ob_digit[i];
588 if ((x >> PyLong_SHIFT) != prev) {
589 PyErr_SetString(PyExc_OverflowError,
590 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200591 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 }
593 }
594 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000595}
596
Thomas Hellera4ea6032003-04-17 18:55:45 +0000597/* Get a C unsigned long int from a long int object, ignoring the high bits.
598 Returns -1 and sets an error condition if an error occurs. */
599
Guido van Rossumddefaf32007-01-14 03:31:43 +0000600static unsigned long
601_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 register PyLongObject *v;
604 unsigned long x;
605 Py_ssize_t i;
606 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (vv == NULL || !PyLong_Check(vv)) {
609 PyErr_BadInternalCall();
610 return (unsigned long) -1;
611 }
612 v = (PyLongObject *)vv;
613 i = Py_SIZE(v);
614 switch (i) {
615 case 0: return 0;
616 case 1: return v->ob_digit[0];
617 }
618 sign = 1;
619 x = 0;
620 if (i < 0) {
621 sign = -1;
622 i = -i;
623 }
624 while (--i >= 0) {
625 x = (x << PyLong_SHIFT) | v->ob_digit[i];
626 }
627 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000628}
629
Guido van Rossumddefaf32007-01-14 03:31:43 +0000630unsigned long
631PyLong_AsUnsignedLongMask(register PyObject *op)
632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PyNumberMethods *nb;
634 PyLongObject *lo;
635 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (op && PyLong_Check(op))
638 return _PyLong_AsUnsignedLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
641 nb->nb_int == NULL) {
642 PyErr_SetString(PyExc_TypeError, "an integer is required");
643 return (unsigned long)-1;
644 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 lo = (PyLongObject*) (*nb->nb_int) (op);
647 if (lo == NULL)
648 return (unsigned long)-1;
649 if (PyLong_Check(lo)) {
650 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
651 Py_DECREF(lo);
652 if (PyErr_Occurred())
653 return (unsigned long)-1;
654 return val;
655 }
656 else
657 {
658 Py_DECREF(lo);
659 PyErr_SetString(PyExc_TypeError,
660 "nb_int should return int object");
661 return (unsigned long)-1;
662 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000663}
664
Tim Peters5b8132f2003-01-31 15:52:05 +0000665int
666_PyLong_Sign(PyObject *vv)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 assert(v != NULL);
671 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000674}
675
Tim Petersbaefd9e2003-01-28 20:37:45 +0000676size_t
677_PyLong_NumBits(PyObject *vv)
678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyLongObject *v = (PyLongObject *)vv;
680 size_t result = 0;
681 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 assert(v != NULL);
684 assert(PyLong_Check(v));
685 ndigits = ABS(Py_SIZE(v));
686 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
687 if (ndigits > 0) {
688 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100689 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100691 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 do {
693 ++result;
694 if (result == 0)
695 goto Overflow;
696 msd >>= 1;
697 } while (msd);
698 }
699 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000700
Mark Dickinson22b20182010-05-10 21:27:53 +0000701 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
703 "to express in a platform size_t");
704 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000705}
706
Tim Peters2a9b3672001-06-11 21:23:58 +0000707PyObject *
708_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000710{
Mark Dickinson22b20182010-05-10 21:27:53 +0000711 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 int incr; /* direction to move pstartbyte */
713 const unsigned char* pendbyte; /* MSB of bytes */
714 size_t numsignificantbytes; /* number of bytes that matter */
715 Py_ssize_t ndigits; /* number of Python long digits */
716 PyLongObject* v; /* result */
717 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (n == 0)
720 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (little_endian) {
723 pstartbyte = bytes;
724 pendbyte = bytes + n - 1;
725 incr = 1;
726 }
727 else {
728 pstartbyte = bytes + n - 1;
729 pendbyte = bytes;
730 incr = -1;
731 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (is_signed)
734 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200737 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 is positive, and leading 0xff bytes if negative. */
739 {
740 size_t i;
741 const unsigned char* p = pendbyte;
742 const int pincr = -incr; /* search MSB to LSB */
743 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 for (i = 0; i < n; ++i, p += pincr) {
746 if (*p != insignficant)
747 break;
748 }
749 numsignificantbytes = n - i;
750 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
751 actually has 2 significant bytes. OTOH, 0xff0001 ==
752 -0x00ffff, so we wouldn't *need* to bump it there; but we
753 do for 0xffff = -0x0001. To be safe without bothering to
754 check every case, bump it regardless. */
755 if (is_signed && numsignificantbytes < n)
756 ++numsignificantbytes;
757 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* How many Python long digits do we need? We have
760 8*numsignificantbytes bits, and each Python long digit has
761 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
762 /* catch overflow before it happens */
763 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
764 PyErr_SetString(PyExc_OverflowError,
765 "byte array too long to convert to int");
766 return NULL;
767 }
768 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
769 v = _PyLong_New(ndigits);
770 if (v == NULL)
771 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 /* Copy the bits over. The tricky parts are computing 2's-comp on
774 the fly for signed numbers, and dealing with the mismatch between
775 8-bit bytes and (probably) 15-bit Python digits.*/
776 {
777 size_t i;
778 twodigits carry = 1; /* for 2's-comp calculation */
779 twodigits accum = 0; /* sliding register */
780 unsigned int accumbits = 0; /* number of bits in accum */
781 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
784 twodigits thisbyte = *p;
785 /* Compute correction for 2's comp, if needed. */
786 if (is_signed) {
787 thisbyte = (0xff ^ thisbyte) + carry;
788 carry = thisbyte >> 8;
789 thisbyte &= 0xff;
790 }
791 /* Because we're going LSB to MSB, thisbyte is
792 more significant than what's already in accum,
793 so needs to be prepended to accum. */
794 accum |= (twodigits)thisbyte << accumbits;
795 accumbits += 8;
796 if (accumbits >= PyLong_SHIFT) {
797 /* There's enough to fill a Python digit. */
798 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000799 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 ++idigit;
801 accum >>= PyLong_SHIFT;
802 accumbits -= PyLong_SHIFT;
803 assert(accumbits < PyLong_SHIFT);
804 }
805 }
806 assert(accumbits < PyLong_SHIFT);
807 if (accumbits) {
808 assert(idigit < ndigits);
809 v->ob_digit[idigit] = (digit)accum;
810 ++idigit;
811 }
812 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_SIZE(v) = is_signed ? -idigit : idigit;
815 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000816}
817
818int
819_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 unsigned char* bytes, size_t n,
821 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000824 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000826 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
828 digit carry; /* for computing 2's-comp */
829 size_t j; /* # bytes filled */
830 unsigned char* p; /* pointer to next byte in bytes */
831 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (Py_SIZE(v) < 0) {
836 ndigits = -(Py_SIZE(v));
837 if (!is_signed) {
838 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000839 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return -1;
841 }
842 do_twos_comp = 1;
843 }
844 else {
845 ndigits = Py_SIZE(v);
846 do_twos_comp = 0;
847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (little_endian) {
850 p = bytes;
851 pincr = 1;
852 }
853 else {
854 p = bytes + n - 1;
855 pincr = -1;
856 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* Copy over all the Python digits.
859 It's crucial that every Python digit except for the MSD contribute
860 exactly PyLong_SHIFT bits to the total, so first assert that the long is
861 normalized. */
862 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
863 j = 0;
864 accum = 0;
865 accumbits = 0;
866 carry = do_twos_comp ? 1 : 0;
867 for (i = 0; i < ndigits; ++i) {
868 digit thisdigit = v->ob_digit[i];
869 if (do_twos_comp) {
870 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
871 carry = thisdigit >> PyLong_SHIFT;
872 thisdigit &= PyLong_MASK;
873 }
874 /* Because we're going LSB to MSB, thisdigit is more
875 significant than what's already in accum, so needs to be
876 prepended to accum. */
877 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* The most-significant digit may be (probably is) at least
880 partly empty. */
881 if (i == ndigits - 1) {
882 /* Count # of sign bits -- they needn't be stored,
883 * although for signed conversion we need later to
884 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000885 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 while (s != 0) {
887 s >>= 1;
888 accumbits++;
889 }
890 }
891 else
892 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Store as many bytes as possible. */
895 while (accumbits >= 8) {
896 if (j >= n)
897 goto Overflow;
898 ++j;
899 *p = (unsigned char)(accum & 0xff);
900 p += pincr;
901 accumbits -= 8;
902 accum >>= 8;
903 }
904 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Store the straggler (if any). */
907 assert(accumbits < 8);
908 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
909 if (accumbits > 0) {
910 if (j >= n)
911 goto Overflow;
912 ++j;
913 if (do_twos_comp) {
914 /* Fill leading bits of the byte with sign bits
915 (appropriately pretending that the long had an
916 infinite supply of sign bits). */
917 accum |= (~(twodigits)0) << accumbits;
918 }
919 *p = (unsigned char)(accum & 0xff);
920 p += pincr;
921 }
922 else if (j == n && n > 0 && is_signed) {
923 /* The main loop filled the byte array exactly, so the code
924 just above didn't get to ensure there's a sign bit, and the
925 loop below wouldn't add one either. Make sure a sign bit
926 exists. */
927 unsigned char msb = *(p - pincr);
928 int sign_bit_set = msb >= 0x80;
929 assert(accumbits == 0);
930 if (sign_bit_set == do_twos_comp)
931 return 0;
932 else
933 goto Overflow;
934 }
Tim Peters05607ad2001-06-13 21:01:27 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Fill remaining bytes with copies of the sign bit. */
937 {
938 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
939 for ( ; j < n; ++j, p += pincr)
940 *p = signbyte;
941 }
Tim Peters05607ad2001-06-13 21:01:27 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000944
Mark Dickinson22b20182010-05-10 21:27:53 +0000945 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
947 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000948
Tim Peters2a9b3672001-06-11 21:23:58 +0000949}
950
Mark Dickinson8d48b432011-10-23 20:47:14 +0100951/* Create a new long int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000952
953PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000954PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000955{
Mark Dickinson91044792012-10-18 19:21:43 +0100956#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100957 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
958#else
959
Tim Peters70128a12001-06-16 08:48:40 +0000960#ifndef HAVE_LONG_LONG
961# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
962#endif
963#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000964# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000965#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100967#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000968
Guido van Rossum78694d91998-09-18 14:14:13 +0000969}
970
Mark Dickinson8d48b432011-10-23 20:47:14 +0100971/* Get a C pointer from a long int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000972
973void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000974PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000975{
Tim Peters70128a12001-06-16 08:48:40 +0000976#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
980 x = PyLong_AsLong(vv);
981 else
982 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000983#else
Tim Peters70128a12001-06-16 08:48:40 +0000984
985#ifndef HAVE_LONG_LONG
986# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
987#endif
988#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000989# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000990#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
994 x = PyLong_AsLongLong(vv);
995 else
996 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +0000997
998#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (x == -1 && PyErr_Occurred())
1001 return NULL;
1002 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001003}
1004
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001005#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001006
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001007/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001008 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001009 */
1010
Mark Dickinson22b20182010-05-10 21:27:53 +00001011#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001012
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001013/* Create a new long int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001014
1015PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001016PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyLongObject *v;
1019 unsigned PY_LONG_LONG abs_ival;
1020 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1021 int ndigits = 0;
1022 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 CHECK_SMALL_INT(ival);
1025 if (ival < 0) {
1026 /* avoid signed overflow on negation; see comments
1027 in PyLong_FromLong above. */
1028 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1029 negative = 1;
1030 }
1031 else {
1032 abs_ival = (unsigned PY_LONG_LONG)ival;
1033 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Count the number of Python digits.
1036 We used to pick 5 ("big enough for anything"), but that's a
1037 waste of time and space given that 5*15 = 75 bits are rarely
1038 needed. */
1039 t = abs_ival;
1040 while (t) {
1041 ++ndigits;
1042 t >>= PyLong_SHIFT;
1043 }
1044 v = _PyLong_New(ndigits);
1045 if (v != NULL) {
1046 digit *p = v->ob_digit;
1047 Py_SIZE(v) = negative ? -ndigits : ndigits;
1048 t = abs_ival;
1049 while (t) {
1050 *p++ = (digit)(t & PyLong_MASK);
1051 t >>= PyLong_SHIFT;
1052 }
1053 }
1054 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001055}
1056
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001057/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001058
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001059PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001060PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 PyLongObject *v;
1063 unsigned PY_LONG_LONG t;
1064 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (ival < PyLong_BASE)
1067 return PyLong_FromLong((long)ival);
1068 /* Count the number of Python digits. */
1069 t = (unsigned PY_LONG_LONG)ival;
1070 while (t) {
1071 ++ndigits;
1072 t >>= PyLong_SHIFT;
1073 }
1074 v = _PyLong_New(ndigits);
1075 if (v != NULL) {
1076 digit *p = v->ob_digit;
1077 Py_SIZE(v) = ndigits;
1078 while (ival) {
1079 *p++ = (digit)(ival & PyLong_MASK);
1080 ival >>= PyLong_SHIFT;
1081 }
1082 }
1083 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001084}
1085
Martin v. Löwis18e16552006-02-15 17:27:45 +00001086/* Create a new long int object from a C Py_ssize_t. */
1087
1088PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001089PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyLongObject *v;
1092 size_t abs_ival;
1093 size_t t; /* unsigned so >> doesn't propagate sign bit */
1094 int ndigits = 0;
1095 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 CHECK_SMALL_INT(ival);
1098 if (ival < 0) {
1099 /* avoid signed overflow when ival = SIZE_T_MIN */
1100 abs_ival = (size_t)(-1-ival)+1;
1101 negative = 1;
1102 }
1103 else {
1104 abs_ival = (size_t)ival;
1105 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 /* Count the number of Python digits. */
1108 t = abs_ival;
1109 while (t) {
1110 ++ndigits;
1111 t >>= PyLong_SHIFT;
1112 }
1113 v = _PyLong_New(ndigits);
1114 if (v != NULL) {
1115 digit *p = v->ob_digit;
1116 Py_SIZE(v) = negative ? -ndigits : ndigits;
1117 t = abs_ival;
1118 while (t) {
1119 *p++ = (digit)(t & PyLong_MASK);
1120 t >>= PyLong_SHIFT;
1121 }
1122 }
1123 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001124}
1125
1126/* Create a new long int object from a C size_t. */
1127
1128PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001129PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 PyLongObject *v;
1132 size_t t;
1133 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (ival < PyLong_BASE)
1136 return PyLong_FromLong((long)ival);
1137 /* Count the number of Python digits. */
1138 t = ival;
1139 while (t) {
1140 ++ndigits;
1141 t >>= PyLong_SHIFT;
1142 }
1143 v = _PyLong_New(ndigits);
1144 if (v != NULL) {
1145 digit *p = v->ob_digit;
1146 Py_SIZE(v) = ndigits;
1147 while (ival) {
1148 *p++ = (digit)(ival & PyLong_MASK);
1149 ival >>= PyLong_SHIFT;
1150 }
1151 }
1152 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001153}
1154
Mark Dickinson8d48b432011-10-23 20:47:14 +01001155/* Get a C long long int from a long int object or any object that has an
1156 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001157
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001158PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001159PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyLongObject *v;
1162 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (vv == NULL) {
1166 PyErr_BadInternalCall();
1167 return -1;
1168 }
1169 if (!PyLong_Check(vv)) {
1170 PyNumberMethods *nb;
1171 PyObject *io;
1172 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1173 nb->nb_int == NULL) {
1174 PyErr_SetString(PyExc_TypeError, "an integer is required");
1175 return -1;
1176 }
1177 io = (*nb->nb_int) (vv);
1178 if (io == NULL)
1179 return -1;
1180 if (PyLong_Check(io)) {
1181 bytes = PyLong_AsLongLong(io);
1182 Py_DECREF(io);
1183 return bytes;
1184 }
1185 Py_DECREF(io);
1186 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1187 return -1;
1188 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 v = (PyLongObject*)vv;
1191 switch(Py_SIZE(v)) {
1192 case -1: return -(sdigit)v->ob_digit[0];
1193 case 0: return 0;
1194 case 1: return v->ob_digit[0];
1195 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001196 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001197 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1200 if (res < 0)
1201 return (PY_LONG_LONG)-1;
1202 else
1203 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001204}
1205
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001206/* Get a C unsigned PY_LONG_LONG int from a long int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001207 Return -1 and set an error if overflow occurs. */
1208
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001209unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001210PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyLongObject *v;
1213 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001215
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001216 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyErr_BadInternalCall();
1218 return (unsigned PY_LONG_LONG)-1;
1219 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001220 if (!PyLong_Check(vv)) {
1221 PyErr_SetString(PyExc_TypeError, "an integer is required");
1222 return (unsigned PY_LONG_LONG)-1;
1223 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 v = (PyLongObject*)vv;
1226 switch(Py_SIZE(v)) {
1227 case 0: return 0;
1228 case 1: return v->ob_digit[0];
1229 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001230
Mark Dickinson22b20182010-05-10 21:27:53 +00001231 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001232 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1235 if (res < 0)
1236 return (unsigned PY_LONG_LONG)res;
1237 else
1238 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239}
Tim Petersd1a7da62001-06-13 00:35:57 +00001240
Thomas Hellera4ea6032003-04-17 18:55:45 +00001241/* Get a C unsigned long int from a long int object, ignoring the high bits.
1242 Returns -1 and sets an error condition if an error occurs. */
1243
Guido van Rossumddefaf32007-01-14 03:31:43 +00001244static unsigned PY_LONG_LONG
1245_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 register PyLongObject *v;
1248 unsigned PY_LONG_LONG x;
1249 Py_ssize_t i;
1250 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (vv == NULL || !PyLong_Check(vv)) {
1253 PyErr_BadInternalCall();
1254 return (unsigned long) -1;
1255 }
1256 v = (PyLongObject *)vv;
1257 switch(Py_SIZE(v)) {
1258 case 0: return 0;
1259 case 1: return v->ob_digit[0];
1260 }
1261 i = Py_SIZE(v);
1262 sign = 1;
1263 x = 0;
1264 if (i < 0) {
1265 sign = -1;
1266 i = -i;
1267 }
1268 while (--i >= 0) {
1269 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1270 }
1271 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001272}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273
1274unsigned PY_LONG_LONG
1275PyLong_AsUnsignedLongLongMask(register PyObject *op)
1276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 PyNumberMethods *nb;
1278 PyLongObject *lo;
1279 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (op && PyLong_Check(op))
1282 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1285 nb->nb_int == NULL) {
1286 PyErr_SetString(PyExc_TypeError, "an integer is required");
1287 return (unsigned PY_LONG_LONG)-1;
1288 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 lo = (PyLongObject*) (*nb->nb_int) (op);
1291 if (lo == NULL)
1292 return (unsigned PY_LONG_LONG)-1;
1293 if (PyLong_Check(lo)) {
1294 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1295 Py_DECREF(lo);
1296 if (PyErr_Occurred())
1297 return (unsigned PY_LONG_LONG)-1;
1298 return val;
1299 }
1300 else
1301 {
1302 Py_DECREF(lo);
1303 PyErr_SetString(PyExc_TypeError,
1304 "nb_int should return int object");
1305 return (unsigned PY_LONG_LONG)-1;
1306 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001307}
Tim Petersd1a7da62001-06-13 00:35:57 +00001308
Mark Dickinson8d48b432011-10-23 20:47:14 +01001309/* Get a C long long int from a long int object or any object that has an
1310 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001311
Mark Dickinson8d48b432011-10-23 20:47:14 +01001312 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1313 the result. Otherwise *overflow is 0.
1314
1315 For other errors (e.g., TypeError), return -1 and set an error condition.
1316 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001317*/
1318
1319PY_LONG_LONG
1320PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 /* This version by Tim Peters */
1323 register PyLongObject *v;
1324 unsigned PY_LONG_LONG x, prev;
1325 PY_LONG_LONG res;
1326 Py_ssize_t i;
1327 int sign;
1328 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 *overflow = 0;
1331 if (vv == NULL) {
1332 PyErr_BadInternalCall();
1333 return -1;
1334 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (!PyLong_Check(vv)) {
1337 PyNumberMethods *nb;
1338 nb = vv->ob_type->tp_as_number;
1339 if (nb == NULL || nb->nb_int == NULL) {
1340 PyErr_SetString(PyExc_TypeError,
1341 "an integer is required");
1342 return -1;
1343 }
1344 vv = (*nb->nb_int) (vv);
1345 if (vv == NULL)
1346 return -1;
1347 do_decref = 1;
1348 if (!PyLong_Check(vv)) {
1349 Py_DECREF(vv);
1350 PyErr_SetString(PyExc_TypeError,
1351 "nb_int should return int object");
1352 return -1;
1353 }
1354 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 res = -1;
1357 v = (PyLongObject *)vv;
1358 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 switch (i) {
1361 case -1:
1362 res = -(sdigit)v->ob_digit[0];
1363 break;
1364 case 0:
1365 res = 0;
1366 break;
1367 case 1:
1368 res = v->ob_digit[0];
1369 break;
1370 default:
1371 sign = 1;
1372 x = 0;
1373 if (i < 0) {
1374 sign = -1;
1375 i = -(i);
1376 }
1377 while (--i >= 0) {
1378 prev = x;
1379 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1380 if ((x >> PyLong_SHIFT) != prev) {
1381 *overflow = sign;
1382 goto exit;
1383 }
1384 }
1385 /* Haven't lost any bits, but casting to long requires extra
1386 * care (see comment above).
1387 */
1388 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1389 res = (PY_LONG_LONG)x * sign;
1390 }
1391 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1392 res = PY_LLONG_MIN;
1393 }
1394 else {
1395 *overflow = sign;
1396 /* res is already set to -1 */
1397 }
1398 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001399 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (do_decref) {
1401 Py_DECREF(vv);
1402 }
1403 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001404}
1405
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001406#endif /* HAVE_LONG_LONG */
1407
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001408#define CHECK_BINOP(v,w) \
1409 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001410 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1411 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001412 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001413
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001414/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1415 2**k if d is nonzero, else 0. */
1416
1417static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1419 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001420};
1421
1422static int
1423bits_in_digit(digit d)
1424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 int d_bits = 0;
1426 while (d >= 32) {
1427 d_bits += 6;
1428 d >>= 6;
1429 }
1430 d_bits += (int)BitLengthTable[d];
1431 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001432}
1433
Tim Peters877a2122002-08-12 05:09:36 +00001434/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1435 * is modified in place, by adding y to it. Carries are propagated as far as
1436 * x[m-1], and the remaining carry (0 or 1) is returned.
1437 */
1438static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001439v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 Py_ssize_t i;
1442 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 assert(m >= n);
1445 for (i = 0; i < n; ++i) {
1446 carry += x[i] + y[i];
1447 x[i] = carry & PyLong_MASK;
1448 carry >>= PyLong_SHIFT;
1449 assert((carry & 1) == carry);
1450 }
1451 for (; carry && i < m; ++i) {
1452 carry += x[i];
1453 x[i] = carry & PyLong_MASK;
1454 carry >>= PyLong_SHIFT;
1455 assert((carry & 1) == carry);
1456 }
1457 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001458}
1459
1460/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1461 * is modified in place, by subtracting y from it. Borrows are propagated as
1462 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1463 */
1464static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001465v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 Py_ssize_t i;
1468 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 assert(m >= n);
1471 for (i = 0; i < n; ++i) {
1472 borrow = x[i] - y[i] - borrow;
1473 x[i] = borrow & PyLong_MASK;
1474 borrow >>= PyLong_SHIFT;
1475 borrow &= 1; /* keep only 1 sign bit */
1476 }
1477 for (; borrow && i < m; ++i) {
1478 borrow = x[i] - borrow;
1479 x[i] = borrow & PyLong_MASK;
1480 borrow >>= PyLong_SHIFT;
1481 borrow &= 1;
1482 }
1483 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001484}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001485
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001486/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1487 * result in z[0:m], and return the d bits shifted out of the top.
1488 */
1489static digit
1490v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_ssize_t i;
1493 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 assert(0 <= d && d < PyLong_SHIFT);
1496 for (i=0; i < m; i++) {
1497 twodigits acc = (twodigits)a[i] << d | carry;
1498 z[i] = (digit)acc & PyLong_MASK;
1499 carry = (digit)(acc >> PyLong_SHIFT);
1500 }
1501 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001502}
1503
1504/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1505 * result in z[0:m], and return the d bits shifted out of the bottom.
1506 */
1507static digit
1508v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 Py_ssize_t i;
1511 digit carry = 0;
1512 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 assert(0 <= d && d < PyLong_SHIFT);
1515 for (i=m; i-- > 0;) {
1516 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1517 carry = (digit)acc & mask;
1518 z[i] = (digit)(acc >> d);
1519 }
1520 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001521}
1522
Tim Peters212e6142001-07-14 12:23:19 +00001523/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1524 in pout, and returning the remainder. pin and pout point at the LSD.
1525 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001526 _PyLong_Format, but that should be done with great care since longs are
Tim Peters212e6142001-07-14 12:23:19 +00001527 immutable. */
1528
1529static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001530inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 assert(n > 0 && n <= PyLong_MASK);
1535 pin += size;
1536 pout += size;
1537 while (--size >= 0) {
1538 digit hi;
1539 rem = (rem << PyLong_SHIFT) | *--pin;
1540 *--pout = hi = (digit)(rem / n);
1541 rem -= (twodigits)hi * n;
1542 }
1543 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001544}
1545
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001546/* Divide a long integer by a digit, returning both the quotient
1547 (as function result) and the remainder (through *prem).
1548 The sign of a is ignored; n should not be zero. */
1549
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001550static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001551divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 const Py_ssize_t size = ABS(Py_SIZE(a));
1554 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 assert(n > 0 && n <= PyLong_MASK);
1557 z = _PyLong_New(size);
1558 if (z == NULL)
1559 return NULL;
1560 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1561 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001562}
1563
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001564/* Convert a long integer to a base 10 string. Returns a new non-shared
1565 string. (Return value is non-shared so that callers can modify the
1566 returned value if necessary.) */
1567
Victor Stinnerd3f08822012-05-29 12:57:52 +02001568static int
1569long_to_decimal_string_internal(PyObject *aa,
1570 PyObject **p_output,
1571 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 PyLongObject *scratch, *a;
1574 PyObject *str;
1575 Py_ssize_t size, strlen, size_a, i, j;
1576 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001578 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 a = (PyLongObject *)aa;
1581 if (a == NULL || !PyLong_Check(a)) {
1582 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001583 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 }
1585 size_a = ABS(Py_SIZE(a));
1586 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* quick and dirty upper bound for the number of digits
1589 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 But log2(a) < size_a * PyLong_SHIFT, and
1594 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1595 > 3 * _PyLong_DECIMAL_SHIFT
1596 */
1597 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1598 PyErr_SetString(PyExc_OverflowError,
1599 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001600 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
1602 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1603 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1604 scratch = _PyLong_New(size);
1605 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001606 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 /* convert array of base _PyLong_BASE digits in pin to an array of
1609 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1610 Volume 2 (3rd edn), section 4.4, Method 1b). */
1611 pin = a->ob_digit;
1612 pout = scratch->ob_digit;
1613 size = 0;
1614 for (i = size_a; --i >= 0; ) {
1615 digit hi = pin[i];
1616 for (j = 0; j < size; j++) {
1617 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1618 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1619 pout[j] = (digit)(z - (twodigits)hi *
1620 _PyLong_DECIMAL_BASE);
1621 }
1622 while (hi) {
1623 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1624 hi /= _PyLong_DECIMAL_BASE;
1625 }
1626 /* check for keyboard interrupt */
1627 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001628 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001629 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001630 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 }
1632 /* pout should have at least one digit, so that the case when a = 0
1633 works correctly */
1634 if (size == 0)
1635 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 /* calculate exact length of output string, and allocate */
1638 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1639 tenpow = 10;
1640 rem = pout[size-1];
1641 while (rem >= tenpow) {
1642 tenpow *= 10;
1643 strlen++;
1644 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001645 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001646 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1647 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001648 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001649 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001650 kind = writer->kind;
1651 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001653 else {
1654 str = PyUnicode_New(strlen, '9');
1655 if (str == NULL) {
1656 Py_DECREF(scratch);
1657 return -1;
1658 }
1659 kind = PyUnicode_KIND(str);
1660 }
1661
1662#define WRITE_DIGITS(TYPE) \
1663 do { \
1664 if (writer) \
1665 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1666 else \
1667 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1668 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001669 /* pout[0] through pout[size-2] contribute exactly \
1670 _PyLong_DECIMAL_SHIFT digits each */ \
1671 for (i=0; i < size - 1; i++) { \
1672 rem = pout[i]; \
1673 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1674 *--p = '0' + rem % 10; \
1675 rem /= 10; \
1676 } \
1677 } \
1678 /* pout[size-1]: always produce at least one decimal digit */ \
1679 rem = pout[i]; \
1680 do { \
1681 *--p = '0' + rem % 10; \
1682 rem /= 10; \
1683 } while (rem != 0); \
1684 \
1685 /* and sign */ \
1686 if (negative) \
1687 *--p = '-'; \
1688 \
1689 /* check we've counted correctly */ \
1690 if (writer) \
1691 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1692 else \
1693 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1694 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001697 if (kind == PyUnicode_1BYTE_KIND) {
1698 Py_UCS1 *p;
1699 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001701 else if (kind == PyUnicode_2BYTE_KIND) {
1702 Py_UCS2 *p;
1703 WRITE_DIGITS(Py_UCS2);
1704 }
1705 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001706 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001707 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 WRITE_DIGITS(Py_UCS4);
1709 }
1710#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001713 if (writer) {
1714 writer->pos += strlen;
1715 }
1716 else {
1717 assert(_PyUnicode_CheckConsistency(str, 1));
1718 *p_output = (PyObject *)str;
1719 }
1720 return 0;
1721}
1722
1723static PyObject *
1724long_to_decimal_string(PyObject *aa)
1725{
1726 PyObject *v;
1727 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1728 return NULL;
1729 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001730}
1731
Mark Dickinsoncd068122009-09-18 14:53:08 +00001732/* Convert a long int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 which should be one of 2, 8 or 16. Return a string object.
1734 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1735 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001736
Victor Stinnerd3f08822012-05-29 12:57:52 +02001737static int
1738long_format_binary(PyObject *aa, int base, int alternate,
1739 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001743 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001745 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001746 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001748
Victor Stinnerd3f08822012-05-29 12:57:52 +02001749 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (a == NULL || !PyLong_Check(a)) {
1751 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001752 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 }
1754 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001755 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 /* Compute a rough upper bound for the length of the string */
1758 switch (base) {
1759 case 16:
1760 bits = 4;
1761 break;
1762 case 8:
1763 bits = 3;
1764 break;
1765 case 2:
1766 bits = 1;
1767 break;
1768 default:
1769 assert(0); /* shouldn't ever get here */
1770 bits = 0; /* to silence gcc warning */
1771 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001772
Mark Dickinsone2846542012-04-20 21:21:24 +01001773 /* Compute exact length 'sz' of output string. */
1774 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001775 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001776 }
1777 else {
1778 Py_ssize_t size_a_in_bits;
1779 /* Ensure overflow doesn't occur during computation of sz. */
1780 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1781 PyErr_SetString(PyExc_OverflowError,
1782 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001783 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001784 }
1785 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1786 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001787 /* Allow 1 character for a '-' sign. */
1788 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1789 }
1790 if (alternate) {
1791 /* 2 characters for prefix */
1792 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001793 }
1794
Victor Stinnerd3f08822012-05-29 12:57:52 +02001795 if (writer) {
1796 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1797 return -1;
1798 kind = writer->kind;
1799 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 }
1801 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001802 v = PyUnicode_New(sz, 'x');
1803 if (v == NULL)
1804 return -1;
1805 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001807
Victor Stinnerd3f08822012-05-29 12:57:52 +02001808#define WRITE_DIGITS(TYPE) \
1809 do { \
1810 if (writer) \
1811 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1812 else \
1813 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1814 \
1815 if (size_a == 0) { \
1816 *--p = '0'; \
1817 } \
1818 else { \
1819 /* JRH: special case for power-of-2 bases */ \
1820 twodigits accum = 0; \
1821 int accumbits = 0; /* # of bits in accum */ \
1822 Py_ssize_t i; \
1823 for (i = 0; i < size_a; ++i) { \
1824 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1825 accumbits += PyLong_SHIFT; \
1826 assert(accumbits >= bits); \
1827 do { \
1828 char cdigit; \
1829 cdigit = (char)(accum & (base - 1)); \
1830 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1831 *--p = cdigit; \
1832 accumbits -= bits; \
1833 accum >>= bits; \
1834 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1835 } \
1836 } \
1837 \
1838 if (alternate) { \
1839 if (base == 16) \
1840 *--p = 'x'; \
1841 else if (base == 8) \
1842 *--p = 'o'; \
1843 else /* (base == 2) */ \
1844 *--p = 'b'; \
1845 *--p = '0'; \
1846 } \
1847 if (negative) \
1848 *--p = '-'; \
1849 if (writer) \
1850 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1851 else \
1852 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1853 } while (0)
1854
1855 if (kind == PyUnicode_1BYTE_KIND) {
1856 Py_UCS1 *p;
1857 WRITE_DIGITS(Py_UCS1);
1858 }
1859 else if (kind == PyUnicode_2BYTE_KIND) {
1860 Py_UCS2 *p;
1861 WRITE_DIGITS(Py_UCS2);
1862 }
1863 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001864 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001865 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001866 WRITE_DIGITS(Py_UCS4);
1867 }
1868#undef WRITE_DIGITS
1869
1870 if (writer) {
1871 writer->pos += sz;
1872 }
1873 else {
1874 assert(_PyUnicode_CheckConsistency(v, 1));
1875 *p_output = v;
1876 }
1877 return 0;
1878}
1879
1880PyObject *
1881_PyLong_Format(PyObject *obj, int base)
1882{
1883 PyObject *str;
1884 int err;
1885 if (base == 10)
1886 err = long_to_decimal_string_internal(obj, &str, NULL);
1887 else
1888 err = long_format_binary(obj, base, 1, &str, NULL);
1889 if (err == -1)
1890 return NULL;
1891 return str;
1892}
1893
1894int
1895_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1896 PyObject *obj,
1897 int base, int alternate)
1898{
1899 if (base == 10)
1900 return long_to_decimal_string_internal(obj, NULL, writer);
1901 else
1902 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001903}
1904
Thomas Wouters477c8d52006-05-27 19:21:47 +00001905/* Table of digit values for 8-bit string -> integer conversion.
1906 * '0' maps to 0, ..., '9' maps to 9.
1907 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1908 * All other indices map to 37.
1909 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001910 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001912unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 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,
1915 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1916 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1917 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1918 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1919 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1920 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1921 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1922 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1923 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1924 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1925 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1926 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1927 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1928 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929};
1930
1931/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001932 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
1933 * non-digit (which may be *str!). A normalized long is returned.
1934 * The point to this routine is that it takes time linear in the number of
1935 * string characters.
1936 */
1937static PyLongObject *
1938long_from_binary_base(char **str, int base)
1939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 char *p = *str;
1941 char *start = p;
1942 int bits_per_char;
1943 Py_ssize_t n;
1944 PyLongObject *z;
1945 twodigits accum;
1946 int bits_in_accum;
1947 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1950 n = base;
1951 for (bits_per_char = -1; n; ++bits_per_char)
1952 n >>= 1;
1953 /* n <- total # of bits needed, while setting p to end-of-string */
1954 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1955 ++p;
1956 *str = p;
1957 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1958 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1959 if (n / bits_per_char < p - start) {
1960 PyErr_SetString(PyExc_ValueError,
1961 "int string too large to convert");
1962 return NULL;
1963 }
1964 n = n / PyLong_SHIFT;
1965 z = _PyLong_New(n);
1966 if (z == NULL)
1967 return NULL;
1968 /* Read string from right, and fill in long from left; i.e.,
1969 * from least to most significant in both.
1970 */
1971 accum = 0;
1972 bits_in_accum = 0;
1973 pdigit = z->ob_digit;
1974 while (--p >= start) {
1975 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1976 assert(k >= 0 && k < base);
1977 accum |= (twodigits)k << bits_in_accum;
1978 bits_in_accum += bits_per_char;
1979 if (bits_in_accum >= PyLong_SHIFT) {
1980 *pdigit++ = (digit)(accum & PyLong_MASK);
1981 assert(pdigit - z->ob_digit <= n);
1982 accum >>= PyLong_SHIFT;
1983 bits_in_accum -= PyLong_SHIFT;
1984 assert(bits_in_accum < PyLong_SHIFT);
1985 }
1986 }
1987 if (bits_in_accum) {
1988 assert(bits_in_accum <= PyLong_SHIFT);
1989 *pdigit++ = (digit)accum;
1990 assert(pdigit - z->ob_digit <= n);
1991 }
1992 while (pdigit - z->ob_digit < n)
1993 *pdigit++ = 0;
1994 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00001995}
1996
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001997PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001998PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00001999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 int sign = 1, error_if_nonzero = 0;
2001 char *start, *orig_str = str;
2002 PyLongObject *z = NULL;
2003 PyObject *strobj;
2004 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if ((base != 0 && base < 2) || base > 36) {
2007 PyErr_SetString(PyExc_ValueError,
2008 "int() arg 2 must be >= 2 and <= 36");
2009 return NULL;
2010 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002011 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 str++;
2013 if (*str == '+')
2014 ++str;
2015 else if (*str == '-') {
2016 ++str;
2017 sign = -1;
2018 }
2019 if (base == 0) {
2020 if (str[0] != '0')
2021 base = 10;
2022 else if (str[1] == 'x' || str[1] == 'X')
2023 base = 16;
2024 else if (str[1] == 'o' || str[1] == 'O')
2025 base = 8;
2026 else if (str[1] == 'b' || str[1] == 'B')
2027 base = 2;
2028 else {
2029 /* "old" (C-style) octal literal, now invalid.
2030 it might still be zero though */
2031 error_if_nonzero = 1;
2032 base = 10;
2033 }
2034 }
2035 if (str[0] == '0' &&
2036 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2037 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2038 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2039 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 start = str;
2042 if ((base & (base - 1)) == 0)
2043 z = long_from_binary_base(&str, base);
2044 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002045/***
2046Binary bases can be converted in time linear in the number of digits, because
2047Python's representation base is binary. Other bases (including decimal!) use
2048the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002049
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050First some math: the largest integer that can be expressed in N base-B digits
2051is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2052case number of Python digits needed to hold it is the smallest integer n s.t.
2053
2054 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2055 BASE**n >= B**N [taking logs to base BASE]
2056 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2057
2058The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
2059this quickly. A Python long with that much space is reserved near the start,
2060and the result is computed into it.
2061
2062The input string is actually treated as being in base base**i (i.e., i digits
2063are processed at a time), where two more static arrays hold:
2064
2065 convwidth_base[base] = the largest integer i such that base**i <= BASE
2066 convmultmax_base[base] = base ** convwidth_base[base]
2067
2068The first of these is the largest i such that i consecutive input digits
2069must fit in a single Python digit. The second is effectively the input
2070base we're really using.
2071
2072Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2073convmultmax_base[base], the result is "simply"
2074
2075 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2076
2077where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002078
2079Error analysis: as above, the number of Python digits `n` needed is worst-
2080case
2081
2082 n >= N * log(B)/log(BASE)
2083
2084where `N` is the number of input digits in base `B`. This is computed via
2085
2086 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2087
2088below. Two numeric concerns are how much space this can waste, and whether
2089the computed result can be too small. To be concrete, assume BASE = 2**15,
2090which is the default (and it's unlikely anyone changes that).
2091
2092Waste isn't a problem: provided the first input digit isn't 0, the difference
2093between the worst-case input with N digits and the smallest input with N
2094digits is about a factor of B, but B is small compared to BASE so at most
2095one allocated Python digit can remain unused on that count. If
2096N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2097and adding 1 returns a result 1 larger than necessary. However, that can't
2098happen: whenever B is a power of 2, long_from_binary_base() is called
2099instead, and it's impossible for B**i to be an integer power of 2**15 when
2100B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2101an exact integer when B is not a power of 2, since B**i has a prime factor
2102other than 2 in that case, but (2**15)**j's only prime factor is 2).
2103
2104The computed result can be too small if the true value of N*log(B)/log(BASE)
2105is a little bit larger than an exact integer, but due to roundoff errors (in
2106computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2107yields a numeric result a little less than that integer. Unfortunately, "how
2108close can a transcendental function get to an integer over some range?"
2109questions are generally theoretically intractable. Computer analysis via
2110continued fractions is practical: expand log(B)/log(BASE) via continued
2111fractions, giving a sequence i/j of "the best" rational approximations. Then
2112j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2113we can get very close to being in trouble, but very rarely. For example,
211476573 is a denominator in one of the continued-fraction approximations to
2115log(10)/log(2**15), and indeed:
2116
2117 >>> log(10)/log(2**15)*76573
2118 16958.000000654003
2119
2120is very close to an integer. If we were working with IEEE single-precision,
2121rounding errors could kill us. Finding worst cases in IEEE double-precision
2122requires better-than-double-precision log() functions, and Tim didn't bother.
2123Instead the code checks to see whether the allocated space is enough as each
2124new Python digit is added, and copies the whole thing to a larger long if not.
2125This should happen extremely rarely, and in fact I don't have a test case
2126that triggers it(!). Instead the code was tested by artificially allocating
2127just 1 digit at the start, so that the copying code was exercised for every
2128digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 register twodigits c; /* current input character */
2131 Py_ssize_t size_z;
2132 int i;
2133 int convwidth;
2134 twodigits convmultmax, convmult;
2135 digit *pz, *pzstop;
2136 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 static double log_base_BASE[37] = {0.0e0,};
2139 static int convwidth_base[37] = {0,};
2140 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (log_base_BASE[base] == 0.0) {
2143 twodigits convmax = base;
2144 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002145
Mark Dickinson22b20182010-05-10 21:27:53 +00002146 log_base_BASE[base] = (log((double)base) /
2147 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 for (;;) {
2149 twodigits next = convmax * base;
2150 if (next > PyLong_BASE)
2151 break;
2152 convmax = next;
2153 ++i;
2154 }
2155 convmultmax_base[base] = convmax;
2156 assert(i > 0);
2157 convwidth_base[base] = i;
2158 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* Find length of the string of numeric characters. */
2161 scan = str;
2162 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2163 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* Create a long object that can contain the largest possible
2166 * integer with this base and length. Note that there's no
2167 * need to initialize z->ob_digit -- no slot is read up before
2168 * being stored into.
2169 */
2170 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2171 /* Uncomment next line to test exceedingly rare copy code */
2172 /* size_z = 1; */
2173 assert(size_z > 0);
2174 z = _PyLong_New(size_z);
2175 if (z == NULL)
2176 return NULL;
2177 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* `convwidth` consecutive input digits are treated as a single
2180 * digit in base `convmultmax`.
2181 */
2182 convwidth = convwidth_base[base];
2183 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* Work ;-) */
2186 while (str < scan) {
2187 /* grab up to convwidth digits from the input string */
2188 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2189 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2190 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002191 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 assert(c < PyLong_BASE);
2193 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 convmult = convmultmax;
2196 /* Calculate the shift only if we couldn't get
2197 * convwidth digits.
2198 */
2199 if (i != convwidth) {
2200 convmult = base;
2201 for ( ; i > 1; --i)
2202 convmult *= base;
2203 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* Multiply z by convmult, and add c. */
2206 pz = z->ob_digit;
2207 pzstop = pz + Py_SIZE(z);
2208 for (; pz < pzstop; ++pz) {
2209 c += (twodigits)*pz * convmult;
2210 *pz = (digit)(c & PyLong_MASK);
2211 c >>= PyLong_SHIFT;
2212 }
2213 /* carry off the current end? */
2214 if (c) {
2215 assert(c < PyLong_BASE);
2216 if (Py_SIZE(z) < size_z) {
2217 *pz = (digit)c;
2218 ++Py_SIZE(z);
2219 }
2220 else {
2221 PyLongObject *tmp;
2222 /* Extremely rare. Get more space. */
2223 assert(Py_SIZE(z) == size_z);
2224 tmp = _PyLong_New(size_z + 1);
2225 if (tmp == NULL) {
2226 Py_DECREF(z);
2227 return NULL;
2228 }
2229 memcpy(tmp->ob_digit,
2230 z->ob_digit,
2231 sizeof(digit) * size_z);
2232 Py_DECREF(z);
2233 z = tmp;
2234 z->ob_digit[size_z] = (digit)c;
2235 ++size_z;
2236 }
2237 }
2238 }
2239 }
2240 if (z == NULL)
2241 return NULL;
2242 if (error_if_nonzero) {
2243 /* reset the base to 0, else the exception message
2244 doesn't make too much sense */
2245 base = 0;
2246 if (Py_SIZE(z) != 0)
2247 goto onError;
2248 /* there might still be other problems, therefore base
2249 remains zero here for the same reason */
2250 }
2251 if (str == start)
2252 goto onError;
2253 if (sign < 0)
2254 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002255 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 str++;
2257 if (*str != '\0')
2258 goto onError;
2259 if (pend)
2260 *pend = str;
2261 long_normalize(z);
2262 return (PyObject *) maybe_small_long(z);
Guido van Rossum9e896b32000-04-05 20:11:21 +00002263
Mark Dickinson22b20182010-05-10 21:27:53 +00002264 onError:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 Py_XDECREF(z);
2266 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2267 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2268 if (strobj == NULL)
2269 return NULL;
2270 PyErr_Format(PyExc_ValueError,
2271 "invalid literal for int() with base %d: %R",
2272 base, strobj);
2273 Py_DECREF(strobj);
2274 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002275}
2276
2277PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002278PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002280 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2281 if (unicode == NULL)
2282 return NULL;
2283 v = PyLong_FromUnicodeObject(unicode, base);
2284 Py_DECREF(unicode);
2285 return v;
2286}
2287
2288PyObject *
2289PyLong_FromUnicodeObject(PyObject *u, int base)
2290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyObject *result;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002292 PyObject *asciidig;
2293 char *buffer, *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002294 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002296 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002297 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002299 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002300 if (buffer == NULL) {
2301 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 return NULL;
2303 }
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002304 result = PyLong_FromString(buffer, &end, base);
2305 if (result != NULL && end != buffer + buflen) {
2306 PyErr_SetString(PyExc_ValueError,
2307 "null byte in argument for int()");
2308 Py_DECREF(result);
2309 result = NULL;
2310 }
2311 Py_DECREF(asciidig);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 return result;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002313}
2314
Tim Peters9f688bf2000-07-07 15:53:28 +00002315/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002316static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002318static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002319
2320/* Long division with remainder, top-level routine */
2321
Guido van Rossume32e0141992-01-19 16:31:05 +00002322static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002323long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2327 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 if (size_b == 0) {
2330 PyErr_SetString(PyExc_ZeroDivisionError,
2331 "integer division or modulo by zero");
2332 return -1;
2333 }
2334 if (size_a < size_b ||
2335 (size_a == size_b &&
2336 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2337 /* |a| < |b|. */
2338 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2339 if (*pdiv == NULL)
2340 return -1;
2341 Py_INCREF(a);
2342 *prem = (PyLongObject *) a;
2343 return 0;
2344 }
2345 if (size_b == 1) {
2346 digit rem = 0;
2347 z = divrem1(a, b->ob_digit[0], &rem);
2348 if (z == NULL)
2349 return -1;
2350 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2351 if (*prem == NULL) {
2352 Py_DECREF(z);
2353 return -1;
2354 }
2355 }
2356 else {
2357 z = x_divrem(a, b, prem);
2358 if (z == NULL)
2359 return -1;
2360 }
2361 /* Set the signs.
2362 The quotient z has the sign of a*b;
2363 the remainder r has the sign of a,
2364 so a = b*z + r. */
2365 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2366 NEGATE(z);
2367 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2368 NEGATE(*prem);
2369 *pdiv = maybe_small_long(z);
2370 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002371}
2372
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002373/* Unsigned long division with remainder -- the algorithm. The arguments v1
2374 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002376static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002377x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyLongObject *v, *w, *a;
2380 Py_ssize_t i, k, size_v, size_w;
2381 int d;
2382 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2383 twodigits vv;
2384 sdigit zhi;
2385 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2388 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2389 handle the special case when the initial estimate q for a quotient
2390 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2391 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* allocate space; w will also be used to hold the final remainder */
2394 size_v = ABS(Py_SIZE(v1));
2395 size_w = ABS(Py_SIZE(w1));
2396 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2397 v = _PyLong_New(size_v+1);
2398 if (v == NULL) {
2399 *prem = NULL;
2400 return NULL;
2401 }
2402 w = _PyLong_New(size_w);
2403 if (w == NULL) {
2404 Py_DECREF(v);
2405 *prem = NULL;
2406 return NULL;
2407 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2410 shift v1 left by the same amount. Results go into w and v. */
2411 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2412 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2413 assert(carry == 0);
2414 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2415 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2416 v->ob_digit[size_v] = carry;
2417 size_v++;
2418 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2421 at most (and usually exactly) k = size_v - size_w digits. */
2422 k = size_v - size_w;
2423 assert(k >= 0);
2424 a = _PyLong_New(k);
2425 if (a == NULL) {
2426 Py_DECREF(w);
2427 Py_DECREF(v);
2428 *prem = NULL;
2429 return NULL;
2430 }
2431 v0 = v->ob_digit;
2432 w0 = w->ob_digit;
2433 wm1 = w0[size_w-1];
2434 wm2 = w0[size_w-2];
2435 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2436 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2437 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002440 Py_DECREF(a);
2441 Py_DECREF(w);
2442 Py_DECREF(v);
2443 *prem = NULL;
2444 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002445 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* estimate quotient digit q; may overestimate by 1 (rare) */
2448 vtop = vk[size_w];
2449 assert(vtop <= wm1);
2450 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2451 q = (digit)(vv / wm1);
2452 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2453 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2454 | vk[size_w-2])) {
2455 --q;
2456 r += wm1;
2457 if (r >= PyLong_BASE)
2458 break;
2459 }
2460 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2463 zhi = 0;
2464 for (i = 0; i < size_w; ++i) {
2465 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2466 -PyLong_BASE * q <= z < PyLong_BASE */
2467 z = (sdigit)vk[i] + zhi -
2468 (stwodigits)q * (stwodigits)w0[i];
2469 vk[i] = (digit)z & PyLong_MASK;
2470 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002471 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 /* add w back if q was too large (this branch taken rarely) */
2475 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2476 if ((sdigit)vtop + zhi < 0) {
2477 carry = 0;
2478 for (i = 0; i < size_w; ++i) {
2479 carry += vk[i] + w0[i];
2480 vk[i] = carry & PyLong_MASK;
2481 carry >>= PyLong_SHIFT;
2482 }
2483 --q;
2484 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* store quotient digit */
2487 assert(q < PyLong_BASE);
2488 *--ak = q;
2489 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 /* unshift remainder; we reuse w to store the result */
2492 carry = v_rshift(w0, v0, size_w, d);
2493 assert(carry==0);
2494 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 *prem = long_normalize(w);
2497 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002498}
2499
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002500/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2501 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2502 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2503 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2504 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2505 -1.0. */
2506
2507/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2508#if DBL_MANT_DIG == 53
2509#define EXP2_DBL_MANT_DIG 9007199254740992.0
2510#else
2511#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2512#endif
2513
2514double
2515_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2518 /* See below for why x_digits is always large enough. */
2519 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2520 double dx;
2521 /* Correction term for round-half-to-even rounding. For a digit x,
2522 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2523 multiple of 4, rounding ties to a multiple of 8. */
2524 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 a_size = ABS(Py_SIZE(a));
2527 if (a_size == 0) {
2528 /* Special case for 0: significand 0.0, exponent 0. */
2529 *e = 0;
2530 return 0.0;
2531 }
2532 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2533 /* The following is an overflow-free version of the check
2534 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2535 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2536 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2537 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002538 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2542 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 Number of digits needed for result: write // for floor division.
2545 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2554 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2557 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2558 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 in both cases.
2565 */
2566 if (a_bits <= DBL_MANT_DIG + 2) {
2567 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2568 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2569 x_size = 0;
2570 while (x_size < shift_digits)
2571 x_digits[x_size++] = 0;
2572 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2573 (int)shift_bits);
2574 x_size += a_size;
2575 x_digits[x_size++] = rem;
2576 }
2577 else {
2578 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2579 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2580 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2581 a_size - shift_digits, (int)shift_bits);
2582 x_size = a_size - shift_digits;
2583 /* For correct rounding below, we need the least significant
2584 bit of x to be 'sticky' for this shift: if any of the bits
2585 shifted out was nonzero, we set the least significant bit
2586 of x. */
2587 if (rem)
2588 x_digits[0] |= 1;
2589 else
2590 while (shift_digits > 0)
2591 if (a->ob_digit[--shift_digits]) {
2592 x_digits[0] |= 1;
2593 break;
2594 }
2595 }
Victor Stinner63941882011-09-29 00:42:28 +02002596 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 /* Round, and convert to double. */
2599 x_digits[0] += half_even_correction[x_digits[0] & 7];
2600 dx = x_digits[--x_size];
2601 while (x_size > 0)
2602 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 /* Rescale; make correction if result is 1.0. */
2605 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2606 if (dx == 1.0) {
2607 if (a_bits == PY_SSIZE_T_MAX)
2608 goto overflow;
2609 dx = 0.5;
2610 a_bits += 1;
2611 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 *e = a_bits;
2614 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002615
2616 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 /* exponent > PY_SSIZE_T_MAX */
2618 PyErr_SetString(PyExc_OverflowError,
2619 "huge integer: number of bits overflows a Py_ssize_t");
2620 *e = 0;
2621 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002622}
2623
2624/* Get a C double from a long int object. Rounds to the nearest double,
2625 using the round-half-to-even rule in the case of a tie. */
2626
2627double
2628PyLong_AsDouble(PyObject *v)
2629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 Py_ssize_t exponent;
2631 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002632
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002633 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 PyErr_BadInternalCall();
2635 return -1.0;
2636 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002637 if (!PyLong_Check(v)) {
2638 PyErr_SetString(PyExc_TypeError, "an integer is required");
2639 return -1.0;
2640 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2642 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2643 PyErr_SetString(PyExc_OverflowError,
2644 "long int too large to convert to float");
2645 return -1.0;
2646 }
2647 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002648}
2649
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002650/* Methods */
2651
2652static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002653long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002656}
2657
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002658static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002659long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 if (Py_SIZE(a) != Py_SIZE(b)) {
2664 sign = Py_SIZE(a) - Py_SIZE(b);
2665 }
2666 else {
2667 Py_ssize_t i = ABS(Py_SIZE(a));
2668 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2669 ;
2670 if (i < 0)
2671 sign = 0;
2672 else {
2673 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2674 if (Py_SIZE(a) < 0)
2675 sign = -sign;
2676 }
2677 }
2678 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002679}
2680
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002681#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002683
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002684static PyObject *
2685long_richcompare(PyObject *self, PyObject *other, int op)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 int result;
2688 PyObject *v;
2689 CHECK_BINOP(self, other);
2690 if (self == other)
2691 result = 0;
2692 else
2693 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2694 /* Convert the return value to a Boolean */
2695 switch (op) {
2696 case Py_EQ:
2697 v = TEST_COND(result == 0);
2698 break;
2699 case Py_NE:
2700 v = TEST_COND(result != 0);
2701 break;
2702 case Py_LE:
2703 v = TEST_COND(result <= 0);
2704 break;
2705 case Py_GE:
2706 v = TEST_COND(result >= 0);
2707 break;
2708 case Py_LT:
2709 v = TEST_COND(result == -1);
2710 break;
2711 case Py_GT:
2712 v = TEST_COND(result == 1);
2713 break;
2714 default:
2715 PyErr_BadArgument();
2716 return NULL;
2717 }
2718 Py_INCREF(v);
2719 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002720}
2721
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002722static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002723long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002724{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002725 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 Py_ssize_t i;
2727 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 i = Py_SIZE(v);
2730 switch(i) {
2731 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2732 case 0: return 0;
2733 case 1: return v->ob_digit[0];
2734 }
2735 sign = 1;
2736 x = 0;
2737 if (i < 0) {
2738 sign = -1;
2739 i = -(i);
2740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002742 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2743 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2744 _PyHASH_MODULUS.
2745
2746 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2747 amounts to a rotation of the bits of x. To see this, write
2748
2749 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2750
2751 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2752 PyLong_SHIFT bits of x (those that are shifted out of the
2753 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2754 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2755 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2756 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2757 congruent to y modulo _PyHASH_MODULUS. So
2758
2759 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2760
2761 The right-hand side is just the result of rotating the
2762 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2763 not all _PyHASH_BITS bits of x are 1s, the same is true
2764 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2765 the reduction of x*2**PyLong_SHIFT modulo
2766 _PyHASH_MODULUS. */
2767 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2768 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002770 if (x >= _PyHASH_MODULUS)
2771 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 }
2773 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002774 if (x == (Py_uhash_t)-1)
2775 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002776 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002777}
2778
2779
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002780/* Add the absolute values of two long integers. */
2781
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002782static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002783x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2786 PyLongObject *z;
2787 Py_ssize_t i;
2788 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 /* Ensure a is the larger of the two: */
2791 if (size_a < size_b) {
2792 { PyLongObject *temp = a; a = b; b = temp; }
2793 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002794 size_a = size_b;
2795 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 }
2797 z = _PyLong_New(size_a+1);
2798 if (z == NULL)
2799 return NULL;
2800 for (i = 0; i < size_b; ++i) {
2801 carry += a->ob_digit[i] + b->ob_digit[i];
2802 z->ob_digit[i] = carry & PyLong_MASK;
2803 carry >>= PyLong_SHIFT;
2804 }
2805 for (; i < size_a; ++i) {
2806 carry += a->ob_digit[i];
2807 z->ob_digit[i] = carry & PyLong_MASK;
2808 carry >>= PyLong_SHIFT;
2809 }
2810 z->ob_digit[i] = carry;
2811 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002812}
2813
2814/* Subtract the absolute values of two integers. */
2815
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002816static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002817x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2820 PyLongObject *z;
2821 Py_ssize_t i;
2822 int sign = 1;
2823 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* Ensure a is the larger of the two: */
2826 if (size_a < size_b) {
2827 sign = -1;
2828 { PyLongObject *temp = a; a = b; b = temp; }
2829 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002830 size_a = size_b;
2831 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 }
2833 else if (size_a == size_b) {
2834 /* Find highest digit where a and b differ: */
2835 i = size_a;
2836 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2837 ;
2838 if (i < 0)
2839 return (PyLongObject *)PyLong_FromLong(0);
2840 if (a->ob_digit[i] < b->ob_digit[i]) {
2841 sign = -1;
2842 { PyLongObject *temp = a; a = b; b = temp; }
2843 }
2844 size_a = size_b = i+1;
2845 }
2846 z = _PyLong_New(size_a);
2847 if (z == NULL)
2848 return NULL;
2849 for (i = 0; i < size_b; ++i) {
2850 /* The following assumes unsigned arithmetic
2851 works module 2**N for some N>PyLong_SHIFT. */
2852 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2853 z->ob_digit[i] = borrow & PyLong_MASK;
2854 borrow >>= PyLong_SHIFT;
2855 borrow &= 1; /* Keep only one sign bit */
2856 }
2857 for (; i < size_a; ++i) {
2858 borrow = a->ob_digit[i] - borrow;
2859 z->ob_digit[i] = borrow & PyLong_MASK;
2860 borrow >>= PyLong_SHIFT;
2861 borrow &= 1; /* Keep only one sign bit */
2862 }
2863 assert(borrow == 0);
2864 if (sign < 0)
2865 NEGATE(z);
2866 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002867}
2868
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002869static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002870long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2877 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2878 MEDIUM_VALUE(b));
2879 return result;
2880 }
2881 if (Py_SIZE(a) < 0) {
2882 if (Py_SIZE(b) < 0) {
2883 z = x_add(a, b);
2884 if (z != NULL && Py_SIZE(z) != 0)
2885 Py_SIZE(z) = -(Py_SIZE(z));
2886 }
2887 else
2888 z = x_sub(b, a);
2889 }
2890 else {
2891 if (Py_SIZE(b) < 0)
2892 z = x_sub(a, b);
2893 else
2894 z = x_add(a, b);
2895 }
2896 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002897}
2898
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002899static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002900long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2907 PyObject* r;
2908 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2909 return r;
2910 }
2911 if (Py_SIZE(a) < 0) {
2912 if (Py_SIZE(b) < 0)
2913 z = x_sub(a, b);
2914 else
2915 z = x_add(a, b);
2916 if (z != NULL && Py_SIZE(z) != 0)
2917 Py_SIZE(z) = -(Py_SIZE(z));
2918 }
2919 else {
2920 if (Py_SIZE(b) < 0)
2921 z = x_add(a, b);
2922 else
2923 z = x_sub(a, b);
2924 }
2925 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002926}
2927
Tim Peters5af4e6c2002-08-12 02:31:19 +00002928/* Grade school multiplication, ignoring the signs.
2929 * Returns the absolute value of the product, or NULL if error.
2930 */
2931static PyLongObject *
2932x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934 PyLongObject *z;
2935 Py_ssize_t size_a = ABS(Py_SIZE(a));
2936 Py_ssize_t size_b = ABS(Py_SIZE(b));
2937 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939 z = _PyLong_New(size_a + size_b);
2940 if (z == NULL)
2941 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2944 if (a == b) {
2945 /* Efficient squaring per HAC, Algorithm 14.16:
2946 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
2947 * Gives slightly less than a 2x speedup when a == b,
2948 * via exploiting that each entry in the multiplication
2949 * pyramid appears twice (except for the size_a squares).
2950 */
2951 for (i = 0; i < size_a; ++i) {
2952 twodigits carry;
2953 twodigits f = a->ob_digit[i];
2954 digit *pz = z->ob_digit + (i << 1);
2955 digit *pa = a->ob_digit + i + 1;
2956 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002959 Py_DECREF(z);
2960 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002961 });
Tim Peters0973b992004-08-29 22:16:50 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 carry = *pz + f * f;
2964 *pz++ = (digit)(carry & PyLong_MASK);
2965 carry >>= PyLong_SHIFT;
2966 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 /* Now f is added in twice in each column of the
2969 * pyramid it appears. Same as adding f<<1 once.
2970 */
2971 f <<= 1;
2972 while (pa < paend) {
2973 carry += *pz + *pa++ * f;
2974 *pz++ = (digit)(carry & PyLong_MASK);
2975 carry >>= PyLong_SHIFT;
2976 assert(carry <= (PyLong_MASK << 1));
2977 }
2978 if (carry) {
2979 carry += *pz;
2980 *pz++ = (digit)(carry & PyLong_MASK);
2981 carry >>= PyLong_SHIFT;
2982 }
2983 if (carry)
2984 *pz += (digit)(carry & PyLong_MASK);
2985 assert((carry >> PyLong_SHIFT) == 0);
2986 }
2987 }
2988 else { /* a is not the same as b -- gradeschool long mult */
2989 for (i = 0; i < size_a; ++i) {
2990 twodigits carry = 0;
2991 twodigits f = a->ob_digit[i];
2992 digit *pz = z->ob_digit + i;
2993 digit *pb = b->ob_digit;
2994 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002997 Py_DECREF(z);
2998 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002999 });
Tim Peters0973b992004-08-29 22:16:50 +00003000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 while (pb < pbend) {
3002 carry += *pz + *pb++ * f;
3003 *pz++ = (digit)(carry & PyLong_MASK);
3004 carry >>= PyLong_SHIFT;
3005 assert(carry <= PyLong_MASK);
3006 }
3007 if (carry)
3008 *pz += (digit)(carry & PyLong_MASK);
3009 assert((carry >> PyLong_SHIFT) == 0);
3010 }
3011 }
3012 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013}
3014
3015/* A helper for Karatsuba multiplication (k_mul).
3016 Takes a long "n" and an integer "size" representing the place to
3017 split, and sets low and high such that abs(n) == (high << size) + low,
3018 viewing the shift as being by digits. The sign bit is ignored, and
3019 the return values are >= 0.
3020 Returns 0 on success, -1 on failure.
3021*/
3022static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003023kmul_split(PyLongObject *n,
3024 Py_ssize_t size,
3025 PyLongObject **high,
3026 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 PyLongObject *hi, *lo;
3029 Py_ssize_t size_lo, size_hi;
3030 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 size_lo = MIN(size_n, size);
3033 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 if ((hi = _PyLong_New(size_hi)) == NULL)
3036 return -1;
3037 if ((lo = _PyLong_New(size_lo)) == NULL) {
3038 Py_DECREF(hi);
3039 return -1;
3040 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3043 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 *high = long_normalize(hi);
3046 *low = long_normalize(lo);
3047 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003048}
3049
Tim Peters60004642002-08-12 22:01:34 +00003050static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3051
Tim Peters5af4e6c2002-08-12 02:31:19 +00003052/* Karatsuba multiplication. Ignores the input signs, and returns the
3053 * absolute value of the product (or NULL if error).
3054 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3055 */
3056static PyLongObject *
3057k_mul(PyLongObject *a, PyLongObject *b)
3058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 Py_ssize_t asize = ABS(Py_SIZE(a));
3060 Py_ssize_t bsize = ABS(Py_SIZE(b));
3061 PyLongObject *ah = NULL;
3062 PyLongObject *al = NULL;
3063 PyLongObject *bh = NULL;
3064 PyLongObject *bl = NULL;
3065 PyLongObject *ret = NULL;
3066 PyLongObject *t1, *t2, *t3;
3067 Py_ssize_t shift; /* the number of digits we split off */
3068 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3071 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3072 * Then the original product is
3073 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3074 * By picking X to be a power of 2, "*X" is just shifting, and it's
3075 * been reduced to 3 multiplies on numbers half the size.
3076 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 /* We want to split based on the larger number; fiddle so that b
3079 * is largest.
3080 */
3081 if (asize > bsize) {
3082 t1 = a;
3083 a = b;
3084 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 i = asize;
3087 asize = bsize;
3088 bsize = i;
3089 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 /* Use gradeschool math when either number is too small. */
3092 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3093 if (asize <= i) {
3094 if (asize == 0)
3095 return (PyLongObject *)PyLong_FromLong(0);
3096 else
3097 return x_mul(a, b);
3098 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 /* If a is small compared to b, splitting on b gives a degenerate
3101 * case with ah==0, and Karatsuba may be (even much) less efficient
3102 * than "grade school" then. However, we can still win, by viewing
3103 * b as a string of "big digits", each of width a->ob_size. That
3104 * leads to a sequence of balanced calls to k_mul.
3105 */
3106 if (2 * asize <= bsize)
3107 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 /* Split a & b into hi & lo pieces. */
3110 shift = bsize >> 1;
3111 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3112 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 if (a == b) {
3115 bh = ah;
3116 bl = al;
3117 Py_INCREF(bh);
3118 Py_INCREF(bl);
3119 }
3120 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 /* The plan:
3123 * 1. Allocate result space (asize + bsize digits: that's always
3124 * enough).
3125 * 2. Compute ah*bh, and copy into result at 2*shift.
3126 * 3. Compute al*bl, and copy into result at 0. Note that this
3127 * can't overlap with #2.
3128 * 4. Subtract al*bl from the result, starting at shift. This may
3129 * underflow (borrow out of the high digit), but we don't care:
3130 * we're effectively doing unsigned arithmetic mod
3131 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3132 * borrows and carries out of the high digit can be ignored.
3133 * 5. Subtract ah*bh from the result, starting at shift.
3134 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3135 * at shift.
3136 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 /* 1. Allocate result space. */
3139 ret = _PyLong_New(asize + bsize);
3140 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003141#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 /* Fill with trash, to catch reference to uninitialized digits. */
3143 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003144#endif
Tim Peters44121a62002-08-12 06:17:58 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3147 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3148 assert(Py_SIZE(t1) >= 0);
3149 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3150 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3151 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* Zero-out the digits higher than the ah*bh copy. */
3154 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3155 if (i)
3156 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3157 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* 3. t2 <- al*bl, and copy into the low digits. */
3160 if ((t2 = k_mul(al, bl)) == NULL) {
3161 Py_DECREF(t1);
3162 goto fail;
3163 }
3164 assert(Py_SIZE(t2) >= 0);
3165 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3166 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* Zero out remaining digits. */
3169 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3170 if (i)
3171 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3174 * because it's fresher in cache.
3175 */
3176 i = Py_SIZE(ret) - shift; /* # digits after shift */
3177 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3178 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3181 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3184 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3185 Py_DECREF(ah);
3186 Py_DECREF(al);
3187 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 if (a == b) {
3190 t2 = t1;
3191 Py_INCREF(t2);
3192 }
3193 else if ((t2 = x_add(bh, bl)) == NULL) {
3194 Py_DECREF(t1);
3195 goto fail;
3196 }
3197 Py_DECREF(bh);
3198 Py_DECREF(bl);
3199 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 t3 = k_mul(t1, t2);
3202 Py_DECREF(t1);
3203 Py_DECREF(t2);
3204 if (t3 == NULL) goto fail;
3205 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 /* Add t3. It's not obvious why we can't run out of room here.
3208 * See the (*) comment after this function.
3209 */
3210 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3211 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003214
Mark Dickinson22b20182010-05-10 21:27:53 +00003215 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 Py_XDECREF(ret);
3217 Py_XDECREF(ah);
3218 Py_XDECREF(al);
3219 Py_XDECREF(bh);
3220 Py_XDECREF(bl);
3221 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003222}
3223
Tim Petersd6974a52002-08-13 20:37:51 +00003224/* (*) Why adding t3 can't "run out of room" above.
3225
Tim Petersab86c2b2002-08-15 20:06:00 +00003226Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3227to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003228
Tim Petersab86c2b2002-08-15 20:06:00 +000032291. For any integer i, i = c(i/2) + f(i/2). In particular,
3230 bsize = c(bsize/2) + f(bsize/2).
32312. shift = f(bsize/2)
32323. asize <= bsize
32334. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3234 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003235
Tim Petersab86c2b2002-08-15 20:06:00 +00003236We allocated asize + bsize result digits, and add t3 into them at an offset
3237of shift. This leaves asize+bsize-shift allocated digit positions for t3
3238to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3239asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003240
Tim Petersab86c2b2002-08-15 20:06:00 +00003241bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3242at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003243
Tim Petersab86c2b2002-08-15 20:06:00 +00003244If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3245digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3246most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003247
Tim Petersab86c2b2002-08-15 20:06:00 +00003248The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003249
Tim Petersab86c2b2002-08-15 20:06:00 +00003250 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003251
Tim Petersab86c2b2002-08-15 20:06:00 +00003252and we have asize + c(bsize/2) available digit positions. We need to show
3253this is always enough. An instance of c(bsize/2) cancels out in both, so
3254the question reduces to whether asize digits is enough to hold
3255(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3256then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3257asize 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 +00003258digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003259asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003260c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3261is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3262bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003263
Tim Peters48d52c02002-08-14 17:07:32 +00003264Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3265clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3266ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003267*/
3268
Tim Peters60004642002-08-12 22:01:34 +00003269/* b has at least twice the digits of a, and a is big enough that Karatsuba
3270 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3271 * of slices, each with a->ob_size digits, and multiply the slices by a,
3272 * one at a time. This gives k_mul balanced inputs to work with, and is
3273 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003274 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003275 * single-width slice overlap between successive partial sums).
3276 */
3277static PyLongObject *
3278k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 const Py_ssize_t asize = ABS(Py_SIZE(a));
3281 Py_ssize_t bsize = ABS(Py_SIZE(b));
3282 Py_ssize_t nbdone; /* # of b digits already multiplied */
3283 PyLongObject *ret;
3284 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 assert(asize > KARATSUBA_CUTOFF);
3287 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 /* Allocate result space, and zero it out. */
3290 ret = _PyLong_New(asize + bsize);
3291 if (ret == NULL)
3292 return NULL;
3293 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 /* Successive slices of b are copied into bslice. */
3296 bslice = _PyLong_New(asize);
3297 if (bslice == NULL)
3298 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 nbdone = 0;
3301 while (bsize > 0) {
3302 PyLongObject *product;
3303 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 /* Multiply the next slice of b by a. */
3306 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3307 nbtouse * sizeof(digit));
3308 Py_SIZE(bslice) = nbtouse;
3309 product = k_mul(a, bslice);
3310 if (product == NULL)
3311 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 /* Add into result. */
3314 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3315 product->ob_digit, Py_SIZE(product));
3316 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 bsize -= nbtouse;
3319 nbdone += nbtouse;
3320 }
Tim Peters60004642002-08-12 22:01:34 +00003321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 Py_DECREF(bslice);
3323 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003324
Mark Dickinson22b20182010-05-10 21:27:53 +00003325 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 Py_DECREF(ret);
3327 Py_XDECREF(bslice);
3328 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003329}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003330
3331static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003332long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003338 /* fast path for single-digit multiplication */
3339 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3340 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003341#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003343#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 /* if we don't have long long then we're almost certainly
3345 using 15-bit digits, so v will fit in a long. In the
3346 unlikely event that we're using 30-bit digits on a platform
3347 without long long, a large v will just cause us to fall
3348 through to the general multiplication code below. */
3349 if (v >= LONG_MIN && v <= LONG_MAX)
3350 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003351#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 z = k_mul(a, b);
3355 /* Negate if exactly one of the inputs is negative. */
3356 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3357 NEGATE(z);
3358 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003359}
3360
Guido van Rossume32e0141992-01-19 16:31:05 +00003361/* The / and % operators are now defined in terms of divmod().
3362 The expression a mod b has the value a - b*floor(a/b).
3363 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003364 |a| by |b|, with the sign of a. This is also expressed
3365 as a - b*trunc(a/b), if trunc truncates towards zero.
3366 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003367 a b a rem b a mod b
3368 13 10 3 3
3369 -13 10 -3 7
3370 13 -10 3 -7
3371 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003372 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003373 have different signs. We then subtract one from the 'div'
3374 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003375
Tim Peters47e52ee2004-08-30 02:44:38 +00003376/* Compute
3377 * *pdiv, *pmod = divmod(v, w)
3378 * NULL can be passed for pdiv or pmod, in which case that part of
3379 * the result is simply thrown away. The caller owns a reference to
3380 * each of these it requests (does not pass NULL for).
3381 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003382static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003383l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 if (long_divrem(v, w, &div, &mod) < 0)
3389 return -1;
3390 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3391 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3392 PyLongObject *temp;
3393 PyLongObject *one;
3394 temp = (PyLongObject *) long_add(mod, w);
3395 Py_DECREF(mod);
3396 mod = temp;
3397 if (mod == NULL) {
3398 Py_DECREF(div);
3399 return -1;
3400 }
3401 one = (PyLongObject *) PyLong_FromLong(1L);
3402 if (one == NULL ||
3403 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3404 Py_DECREF(mod);
3405 Py_DECREF(div);
3406 Py_XDECREF(one);
3407 return -1;
3408 }
3409 Py_DECREF(one);
3410 Py_DECREF(div);
3411 div = temp;
3412 }
3413 if (pdiv != NULL)
3414 *pdiv = div;
3415 else
3416 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 if (pmod != NULL)
3419 *pmod = mod;
3420 else
3421 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003424}
3425
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003426static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003427long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 CHECK_BINOP(a, b);
3432 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3433 div = NULL;
3434 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003435}
3436
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003437/* PyLong/PyLong -> float, with correctly rounded result. */
3438
3439#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3440#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003442static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003443long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 PyLongObject *a, *b, *x;
3446 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3447 digit mask, low;
3448 int inexact, negate, a_is_small, b_is_small;
3449 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 CHECK_BINOP(v, w);
3452 a = (PyLongObject *)v;
3453 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 /*
3456 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3459 1. choose a suitable integer 'shift'
3460 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3461 3. adjust x for correct rounding
3462 4. convert x to a double dx with the same value
3463 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3468 returns either 0.0 or -0.0, depending on the sign of b. For a and
3469 b both nonzero, ignore signs of a and b, and add the sign back in
3470 at the end. Now write a_bits and b_bits for the bit lengths of a
3471 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3472 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003474 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3477 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3478 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3479 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003481 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 1. The integer 'shift' is chosen so that x has the right number of
3484 bits for a double, plus two or three extra bits that will be used
3485 in the rounding decisions. Writing a_bits and b_bits for the
3486 number of significant bits in a and b respectively, a
3487 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003489 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 This is fine in the usual case, but if a/b is smaller than the
3492 smallest normal float then it can lead to double rounding on an
3493 IEEE 754 platform, giving incorrectly rounded results. So we
3494 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 2. The quantity x is computed by first shifting a (left -shift bits
3499 if shift <= 0, right shift bits if shift > 0) and then dividing by
3500 b. For both the shift and the division, we keep track of whether
3501 the result is inexact, in a flag 'inexact'; this information is
3502 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 With the choice of shift above, together with our assumption that
3505 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3506 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3509 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003511 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 For float representability, we need x/2**extra_bits <
3514 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3515 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 To round, we just modify the bottom digit of x in-place; this can
3520 end up giving a digit with value > PyLONG_MASK, but that's not a
3521 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 With the original choices for shift above, extra_bits will always
3524 be 2 or 3. Then rounding under the round-half-to-even rule, we
3525 round up iff the most significant of the extra bits is 1, and
3526 either: (a) the computation of x in step 2 had an inexact result,
3527 or (b) at least one other of the extra bits is 1, or (c) the least
3528 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 4. Conversion to a double is straightforward; all floating-point
3531 operations involved in the conversion are exact, so there's no
3532 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003534 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3535 The result will always be exactly representable as a double, except
3536 in the case that it overflows. To avoid dependence on the exact
3537 behaviour of ldexp on overflow, we check for overflow before
3538 applying ldexp. The result of ldexp is adjusted for sign before
3539 returning.
3540 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 /* Reduce to case where a and b are both positive. */
3543 a_size = ABS(Py_SIZE(a));
3544 b_size = ABS(Py_SIZE(b));
3545 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3546 if (b_size == 0) {
3547 PyErr_SetString(PyExc_ZeroDivisionError,
3548 "division by zero");
3549 goto error;
3550 }
3551 if (a_size == 0)
3552 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 /* Fast path for a and b small (exactly representable in a double).
3555 Relies on floating-point division being correctly rounded; results
3556 may be subject to double rounding on x86 machines that operate with
3557 the x87 FPU set to 64-bit precision. */
3558 a_is_small = a_size <= MANT_DIG_DIGITS ||
3559 (a_size == MANT_DIG_DIGITS+1 &&
3560 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3561 b_is_small = b_size <= MANT_DIG_DIGITS ||
3562 (b_size == MANT_DIG_DIGITS+1 &&
3563 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3564 if (a_is_small && b_is_small) {
3565 double da, db;
3566 da = a->ob_digit[--a_size];
3567 while (a_size > 0)
3568 da = da * PyLong_BASE + a->ob_digit[--a_size];
3569 db = b->ob_digit[--b_size];
3570 while (b_size > 0)
3571 db = db * PyLong_BASE + b->ob_digit[--b_size];
3572 result = da / db;
3573 goto success;
3574 }
Tim Peterse2a60002001-09-04 06:17:36 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 /* Catch obvious cases of underflow and overflow */
3577 diff = a_size - b_size;
3578 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3579 /* Extreme overflow */
3580 goto overflow;
3581 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3582 /* Extreme underflow */
3583 goto underflow_or_zero;
3584 /* Next line is now safe from overflowing a Py_ssize_t */
3585 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3586 bits_in_digit(b->ob_digit[b_size - 1]);
3587 /* Now diff = a_bits - b_bits. */
3588 if (diff > DBL_MAX_EXP)
3589 goto overflow;
3590 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3591 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 /* Choose value for shift; see comments for step 1 above. */
3594 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 /* x = abs(a * 2**-shift) */
3599 if (shift <= 0) {
3600 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3601 digit rem;
3602 /* x = a << -shift */
3603 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3604 /* In practice, it's probably impossible to end up
3605 here. Both a and b would have to be enormous,
3606 using close to SIZE_T_MAX bytes of memory each. */
3607 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003608 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 goto error;
3610 }
3611 x = _PyLong_New(a_size + shift_digits + 1);
3612 if (x == NULL)
3613 goto error;
3614 for (i = 0; i < shift_digits; i++)
3615 x->ob_digit[i] = 0;
3616 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3617 a_size, -shift % PyLong_SHIFT);
3618 x->ob_digit[a_size + shift_digits] = rem;
3619 }
3620 else {
3621 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3622 digit rem;
3623 /* x = a >> shift */
3624 assert(a_size >= shift_digits);
3625 x = _PyLong_New(a_size - shift_digits);
3626 if (x == NULL)
3627 goto error;
3628 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3629 a_size - shift_digits, shift % PyLong_SHIFT);
3630 /* set inexact if any of the bits shifted out is nonzero */
3631 if (rem)
3632 inexact = 1;
3633 while (!inexact && shift_digits > 0)
3634 if (a->ob_digit[--shift_digits])
3635 inexact = 1;
3636 }
3637 long_normalize(x);
3638 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3641 reference to x, so it's safe to modify it in-place. */
3642 if (b_size == 1) {
3643 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3644 b->ob_digit[0]);
3645 long_normalize(x);
3646 if (rem)
3647 inexact = 1;
3648 }
3649 else {
3650 PyLongObject *div, *rem;
3651 div = x_divrem(x, b, &rem);
3652 Py_DECREF(x);
3653 x = div;
3654 if (x == NULL)
3655 goto error;
3656 if (Py_SIZE(rem))
3657 inexact = 1;
3658 Py_DECREF(rem);
3659 }
3660 x_size = ABS(Py_SIZE(x));
3661 assert(x_size > 0); /* result of division is never zero */
3662 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 /* The number of extra bits that have to be rounded away. */
3665 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3666 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 /* Round by directly modifying the low digit of x. */
3669 mask = (digit)1 << (extra_bits - 1);
3670 low = x->ob_digit[0] | inexact;
3671 if (low & mask && low & (3*mask-1))
3672 low += mask;
3673 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 /* Convert x to a double dx; the conversion is exact. */
3676 dx = x->ob_digit[--x_size];
3677 while (x_size > 0)
3678 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3679 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 /* Check whether ldexp result will overflow a double. */
3682 if (shift + x_bits >= DBL_MAX_EXP &&
3683 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3684 goto overflow;
3685 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003686
3687 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003688 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003689
3690 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003691 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003692
3693 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003694 PyErr_SetString(PyExc_OverflowError,
3695 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003696 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003698}
3699
3700static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003701long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003703 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003705 CHECK_BINOP(a, b);
3706
3707 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3708 mod = NULL;
3709 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003710}
3711
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003712static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003713long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003715 PyLongObject *div, *mod;
3716 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003720 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3721 return NULL;
3722 }
3723 z = PyTuple_New(2);
3724 if (z != NULL) {
3725 PyTuple_SetItem(z, 0, (PyObject *) div);
3726 PyTuple_SetItem(z, 1, (PyObject *) mod);
3727 }
3728 else {
3729 Py_DECREF(div);
3730 Py_DECREF(mod);
3731 }
3732 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003733}
3734
Tim Peters47e52ee2004-08-30 02:44:38 +00003735/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003736static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003737long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3740 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 PyLongObject *z = NULL; /* accumulated result */
3743 Py_ssize_t i, j, k; /* counters */
3744 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 /* 5-ary values. If the exponent is large enough, table is
3747 * precomputed so that table[i] == a**i % c for i in range(32).
3748 */
3749 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3750 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 /* a, b, c = v, w, x */
3753 CHECK_BINOP(v, w);
3754 a = (PyLongObject*)v; Py_INCREF(a);
3755 b = (PyLongObject*)w; Py_INCREF(b);
3756 if (PyLong_Check(x)) {
3757 c = (PyLongObject *)x;
3758 Py_INCREF(x);
3759 }
3760 else if (x == Py_None)
3761 c = NULL;
3762 else {
3763 Py_DECREF(a);
3764 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003765 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 }
Tim Peters4c483c42001-09-05 06:24:58 +00003767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3769 if (c) {
3770 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003771 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 goto Error;
3773 }
3774 else {
3775 /* else return a float. This works because we know
3776 that this calls float_pow() which converts its
3777 arguments to double. */
3778 Py_DECREF(a);
3779 Py_DECREF(b);
3780 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3781 }
3782 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (c) {
3785 /* if modulus == 0:
3786 raise ValueError() */
3787 if (Py_SIZE(c) == 0) {
3788 PyErr_SetString(PyExc_ValueError,
3789 "pow() 3rd argument cannot be 0");
3790 goto Error;
3791 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 /* if modulus < 0:
3794 negativeOutput = True
3795 modulus = -modulus */
3796 if (Py_SIZE(c) < 0) {
3797 negativeOutput = 1;
3798 temp = (PyLongObject *)_PyLong_Copy(c);
3799 if (temp == NULL)
3800 goto Error;
3801 Py_DECREF(c);
3802 c = temp;
3803 temp = NULL;
3804 NEGATE(c);
3805 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 /* if modulus == 1:
3808 return 0 */
3809 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3810 z = (PyLongObject *)PyLong_FromLong(0L);
3811 goto Done;
3812 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 /* if base < 0:
3815 base = base % modulus
3816 Having the base positive just makes things easier. */
3817 if (Py_SIZE(a) < 0) {
3818 if (l_divmod(a, c, NULL, &temp) < 0)
3819 goto Error;
3820 Py_DECREF(a);
3821 a = temp;
3822 temp = NULL;
3823 }
3824 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 /* At this point a, b, and c are guaranteed non-negative UNLESS
3827 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 z = (PyLongObject *)PyLong_FromLong(1L);
3830 if (z == NULL)
3831 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003833 /* Perform a modular reduction, X = X % c, but leave X alone if c
3834 * is NULL.
3835 */
3836#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003837 do { \
3838 if (c != NULL) { \
3839 if (l_divmod(X, c, NULL, &temp) < 0) \
3840 goto Error; \
3841 Py_XDECREF(X); \
3842 X = temp; \
3843 temp = NULL; \
3844 } \
3845 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003847 /* Multiply two values, then reduce the result:
3848 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003849#define MULT(X, Y, result) \
3850 do { \
3851 temp = (PyLongObject *)long_mul(X, Y); \
3852 if (temp == NULL) \
3853 goto Error; \
3854 Py_XDECREF(result); \
3855 result = temp; \
3856 temp = NULL; \
3857 REDUCE(result); \
3858 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3861 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3862 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3863 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3864 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003867 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003868 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003869 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003870 }
3871 }
3872 }
3873 else {
3874 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3875 Py_INCREF(z); /* still holds 1L */
3876 table[0] = z;
3877 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003878 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3881 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3884 const int index = (bi >> j) & 0x1f;
3885 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003886 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003888 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 }
3890 }
3891 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 if (negativeOutput && (Py_SIZE(z) != 0)) {
3894 temp = (PyLongObject *)long_sub(z, c);
3895 if (temp == NULL)
3896 goto Error;
3897 Py_DECREF(z);
3898 z = temp;
3899 temp = NULL;
3900 }
3901 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003902
Mark Dickinson22b20182010-05-10 21:27:53 +00003903 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 if (z != NULL) {
3905 Py_DECREF(z);
3906 z = NULL;
3907 }
3908 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003909 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3911 for (i = 0; i < 32; ++i)
3912 Py_XDECREF(table[i]);
3913 }
3914 Py_DECREF(a);
3915 Py_DECREF(b);
3916 Py_XDECREF(c);
3917 Py_XDECREF(temp);
3918 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003919}
3920
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003921static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003922long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 /* Implement ~x as -(x+1) */
3925 PyLongObject *x;
3926 PyLongObject *w;
3927 if (ABS(Py_SIZE(v)) <=1)
3928 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3929 w = (PyLongObject *)PyLong_FromLong(1L);
3930 if (w == NULL)
3931 return NULL;
3932 x = (PyLongObject *) long_add(v, w);
3933 Py_DECREF(w);
3934 if (x == NULL)
3935 return NULL;
3936 Py_SIZE(x) = -(Py_SIZE(x));
3937 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003938}
3939
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003940static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003941long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 PyLongObject *z;
3944 if (ABS(Py_SIZE(v)) <= 1)
3945 return PyLong_FromLong(-MEDIUM_VALUE(v));
3946 z = (PyLongObject *)_PyLong_Copy(v);
3947 if (z != NULL)
3948 Py_SIZE(z) = -(Py_SIZE(v));
3949 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003950}
3951
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003952static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003953long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 if (Py_SIZE(v) < 0)
3956 return long_neg(v);
3957 else
3958 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003959}
3960
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003961static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00003962long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00003965}
3966
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003967static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003968long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00003969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 PyLongObject *z = NULL;
3971 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
3972 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003976 if (Py_SIZE(a) < 0) {
3977 /* Right shifting negative numbers is harder */
3978 PyLongObject *a1, *a2;
3979 a1 = (PyLongObject *) long_invert(a);
3980 if (a1 == NULL)
3981 goto rshift_error;
3982 a2 = (PyLongObject *) long_rshift(a1, b);
3983 Py_DECREF(a1);
3984 if (a2 == NULL)
3985 goto rshift_error;
3986 z = (PyLongObject *) long_invert(a2);
3987 Py_DECREF(a2);
3988 }
3989 else {
3990 shiftby = PyLong_AsSsize_t((PyObject *)b);
3991 if (shiftby == -1L && PyErr_Occurred())
3992 goto rshift_error;
3993 if (shiftby < 0) {
3994 PyErr_SetString(PyExc_ValueError,
3995 "negative shift count");
3996 goto rshift_error;
3997 }
3998 wordshift = shiftby / PyLong_SHIFT;
3999 newsize = ABS(Py_SIZE(a)) - wordshift;
4000 if (newsize <= 0)
4001 return PyLong_FromLong(0);
4002 loshift = shiftby % PyLong_SHIFT;
4003 hishift = PyLong_SHIFT - loshift;
4004 lomask = ((digit)1 << hishift) - 1;
4005 himask = PyLong_MASK ^ lomask;
4006 z = _PyLong_New(newsize);
4007 if (z == NULL)
4008 goto rshift_error;
4009 if (Py_SIZE(a) < 0)
4010 Py_SIZE(z) = -(Py_SIZE(z));
4011 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4012 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4013 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004014 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004015 }
4016 z = long_normalize(z);
4017 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004018 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004019 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004020
Guido van Rossumc6913e71991-11-19 20:26:46 +00004021}
4022
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004023static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004024long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004026 /* This version due to Tim Peters */
4027 PyLongObject *a = (PyLongObject*)v;
4028 PyLongObject *b = (PyLongObject*)w;
4029 PyLongObject *z = NULL;
4030 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4031 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 shiftby = PyLong_AsSsize_t((PyObject *)b);
4036 if (shiftby == -1L && PyErr_Occurred())
4037 goto lshift_error;
4038 if (shiftby < 0) {
4039 PyErr_SetString(PyExc_ValueError, "negative shift count");
4040 goto lshift_error;
4041 }
4042 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4043 wordshift = shiftby / PyLong_SHIFT;
4044 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 oldsize = ABS(Py_SIZE(a));
4047 newsize = oldsize + wordshift;
4048 if (remshift)
4049 ++newsize;
4050 z = _PyLong_New(newsize);
4051 if (z == NULL)
4052 goto lshift_error;
4053 if (Py_SIZE(a) < 0)
4054 NEGATE(z);
4055 for (i = 0; i < wordshift; i++)
4056 z->ob_digit[i] = 0;
4057 accum = 0;
4058 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4059 accum |= (twodigits)a->ob_digit[j] << remshift;
4060 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4061 accum >>= PyLong_SHIFT;
4062 }
4063 if (remshift)
4064 z->ob_digit[newsize-1] = (digit)accum;
4065 else
4066 assert(!accum);
4067 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004068 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004069 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004070}
4071
Mark Dickinson27a87a22009-10-25 20:43:34 +00004072/* Compute two's complement of digit vector a[0:m], writing result to
4073 z[0:m]. The digit vector a need not be normalized, but should not
4074 be entirely zero. a and z may point to the same digit vector. */
4075
4076static void
4077v_complement(digit *z, digit *a, Py_ssize_t m)
4078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004079 Py_ssize_t i;
4080 digit carry = 1;
4081 for (i = 0; i < m; ++i) {
4082 carry += a[i] ^ PyLong_MASK;
4083 z[i] = carry & PyLong_MASK;
4084 carry >>= PyLong_SHIFT;
4085 }
4086 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004087}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004088
4089/* Bitwise and/xor/or operations */
4090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004091static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004092long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004093 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004094 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 int nega, negb, negz;
4097 Py_ssize_t size_a, size_b, size_z, i;
4098 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 /* Bitwise operations for negative numbers operate as though
4101 on a two's complement representation. So convert arguments
4102 from sign-magnitude to two's complement, and convert the
4103 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 /* If a is negative, replace it by its two's complement. */
4106 size_a = ABS(Py_SIZE(a));
4107 nega = Py_SIZE(a) < 0;
4108 if (nega) {
4109 z = _PyLong_New(size_a);
4110 if (z == NULL)
4111 return NULL;
4112 v_complement(z->ob_digit, a->ob_digit, size_a);
4113 a = z;
4114 }
4115 else
4116 /* Keep reference count consistent. */
4117 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 /* Same for b. */
4120 size_b = ABS(Py_SIZE(b));
4121 negb = Py_SIZE(b) < 0;
4122 if (negb) {
4123 z = _PyLong_New(size_b);
4124 if (z == NULL) {
4125 Py_DECREF(a);
4126 return NULL;
4127 }
4128 v_complement(z->ob_digit, b->ob_digit, size_b);
4129 b = z;
4130 }
4131 else
4132 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 /* Swap a and b if necessary to ensure size_a >= size_b. */
4135 if (size_a < size_b) {
4136 z = a; a = b; b = z;
4137 size_z = size_a; size_a = size_b; size_b = size_z;
4138 negz = nega; nega = negb; negb = negz;
4139 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 /* JRH: The original logic here was to allocate the result value (z)
4142 as the longer of the two operands. However, there are some cases
4143 where the result is guaranteed to be shorter than that: AND of two
4144 positives, OR of two negatives: use the shorter number. AND with
4145 mixed signs: use the positive number. OR with mixed signs: use the
4146 negative number.
4147 */
4148 switch (op) {
4149 case '^':
4150 negz = nega ^ negb;
4151 size_z = size_a;
4152 break;
4153 case '&':
4154 negz = nega & negb;
4155 size_z = negb ? size_a : size_b;
4156 break;
4157 case '|':
4158 negz = nega | negb;
4159 size_z = negb ? size_b : size_a;
4160 break;
4161 default:
4162 PyErr_BadArgument();
4163 return NULL;
4164 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* We allow an extra digit if z is negative, to make sure that
4167 the final two's complement of z doesn't overflow. */
4168 z = _PyLong_New(size_z + negz);
4169 if (z == NULL) {
4170 Py_DECREF(a);
4171 Py_DECREF(b);
4172 return NULL;
4173 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 /* Compute digits for overlap of a and b. */
4176 switch(op) {
4177 case '&':
4178 for (i = 0; i < size_b; ++i)
4179 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4180 break;
4181 case '|':
4182 for (i = 0; i < size_b; ++i)
4183 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4184 break;
4185 case '^':
4186 for (i = 0; i < size_b; ++i)
4187 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4188 break;
4189 default:
4190 PyErr_BadArgument();
4191 return NULL;
4192 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004194 /* Copy any remaining digits of a, inverting if necessary. */
4195 if (op == '^' && negb)
4196 for (; i < size_z; ++i)
4197 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4198 else if (i < size_z)
4199 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4200 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* Complement result if negative. */
4203 if (negz) {
4204 Py_SIZE(z) = -(Py_SIZE(z));
4205 z->ob_digit[size_z] = PyLong_MASK;
4206 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4207 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004209 Py_DECREF(a);
4210 Py_DECREF(b);
4211 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004212}
4213
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004214static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004215long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004217 PyObject *c;
4218 CHECK_BINOP(a, b);
4219 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4220 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004221}
4222
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004223static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004224long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004226 PyObject *c;
4227 CHECK_BINOP(a, b);
4228 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4229 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004230}
4231
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004232static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004233long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004235 PyObject *c;
4236 CHECK_BINOP(a, b);
4237 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4238 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004239}
4240
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004241static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004242long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 if (PyLong_CheckExact(v))
4245 Py_INCREF(v);
4246 else
4247 v = _PyLong_Copy((PyLongObject *)v);
4248 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004249}
4250
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004251static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004252long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 double result;
4255 result = PyLong_AsDouble(v);
4256 if (result == -1.0 && PyErr_Occurred())
4257 return NULL;
4258 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004259}
4260
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004261static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004262long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004263
Tim Peters6d6c1a32001-08-02 04:15:00 +00004264static PyObject *
4265long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4266{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004267 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004268 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004269 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004271 if (type != &PyLong_Type)
4272 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004273 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4274 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004275 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004276 if (x == NULL) {
4277 if (obase != NULL) {
4278 PyErr_SetString(PyExc_TypeError,
4279 "int() missing string argument");
4280 return NULL;
4281 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004283 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004284 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004285 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004286
Gregory P. Smitha689e522012-12-25 22:38:32 -08004287 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004288 if (base == -1 && PyErr_Occurred())
4289 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004290 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004291 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004292 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004293 return NULL;
4294 }
4295
4296 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004297 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
4299 /* Since PyLong_FromString doesn't have a length parameter,
4300 * check here for possible NULs in the string. */
4301 char *string;
4302 Py_ssize_t size = Py_SIZE(x);
4303 if (PyByteArray_Check(x))
4304 string = PyByteArray_AS_STRING(x);
4305 else
4306 string = PyBytes_AS_STRING(x);
Christian Heimes79b97ee2012-09-12 15:31:43 +02004307 if (strlen(string) != (size_t)size || !size) {
4308 /* We only see this if there's a null byte in x or x is empty,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004309 x is a bytes or buffer, *and* a base is given. */
4310 PyErr_Format(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004311 "invalid literal for int() with base %d: %R",
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004312 (int)base, x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 return NULL;
4314 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004315 return PyLong_FromString(string, NULL, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004316 }
4317 else {
4318 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004319 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004320 return NULL;
4321 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004322}
4323
Guido van Rossumbef14172001-08-29 15:47:46 +00004324/* Wimpy, slow approach to tp_new calls for subtypes of long:
4325 first create a regular long from whatever arguments we got,
4326 then allocate a subtype instance and initialize it from
4327 the regular long. The regular long is then thrown away.
4328*/
4329static PyObject *
4330long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 PyLongObject *tmp, *newobj;
4333 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 assert(PyType_IsSubtype(type, &PyLong_Type));
4336 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4337 if (tmp == NULL)
4338 return NULL;
4339 assert(PyLong_CheckExact(tmp));
4340 n = Py_SIZE(tmp);
4341 if (n < 0)
4342 n = -n;
4343 newobj = (PyLongObject *)type->tp_alloc(type, n);
4344 if (newobj == NULL) {
4345 Py_DECREF(tmp);
4346 return NULL;
4347 }
4348 assert(PyLong_Check(newobj));
4349 Py_SIZE(newobj) = Py_SIZE(tmp);
4350 for (i = 0; i < n; i++)
4351 newobj->ob_digit[i] = tmp->ob_digit[i];
4352 Py_DECREF(tmp);
4353 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004354}
4355
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004356static PyObject *
4357long_getnewargs(PyLongObject *v)
4358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004359 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004360}
4361
Guido van Rossumb43daf72007-08-01 18:08:08 +00004362static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004363long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004365}
4366
4367static PyObject *
4368long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004370}
4371
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004372static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004373long__format__(PyObject *self, PyObject *args)
4374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004375 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004376 _PyUnicodeWriter writer;
4377 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4380 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004381
4382 _PyUnicodeWriter_Init(&writer, 0);
4383 ret = _PyLong_FormatAdvancedWriter(
4384 &writer,
4385 self,
4386 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4387 if (ret == -1) {
4388 _PyUnicodeWriter_Dealloc(&writer);
4389 return NULL;
4390 }
4391 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004392}
4393
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004394/* Return a pair (q, r) such that a = b * q + r, and
4395 abs(r) <= abs(b)/2, with equality possible only if q is even.
4396 In other words, q == a / b, rounded to the nearest integer using
4397 round-half-to-even. */
4398
4399PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004400_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004401{
4402 PyLongObject *quo = NULL, *rem = NULL;
4403 PyObject *one = NULL, *twice_rem, *result, *temp;
4404 int cmp, quo_is_odd, quo_is_neg;
4405
4406 /* Equivalent Python code:
4407
4408 def divmod_near(a, b):
4409 q, r = divmod(a, b)
4410 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4411 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4412 # positive, 2 * r < b if b negative.
4413 greater_than_half = 2*r > b if b > 0 else 2*r < b
4414 exactly_half = 2*r == b
4415 if greater_than_half or exactly_half and q % 2 == 1:
4416 q += 1
4417 r -= b
4418 return q, r
4419
4420 */
4421 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4422 PyErr_SetString(PyExc_TypeError,
4423 "non-integer arguments in division");
4424 return NULL;
4425 }
4426
4427 /* Do a and b have different signs? If so, quotient is negative. */
4428 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4429
4430 one = PyLong_FromLong(1L);
4431 if (one == NULL)
4432 return NULL;
4433
4434 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4435 goto error;
4436
4437 /* compare twice the remainder with the divisor, to see
4438 if we need to adjust the quotient and remainder */
4439 twice_rem = long_lshift((PyObject *)rem, one);
4440 if (twice_rem == NULL)
4441 goto error;
4442 if (quo_is_neg) {
4443 temp = long_neg((PyLongObject*)twice_rem);
4444 Py_DECREF(twice_rem);
4445 twice_rem = temp;
4446 if (twice_rem == NULL)
4447 goto error;
4448 }
4449 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4450 Py_DECREF(twice_rem);
4451
4452 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4453 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4454 /* fix up quotient */
4455 if (quo_is_neg)
4456 temp = long_sub(quo, (PyLongObject *)one);
4457 else
4458 temp = long_add(quo, (PyLongObject *)one);
4459 Py_DECREF(quo);
4460 quo = (PyLongObject *)temp;
4461 if (quo == NULL)
4462 goto error;
4463 /* and remainder */
4464 if (quo_is_neg)
4465 temp = long_add(rem, (PyLongObject *)b);
4466 else
4467 temp = long_sub(rem, (PyLongObject *)b);
4468 Py_DECREF(rem);
4469 rem = (PyLongObject *)temp;
4470 if (rem == NULL)
4471 goto error;
4472 }
4473
4474 result = PyTuple_New(2);
4475 if (result == NULL)
4476 goto error;
4477
4478 /* PyTuple_SET_ITEM steals references */
4479 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4480 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4481 Py_DECREF(one);
4482 return result;
4483
4484 error:
4485 Py_XDECREF(quo);
4486 Py_XDECREF(rem);
4487 Py_XDECREF(one);
4488 return NULL;
4489}
4490
Eric Smith8c663262007-08-25 02:26:07 +00004491static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004492long_round(PyObject *self, PyObject *args)
4493{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004494 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004495
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004496 /* To round an integer m to the nearest 10**n (n positive), we make use of
4497 * the divmod_near operation, defined by:
4498 *
4499 * divmod_near(a, b) = (q, r)
4500 *
4501 * where q is the nearest integer to the quotient a / b (the
4502 * nearest even integer in the case of a tie) and r == a - q * b.
4503 * Hence q * b = a - r is the nearest multiple of b to a,
4504 * preferring even multiples in the case of a tie.
4505 *
4506 * So the nearest multiple of 10**n to m is:
4507 *
4508 * m - divmod_near(m, 10**n)[1].
4509 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4511 return NULL;
4512 if (o_ndigits == NULL)
4513 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004514
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004515 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516 if (ndigits == NULL)
4517 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004518
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004519 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 if (Py_SIZE(ndigits) >= 0) {
4521 Py_DECREF(ndigits);
4522 return long_long(self);
4523 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004524
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004525 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4526 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004528 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004530 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004531
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004532 result = PyLong_FromLong(10L);
4533 if (result == NULL) {
4534 Py_DECREF(ndigits);
4535 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004537
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004538 temp = long_pow(result, ndigits, Py_None);
4539 Py_DECREF(ndigits);
4540 Py_DECREF(result);
4541 result = temp;
4542 if (result == NULL)
4543 return NULL;
4544
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004545 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004546 Py_DECREF(result);
4547 result = temp;
4548 if (result == NULL)
4549 return NULL;
4550
4551 temp = long_sub((PyLongObject *)self,
4552 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4553 Py_DECREF(result);
4554 result = temp;
4555
4556 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004557}
4558
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004559static PyObject *
4560long_sizeof(PyLongObject *v)
4561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004562 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004564 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4565 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004566}
4567
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004568static PyObject *
4569long_bit_length(PyLongObject *v)
4570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 PyLongObject *result, *x, *y;
4572 Py_ssize_t ndigits, msd_bits = 0;
4573 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 assert(v != NULL);
4576 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 ndigits = ABS(Py_SIZE(v));
4579 if (ndigits == 0)
4580 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 msd = v->ob_digit[ndigits-1];
4583 while (msd >= 32) {
4584 msd_bits += 6;
4585 msd >>= 6;
4586 }
4587 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4590 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 /* expression above may overflow; use Python integers instead */
4593 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4594 if (result == NULL)
4595 return NULL;
4596 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4597 if (x == NULL)
4598 goto error;
4599 y = (PyLongObject *)long_mul(result, x);
4600 Py_DECREF(x);
4601 if (y == NULL)
4602 goto error;
4603 Py_DECREF(result);
4604 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004606 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4607 if (x == NULL)
4608 goto error;
4609 y = (PyLongObject *)long_add(result, x);
4610 Py_DECREF(x);
4611 if (y == NULL)
4612 goto error;
4613 Py_DECREF(result);
4614 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004617
Mark Dickinson22b20182010-05-10 21:27:53 +00004618 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004619 Py_DECREF(result);
4620 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004621}
4622
4623PyDoc_STRVAR(long_bit_length_doc,
4624"int.bit_length() -> int\n\
4625\n\
4626Number of bits necessary to represent self in binary.\n\
4627>>> bin(37)\n\
4628'0b100101'\n\
4629>>> (37).bit_length()\n\
46306");
4631
Christian Heimes53876d92008-04-19 00:31:39 +00004632#if 0
4633static PyObject *
4634long_is_finite(PyObject *v)
4635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004637}
4638#endif
4639
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004640
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004641static PyObject *
4642long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 PyObject *byteorder_str;
4645 PyObject *is_signed_obj = NULL;
4646 Py_ssize_t length;
4647 int little_endian;
4648 int is_signed;
4649 PyObject *bytes;
4650 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4653 &length, &byteorder_str,
4654 &is_signed_obj))
4655 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 if (args != NULL && Py_SIZE(args) > 2) {
4658 PyErr_SetString(PyExc_TypeError,
4659 "'signed' is a keyword-only argument");
4660 return NULL;
4661 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4664 little_endian = 1;
4665 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4666 little_endian = 0;
4667 else {
4668 PyErr_SetString(PyExc_ValueError,
4669 "byteorder must be either 'little' or 'big'");
4670 return NULL;
4671 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 if (is_signed_obj != NULL) {
4674 int cmp = PyObject_IsTrue(is_signed_obj);
4675 if (cmp < 0)
4676 return NULL;
4677 is_signed = cmp ? 1 : 0;
4678 }
4679 else {
4680 /* If the signed argument was omitted, use False as the
4681 default. */
4682 is_signed = 0;
4683 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 if (length < 0) {
4686 PyErr_SetString(PyExc_ValueError,
4687 "length argument must be non-negative");
4688 return NULL;
4689 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 bytes = PyBytes_FromStringAndSize(NULL, length);
4692 if (bytes == NULL)
4693 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4696 length, little_endian, is_signed) < 0) {
4697 Py_DECREF(bytes);
4698 return NULL;
4699 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004702}
4703
Mark Dickinson078c2532010-01-30 18:06:17 +00004704PyDoc_STRVAR(long_to_bytes_doc,
4705"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004706\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004707Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004708\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004710raised if the integer is not representable with the given number of\n\
4711bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004712\n\
4713The byteorder argument determines the byte order used to represent the\n\
4714integer. If byteorder is 'big', the most significant byte is at the\n\
4715beginning of the byte array. If byteorder is 'little', the most\n\
4716significant byte is at the end of the byte array. To request the native\n\
4717byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4718\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004719The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004721is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004722
4723static PyObject *
4724long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 PyObject *byteorder_str;
4727 PyObject *is_signed_obj = NULL;
4728 int little_endian;
4729 int is_signed;
4730 PyObject *obj;
4731 PyObject *bytes;
4732 PyObject *long_obj;
4733 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4736 &obj, &byteorder_str,
4737 &is_signed_obj))
4738 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 if (args != NULL && Py_SIZE(args) > 2) {
4741 PyErr_SetString(PyExc_TypeError,
4742 "'signed' is a keyword-only argument");
4743 return NULL;
4744 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4747 little_endian = 1;
4748 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4749 little_endian = 0;
4750 else {
4751 PyErr_SetString(PyExc_ValueError,
4752 "byteorder must be either 'little' or 'big'");
4753 return NULL;
4754 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 if (is_signed_obj != NULL) {
4757 int cmp = PyObject_IsTrue(is_signed_obj);
4758 if (cmp < 0)
4759 return NULL;
4760 is_signed = cmp ? 1 : 0;
4761 }
4762 else {
4763 /* If the signed argument was omitted, use False as the
4764 default. */
4765 is_signed = 0;
4766 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 bytes = PyObject_Bytes(obj);
4769 if (bytes == NULL)
4770 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 long_obj = _PyLong_FromByteArray(
4773 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4774 little_endian, is_signed);
4775 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 /* If from_bytes() was used on subclass, allocate new subclass
4778 * instance, initialize it with decoded long value and return it.
4779 */
4780 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4781 PyLongObject *newobj;
4782 int i;
4783 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004785 newobj = (PyLongObject *)type->tp_alloc(type, n);
4786 if (newobj == NULL) {
4787 Py_DECREF(long_obj);
4788 return NULL;
4789 }
4790 assert(PyLong_Check(newobj));
4791 Py_SIZE(newobj) = Py_SIZE(long_obj);
4792 for (i = 0; i < n; i++) {
4793 newobj->ob_digit[i] =
4794 ((PyLongObject *)long_obj)->ob_digit[i];
4795 }
4796 Py_DECREF(long_obj);
4797 return (PyObject *)newobj;
4798 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004801}
4802
Mark Dickinson078c2532010-01-30 18:06:17 +00004803PyDoc_STRVAR(long_from_bytes_doc,
4804"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4805\n\
4806Return the integer represented by the given array of bytes.\n\
4807\n\
4808The bytes argument must either support the buffer protocol or be an\n\
4809iterable object producing bytes. Bytes and bytearray are examples of\n\
4810built-in objects that support the buffer protocol.\n\
4811\n\
4812The byteorder argument determines the byte order used to represent the\n\
4813integer. If byteorder is 'big', the most significant byte is at the\n\
4814beginning of the byte array. If byteorder is 'little', the most\n\
4815significant byte is at the end of the byte array. To request the native\n\
4816byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4817\n\
4818The signed keyword-only argument indicates whether two's complement is\n\
4819used to represent the integer.");
4820
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004821static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004822 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4823 "Returns self, the complex conjugate of any int."},
4824 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4825 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004826#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004827 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4828 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004829#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 {"to_bytes", (PyCFunction)long_to_bytes,
4831 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4832 {"from_bytes", (PyCFunction)long_from_bytes,
4833 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4834 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4835 "Truncating an Integral returns itself."},
4836 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4837 "Flooring an Integral returns itself."},
4838 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4839 "Ceiling of an Integral returns itself."},
4840 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4841 "Rounding an Integral returns itself.\n"
4842 "Rounding with an ndigits argument also returns an integer."},
4843 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4844 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4845 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4846 "Returns size in memory, in bytes"},
4847 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004848};
4849
Guido van Rossumb43daf72007-08-01 18:08:08 +00004850static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004851 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004852 (getter)long_long, (setter)NULL,
4853 "the real part of a complex number",
4854 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004855 {"imag",
4856 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004857 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004858 NULL},
4859 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004860 (getter)long_long, (setter)NULL,
4861 "the numerator of a rational number in lowest terms",
4862 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004863 {"denominator",
4864 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004865 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004866 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004867 {NULL} /* Sentinel */
4868};
4869
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004870PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004871"int(x=0) -> integer\n\
4872int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004873\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004874Convert a number or string to an integer, or return 0 if no arguments\n\
4875are given. If x is a number, return x.__int__(). For floating point\n\
4876numbers, this truncates towards zero.\n\
4877\n\
4878If x is not a number or if base is given, then x must be a string,\n\
4879bytes, or bytearray instance representing an integer literal in the\n\
4880given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4881by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4882Base 0 means to interpret the base from the string as an integer literal.\n\
4883>>> int('0b100', base=0)\n\
48844");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004885
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004886static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004887 (binaryfunc)long_add, /*nb_add*/
4888 (binaryfunc)long_sub, /*nb_subtract*/
4889 (binaryfunc)long_mul, /*nb_multiply*/
4890 long_mod, /*nb_remainder*/
4891 long_divmod, /*nb_divmod*/
4892 long_pow, /*nb_power*/
4893 (unaryfunc)long_neg, /*nb_negative*/
4894 (unaryfunc)long_long, /*tp_positive*/
4895 (unaryfunc)long_abs, /*tp_absolute*/
4896 (inquiry)long_bool, /*tp_bool*/
4897 (unaryfunc)long_invert, /*nb_invert*/
4898 long_lshift, /*nb_lshift*/
4899 (binaryfunc)long_rshift, /*nb_rshift*/
4900 long_and, /*nb_and*/
4901 long_xor, /*nb_xor*/
4902 long_or, /*nb_or*/
4903 long_long, /*nb_int*/
4904 0, /*nb_reserved*/
4905 long_float, /*nb_float*/
4906 0, /* nb_inplace_add */
4907 0, /* nb_inplace_subtract */
4908 0, /* nb_inplace_multiply */
4909 0, /* nb_inplace_remainder */
4910 0, /* nb_inplace_power */
4911 0, /* nb_inplace_lshift */
4912 0, /* nb_inplace_rshift */
4913 0, /* nb_inplace_and */
4914 0, /* nb_inplace_xor */
4915 0, /* nb_inplace_or */
4916 long_div, /* nb_floor_divide */
4917 long_true_divide, /* nb_true_divide */
4918 0, /* nb_inplace_floor_divide */
4919 0, /* nb_inplace_true_divide */
4920 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004921};
4922
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004923PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004924 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4925 "int", /* tp_name */
4926 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4927 sizeof(digit), /* tp_itemsize */
4928 long_dealloc, /* tp_dealloc */
4929 0, /* tp_print */
4930 0, /* tp_getattr */
4931 0, /* tp_setattr */
4932 0, /* tp_reserved */
4933 long_to_decimal_string, /* tp_repr */
4934 &long_as_number, /* tp_as_number */
4935 0, /* tp_as_sequence */
4936 0, /* tp_as_mapping */
4937 (hashfunc)long_hash, /* tp_hash */
4938 0, /* tp_call */
4939 long_to_decimal_string, /* tp_str */
4940 PyObject_GenericGetAttr, /* tp_getattro */
4941 0, /* tp_setattro */
4942 0, /* tp_as_buffer */
4943 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4944 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4945 long_doc, /* tp_doc */
4946 0, /* tp_traverse */
4947 0, /* tp_clear */
4948 long_richcompare, /* tp_richcompare */
4949 0, /* tp_weaklistoffset */
4950 0, /* tp_iter */
4951 0, /* tp_iternext */
4952 long_methods, /* tp_methods */
4953 0, /* tp_members */
4954 long_getset, /* tp_getset */
4955 0, /* tp_base */
4956 0, /* tp_dict */
4957 0, /* tp_descr_get */
4958 0, /* tp_descr_set */
4959 0, /* tp_dictoffset */
4960 0, /* tp_init */
4961 0, /* tp_alloc */
4962 long_new, /* tp_new */
4963 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004964};
Guido van Rossumddefaf32007-01-14 03:31:43 +00004965
Mark Dickinsonbd792642009-03-18 20:06:12 +00004966static PyTypeObject Int_InfoType;
4967
4968PyDoc_STRVAR(int_info__doc__,
4969"sys.int_info\n\
4970\n\
4971A struct sequence that holds information about Python's\n\
4972internal representation of integers. The attributes are read only.");
4973
4974static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00004976 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00004978};
4979
4980static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 "sys.int_info", /* name */
4982 int_info__doc__, /* doc */
4983 int_info_fields, /* fields */
4984 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00004985};
4986
4987PyObject *
4988PyLong_GetInfo(void)
4989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 PyObject* int_info;
4991 int field = 0;
4992 int_info = PyStructSequence_New(&Int_InfoType);
4993 if (int_info == NULL)
4994 return NULL;
4995 PyStructSequence_SET_ITEM(int_info, field++,
4996 PyLong_FromLong(PyLong_SHIFT));
4997 PyStructSequence_SET_ITEM(int_info, field++,
4998 PyLong_FromLong(sizeof(digit)));
4999 if (PyErr_Occurred()) {
5000 Py_CLEAR(int_info);
5001 return NULL;
5002 }
5003 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005004}
5005
Guido van Rossumddefaf32007-01-14 03:31:43 +00005006int
5007_PyLong_Init(void)
5008{
5009#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 int ival, size;
5011 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5014 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5015 if (Py_TYPE(v) == &PyLong_Type) {
5016 /* The element is already initialized, most likely
5017 * the Python interpreter was initialized before.
5018 */
5019 Py_ssize_t refcnt;
5020 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5023 _Py_NewReference(op);
5024 /* _Py_NewReference sets the ref count to 1 but
5025 * the ref count might be larger. Set the refcnt
5026 * to the original refcnt + 1 */
5027 Py_REFCNT(op) = refcnt + 1;
5028 assert(Py_SIZE(op) == size);
5029 assert(v->ob_digit[0] == abs(ival));
5030 }
5031 else {
5032 PyObject_INIT(v, &PyLong_Type);
5033 }
5034 Py_SIZE(v) = size;
5035 v->ob_digit[0] = abs(ival);
5036 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005037#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 /* initialize int_info */
5039 if (Int_InfoType.tp_name == 0)
5040 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005043}
5044
5045void
5046PyLong_Fini(void)
5047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 /* Integers are currently statically allocated. Py_DECREF is not
5049 needed, but Python must forget about the reference or multiple
5050 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005051#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 int i;
5053 PyLongObject *v = small_ints;
5054 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5055 _Py_DEC_REFTOTAL;
5056 _Py_ForgetReference((PyObject*)v);
5057 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005058#endif
5059}