blob: 6383507a5c6ab39fb42442d6d9b89ed684eade63 [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
Serhiy Storchaka95949422013-08-27 19:40:23 +030071/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000072 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)
Serhiy Storchaka95949422013-08-27 19:40:23 +030078/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000079 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030080 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000081 */
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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300102/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000103 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300119/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000120 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300171/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000172
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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300240/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000241
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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300269/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000270
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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300323/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100324 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300420/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100421 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 Storchaka95949422013-08-27 19:40:23 +0300437/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka441d30f2013-01-19 12:26:26 +0200438 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300455/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000456 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300510/* Get a C unsigned long int from an 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300554/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200555 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300597/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000598 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 */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300715 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300759 /* How many Python int digits do we need? We have
760 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300860 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300915 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 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
Serhiy Storchaka95949422013-08-27 19:40:23 +0300951/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000952
953PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000954PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000955{
Mark Dickinson91044792012-10-18 19:21:43 +0100956#if SIZEOF_VOID_P <= SIZEOF_LONG
957 /* special-case null pointer */
958 if (!p)
959 return PyLong_FromLong(0);
960 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
961#else
962
Tim Peters70128a12001-06-16 08:48:40 +0000963#ifndef HAVE_LONG_LONG
964# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
965#endif
966#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000967# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000968#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* special-case null pointer */
970 if (!p)
971 return PyLong_FromLong(0);
972 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100973#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000974
Guido van Rossum78694d91998-09-18 14:14:13 +0000975}
976
Serhiy Storchaka95949422013-08-27 19:40:23 +0300977/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000978
979void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000980PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +0000981{
Tim Peters70128a12001-06-16 08:48:40 +0000982#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
986 x = PyLong_AsLong(vv);
987 else
988 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +0000989#else
Tim Peters70128a12001-06-16 08:48:40 +0000990
991#ifndef HAVE_LONG_LONG
992# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
993#endif
994#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000996#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1000 x = PyLong_AsLongLong(vv);
1001 else
1002 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001003
1004#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (x == -1 && PyErr_Occurred())
1007 return NULL;
1008 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001009}
1010
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001011#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001012
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001013/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001014 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001015 */
1016
Tim Peterscf37dfc2001-06-14 18:42:50 +00001017#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +00001018#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001019
Serhiy Storchaka95949422013-08-27 19:40:23 +03001020/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001021
1022PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyLongObject *v;
1026 unsigned PY_LONG_LONG abs_ival;
1027 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1028 int ndigits = 0;
1029 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 CHECK_SMALL_INT(ival);
1032 if (ival < 0) {
1033 /* avoid signed overflow on negation; see comments
1034 in PyLong_FromLong above. */
1035 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1036 negative = 1;
1037 }
1038 else {
1039 abs_ival = (unsigned PY_LONG_LONG)ival;
1040 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 /* Count the number of Python digits.
1043 We used to pick 5 ("big enough for anything"), but that's a
1044 waste of time and space given that 5*15 = 75 bits are rarely
1045 needed. */
1046 t = abs_ival;
1047 while (t) {
1048 ++ndigits;
1049 t >>= PyLong_SHIFT;
1050 }
1051 v = _PyLong_New(ndigits);
1052 if (v != NULL) {
1053 digit *p = v->ob_digit;
1054 Py_SIZE(v) = negative ? -ndigits : ndigits;
1055 t = abs_ival;
1056 while (t) {
1057 *p++ = (digit)(t & PyLong_MASK);
1058 t >>= PyLong_SHIFT;
1059 }
1060 }
1061 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001062}
1063
Serhiy Storchaka95949422013-08-27 19:40:23 +03001064/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001065
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001066PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001067PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyLongObject *v;
1070 unsigned PY_LONG_LONG t;
1071 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (ival < PyLong_BASE)
1074 return PyLong_FromLong((long)ival);
1075 /* Count the number of Python digits. */
1076 t = (unsigned PY_LONG_LONG)ival;
1077 while (t) {
1078 ++ndigits;
1079 t >>= PyLong_SHIFT;
1080 }
1081 v = _PyLong_New(ndigits);
1082 if (v != NULL) {
1083 digit *p = v->ob_digit;
1084 Py_SIZE(v) = ndigits;
1085 while (ival) {
1086 *p++ = (digit)(ival & PyLong_MASK);
1087 ival >>= PyLong_SHIFT;
1088 }
1089 }
1090 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001091}
1092
Serhiy Storchaka95949422013-08-27 19:40:23 +03001093/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094
1095PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001096PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyLongObject *v;
1099 size_t abs_ival;
1100 size_t t; /* unsigned so >> doesn't propagate sign bit */
1101 int ndigits = 0;
1102 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 CHECK_SMALL_INT(ival);
1105 if (ival < 0) {
1106 /* avoid signed overflow when ival = SIZE_T_MIN */
1107 abs_ival = (size_t)(-1-ival)+1;
1108 negative = 1;
1109 }
1110 else {
1111 abs_ival = (size_t)ival;
1112 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* Count the number of Python digits. */
1115 t = abs_ival;
1116 while (t) {
1117 ++ndigits;
1118 t >>= PyLong_SHIFT;
1119 }
1120 v = _PyLong_New(ndigits);
1121 if (v != NULL) {
1122 digit *p = v->ob_digit;
1123 Py_SIZE(v) = negative ? -ndigits : ndigits;
1124 t = abs_ival;
1125 while (t) {
1126 *p++ = (digit)(t & PyLong_MASK);
1127 t >>= PyLong_SHIFT;
1128 }
1129 }
1130 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131}
1132
Serhiy Storchaka95949422013-08-27 19:40:23 +03001133/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001134
1135PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001136PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyLongObject *v;
1139 size_t t;
1140 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (ival < PyLong_BASE)
1143 return PyLong_FromLong((long)ival);
1144 /* Count the number of Python digits. */
1145 t = ival;
1146 while (t) {
1147 ++ndigits;
1148 t >>= PyLong_SHIFT;
1149 }
1150 v = _PyLong_New(ndigits);
1151 if (v != NULL) {
1152 digit *p = v->ob_digit;
1153 Py_SIZE(v) = ndigits;
1154 while (ival) {
1155 *p++ = (digit)(ival & PyLong_MASK);
1156 ival >>= PyLong_SHIFT;
1157 }
1158 }
1159 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001160}
1161
Serhiy Storchaka95949422013-08-27 19:40:23 +03001162/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001163 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001164
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001165PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001166PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyLongObject *v;
1169 PY_LONG_LONG bytes;
1170 int one = 1;
1171 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 if (vv == NULL) {
1174 PyErr_BadInternalCall();
1175 return -1;
1176 }
1177 if (!PyLong_Check(vv)) {
1178 PyNumberMethods *nb;
1179 PyObject *io;
1180 if ((nb = vv->ob_type->tp_as_number) == NULL ||
1181 nb->nb_int == NULL) {
1182 PyErr_SetString(PyExc_TypeError, "an integer is required");
1183 return -1;
1184 }
1185 io = (*nb->nb_int) (vv);
1186 if (io == NULL)
1187 return -1;
1188 if (PyLong_Check(io)) {
1189 bytes = PyLong_AsLongLong(io);
1190 Py_DECREF(io);
1191 return bytes;
1192 }
1193 Py_DECREF(io);
1194 PyErr_SetString(PyExc_TypeError, "integer conversion failed");
1195 return -1;
1196 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 v = (PyLongObject*)vv;
1199 switch(Py_SIZE(v)) {
1200 case -1: return -(sdigit)v->ob_digit[0];
1201 case 0: return 0;
1202 case 1: return v->ob_digit[0];
1203 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001204 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1205 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1208 if (res < 0)
1209 return (PY_LONG_LONG)-1;
1210 else
1211 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001212}
1213
Serhiy Storchaka95949422013-08-27 19:40:23 +03001214/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001215 Return -1 and set an error if overflow occurs. */
1216
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001217unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001218PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyLongObject *v;
1221 unsigned PY_LONG_LONG bytes;
1222 int one = 1;
1223 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001224
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001225 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyErr_BadInternalCall();
1227 return (unsigned PY_LONG_LONG)-1;
1228 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001229 if (!PyLong_Check(vv)) {
1230 PyErr_SetString(PyExc_TypeError, "an integer is required");
1231 return (unsigned PY_LONG_LONG)-1;
1232 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 v = (PyLongObject*)vv;
1235 switch(Py_SIZE(v)) {
1236 case 0: return 0;
1237 case 1: return v->ob_digit[0];
1238 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001239
Mark Dickinson22b20182010-05-10 21:27:53 +00001240 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1241 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1244 if (res < 0)
1245 return (unsigned PY_LONG_LONG)res;
1246 else
1247 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001248}
Tim Petersd1a7da62001-06-13 00:35:57 +00001249
Serhiy Storchaka95949422013-08-27 19:40:23 +03001250/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001251 Returns -1 and sets an error condition if an error occurs. */
1252
Guido van Rossumddefaf32007-01-14 03:31:43 +00001253static unsigned PY_LONG_LONG
1254_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 register PyLongObject *v;
1257 unsigned PY_LONG_LONG x;
1258 Py_ssize_t i;
1259 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 if (vv == NULL || !PyLong_Check(vv)) {
1262 PyErr_BadInternalCall();
1263 return (unsigned long) -1;
1264 }
1265 v = (PyLongObject *)vv;
1266 switch(Py_SIZE(v)) {
1267 case 0: return 0;
1268 case 1: return v->ob_digit[0];
1269 }
1270 i = Py_SIZE(v);
1271 sign = 1;
1272 x = 0;
1273 if (i < 0) {
1274 sign = -1;
1275 i = -i;
1276 }
1277 while (--i >= 0) {
1278 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1279 }
1280 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001281}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001282
1283unsigned PY_LONG_LONG
1284PyLong_AsUnsignedLongLongMask(register PyObject *op)
1285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 PyNumberMethods *nb;
1287 PyLongObject *lo;
1288 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (op && PyLong_Check(op))
1291 return _PyLong_AsUnsignedLongLongMask(op);
Guido van Rossumddefaf32007-01-14 03:31:43 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
1294 nb->nb_int == NULL) {
1295 PyErr_SetString(PyExc_TypeError, "an integer is required");
1296 return (unsigned PY_LONG_LONG)-1;
1297 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 lo = (PyLongObject*) (*nb->nb_int) (op);
1300 if (lo == NULL)
1301 return (unsigned PY_LONG_LONG)-1;
1302 if (PyLong_Check(lo)) {
1303 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1304 Py_DECREF(lo);
1305 if (PyErr_Occurred())
1306 return (unsigned PY_LONG_LONG)-1;
1307 return val;
1308 }
1309 else
1310 {
1311 Py_DECREF(lo);
1312 PyErr_SetString(PyExc_TypeError,
1313 "nb_int should return int object");
1314 return (unsigned PY_LONG_LONG)-1;
1315 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001316}
Tim Petersd1a7da62001-06-13 00:35:57 +00001317#undef IS_LITTLE_ENDIAN
1318
Serhiy Storchaka95949422013-08-27 19:40:23 +03001319/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001320 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001321
Mark Dickinson8d48b432011-10-23 20:47:14 +01001322 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1323 the result. Otherwise *overflow is 0.
1324
1325 For other errors (e.g., TypeError), return -1 and set an error condition.
1326 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001327*/
1328
1329PY_LONG_LONG
1330PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* This version by Tim Peters */
1333 register PyLongObject *v;
1334 unsigned PY_LONG_LONG x, prev;
1335 PY_LONG_LONG res;
1336 Py_ssize_t i;
1337 int sign;
1338 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 *overflow = 0;
1341 if (vv == NULL) {
1342 PyErr_BadInternalCall();
1343 return -1;
1344 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (!PyLong_Check(vv)) {
1347 PyNumberMethods *nb;
1348 nb = vv->ob_type->tp_as_number;
1349 if (nb == NULL || nb->nb_int == NULL) {
1350 PyErr_SetString(PyExc_TypeError,
1351 "an integer is required");
1352 return -1;
1353 }
1354 vv = (*nb->nb_int) (vv);
1355 if (vv == NULL)
1356 return -1;
1357 do_decref = 1;
1358 if (!PyLong_Check(vv)) {
1359 Py_DECREF(vv);
1360 PyErr_SetString(PyExc_TypeError,
1361 "nb_int should return int object");
1362 return -1;
1363 }
1364 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 res = -1;
1367 v = (PyLongObject *)vv;
1368 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 switch (i) {
1371 case -1:
1372 res = -(sdigit)v->ob_digit[0];
1373 break;
1374 case 0:
1375 res = 0;
1376 break;
1377 case 1:
1378 res = v->ob_digit[0];
1379 break;
1380 default:
1381 sign = 1;
1382 x = 0;
1383 if (i < 0) {
1384 sign = -1;
1385 i = -(i);
1386 }
1387 while (--i >= 0) {
1388 prev = x;
1389 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1390 if ((x >> PyLong_SHIFT) != prev) {
1391 *overflow = sign;
1392 goto exit;
1393 }
1394 }
1395 /* Haven't lost any bits, but casting to long requires extra
1396 * care (see comment above).
1397 */
1398 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1399 res = (PY_LONG_LONG)x * sign;
1400 }
1401 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1402 res = PY_LLONG_MIN;
1403 }
1404 else {
1405 *overflow = sign;
1406 /* res is already set to -1 */
1407 }
1408 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001409 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (do_decref) {
1411 Py_DECREF(vv);
1412 }
1413 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001414}
1415
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001416#endif /* HAVE_LONG_LONG */
1417
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001418#define CHECK_BINOP(v,w) \
1419 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001420 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1421 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001422 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001423
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001424/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1425 2**k if d is nonzero, else 0. */
1426
1427static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1429 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001430};
1431
1432static int
1433bits_in_digit(digit d)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 int d_bits = 0;
1436 while (d >= 32) {
1437 d_bits += 6;
1438 d >>= 6;
1439 }
1440 d_bits += (int)BitLengthTable[d];
1441 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001442}
1443
Tim Peters877a2122002-08-12 05:09:36 +00001444/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1445 * is modified in place, by adding y to it. Carries are propagated as far as
1446 * x[m-1], and the remaining carry (0 or 1) is returned.
1447 */
1448static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001449v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 Py_ssize_t i;
1452 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 assert(m >= n);
1455 for (i = 0; i < n; ++i) {
1456 carry += x[i] + y[i];
1457 x[i] = carry & PyLong_MASK;
1458 carry >>= PyLong_SHIFT;
1459 assert((carry & 1) == carry);
1460 }
1461 for (; carry && i < m; ++i) {
1462 carry += x[i];
1463 x[i] = carry & PyLong_MASK;
1464 carry >>= PyLong_SHIFT;
1465 assert((carry & 1) == carry);
1466 }
1467 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001468}
1469
1470/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1471 * is modified in place, by subtracting y from it. Borrows are propagated as
1472 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1473 */
1474static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001475v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 Py_ssize_t i;
1478 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 assert(m >= n);
1481 for (i = 0; i < n; ++i) {
1482 borrow = x[i] - y[i] - borrow;
1483 x[i] = borrow & PyLong_MASK;
1484 borrow >>= PyLong_SHIFT;
1485 borrow &= 1; /* keep only 1 sign bit */
1486 }
1487 for (; borrow && i < m; ++i) {
1488 borrow = x[i] - borrow;
1489 x[i] = borrow & PyLong_MASK;
1490 borrow >>= PyLong_SHIFT;
1491 borrow &= 1;
1492 }
1493 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001494}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001495
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001496/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1497 * result in z[0:m], and return the d bits shifted out of the top.
1498 */
1499static digit
1500v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 Py_ssize_t i;
1503 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 assert(0 <= d && d < PyLong_SHIFT);
1506 for (i=0; i < m; i++) {
1507 twodigits acc = (twodigits)a[i] << d | carry;
1508 z[i] = (digit)acc & PyLong_MASK;
1509 carry = (digit)(acc >> PyLong_SHIFT);
1510 }
1511 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001512}
1513
1514/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1515 * result in z[0:m], and return the d bits shifted out of the bottom.
1516 */
1517static digit
1518v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 Py_ssize_t i;
1521 digit carry = 0;
1522 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 assert(0 <= d && d < PyLong_SHIFT);
1525 for (i=m; i-- > 0;) {
1526 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1527 carry = (digit)acc & mask;
1528 z[i] = (digit)(acc >> d);
1529 }
1530 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001531}
1532
Tim Peters212e6142001-07-14 12:23:19 +00001533/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1534 in pout, and returning the remainder. pin and pout point at the LSD.
1535 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001536 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001537 immutable. */
1538
1539static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001540inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 assert(n > 0 && n <= PyLong_MASK);
1545 pin += size;
1546 pout += size;
1547 while (--size >= 0) {
1548 digit hi;
1549 rem = (rem << PyLong_SHIFT) | *--pin;
1550 *--pout = hi = (digit)(rem / n);
1551 rem -= (twodigits)hi * n;
1552 }
1553 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001554}
1555
Serhiy Storchaka95949422013-08-27 19:40:23 +03001556/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001557 (as function result) and the remainder (through *prem).
1558 The sign of a is ignored; n should not be zero. */
1559
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001560static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001561divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 const Py_ssize_t size = ABS(Py_SIZE(a));
1564 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 assert(n > 0 && n <= PyLong_MASK);
1567 z = _PyLong_New(size);
1568 if (z == NULL)
1569 return NULL;
1570 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1571 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001572}
1573
Serhiy Storchaka95949422013-08-27 19:40:23 +03001574/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001575 string. (Return value is non-shared so that callers can modify the
1576 returned value if necessary.) */
1577
Victor Stinnerd3f08822012-05-29 12:57:52 +02001578static int
1579long_to_decimal_string_internal(PyObject *aa,
1580 PyObject **p_output,
1581 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 PyLongObject *scratch, *a;
1584 PyObject *str;
1585 Py_ssize_t size, strlen, size_a, i, j;
1586 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001588 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 a = (PyLongObject *)aa;
1591 if (a == NULL || !PyLong_Check(a)) {
1592 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001593 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
1595 size_a = ABS(Py_SIZE(a));
1596 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 /* quick and dirty upper bound for the number of digits
1599 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 But log2(a) < size_a * PyLong_SHIFT, and
1604 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1605 > 3 * _PyLong_DECIMAL_SHIFT
1606 */
1607 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1608 PyErr_SetString(PyExc_OverflowError,
1609 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001610 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 }
1612 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1613 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1614 scratch = _PyLong_New(size);
1615 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001616 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* convert array of base _PyLong_BASE digits in pin to an array of
1619 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1620 Volume 2 (3rd edn), section 4.4, Method 1b). */
1621 pin = a->ob_digit;
1622 pout = scratch->ob_digit;
1623 size = 0;
1624 for (i = size_a; --i >= 0; ) {
1625 digit hi = pin[i];
1626 for (j = 0; j < size; j++) {
1627 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1628 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1629 pout[j] = (digit)(z - (twodigits)hi *
1630 _PyLong_DECIMAL_BASE);
1631 }
1632 while (hi) {
1633 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1634 hi /= _PyLong_DECIMAL_BASE;
1635 }
1636 /* check for keyboard interrupt */
1637 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001638 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001639 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001640 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 }
1642 /* pout should have at least one digit, so that the case when a = 0
1643 works correctly */
1644 if (size == 0)
1645 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* calculate exact length of output string, and allocate */
1648 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1649 tenpow = 10;
1650 rem = pout[size-1];
1651 while (rem >= tenpow) {
1652 tenpow *= 10;
1653 strlen++;
1654 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001655 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001656 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1657 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001658 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001659 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001660 kind = writer->kind;
1661 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001663 else {
1664 str = PyUnicode_New(strlen, '9');
1665 if (str == NULL) {
1666 Py_DECREF(scratch);
1667 return -1;
1668 }
1669 kind = PyUnicode_KIND(str);
1670 }
1671
1672#define WRITE_DIGITS(TYPE) \
1673 do { \
1674 if (writer) \
1675 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1676 else \
1677 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1678 \
1679 *p = '\0'; \
1680 /* pout[0] through pout[size-2] contribute exactly \
1681 _PyLong_DECIMAL_SHIFT digits each */ \
1682 for (i=0; i < size - 1; i++) { \
1683 rem = pout[i]; \
1684 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1685 *--p = '0' + rem % 10; \
1686 rem /= 10; \
1687 } \
1688 } \
1689 /* pout[size-1]: always produce at least one decimal digit */ \
1690 rem = pout[i]; \
1691 do { \
1692 *--p = '0' + rem % 10; \
1693 rem /= 10; \
1694 } while (rem != 0); \
1695 \
1696 /* and sign */ \
1697 if (negative) \
1698 *--p = '-'; \
1699 \
1700 /* check we've counted correctly */ \
1701 if (writer) \
1702 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1703 else \
1704 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1705 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 if (kind == PyUnicode_1BYTE_KIND) {
1709 Py_UCS1 *p;
1710 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001712 else if (kind == PyUnicode_2BYTE_KIND) {
1713 Py_UCS2 *p;
1714 WRITE_DIGITS(Py_UCS2);
1715 }
1716 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001718 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 WRITE_DIGITS(Py_UCS4);
1720 }
1721#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001724 if (writer) {
1725 writer->pos += strlen;
1726 }
1727 else {
1728 assert(_PyUnicode_CheckConsistency(str, 1));
1729 *p_output = (PyObject *)str;
1730 }
1731 return 0;
1732}
1733
1734static PyObject *
1735long_to_decimal_string(PyObject *aa)
1736{
1737 PyObject *v;
1738 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1739 return NULL;
1740 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001741}
1742
Serhiy Storchaka95949422013-08-27 19:40:23 +03001743/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001744 which should be one of 2, 8 or 16. Return a string object.
1745 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1746 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001747
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748static int
1749long_format_binary(PyObject *aa, int base, int alternate,
1750 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001754 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001756 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001757 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001759
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (a == NULL || !PyLong_Check(a)) {
1762 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 }
1765 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001766 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* Compute a rough upper bound for the length of the string */
1769 switch (base) {
1770 case 16:
1771 bits = 4;
1772 break;
1773 case 8:
1774 bits = 3;
1775 break;
1776 case 2:
1777 bits = 1;
1778 break;
1779 default:
1780 assert(0); /* shouldn't ever get here */
1781 bits = 0; /* to silence gcc warning */
1782 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001783
Mark Dickinsone2846542012-04-20 21:21:24 +01001784 /* Compute exact length 'sz' of output string. */
1785 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001786 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001787 }
1788 else {
1789 Py_ssize_t size_a_in_bits;
1790 /* Ensure overflow doesn't occur during computation of sz. */
1791 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1792 PyErr_SetString(PyExc_OverflowError,
1793 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001794 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001795 }
1796 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1797 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001798 /* Allow 1 character for a '-' sign. */
1799 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1800 }
1801 if (alternate) {
1802 /* 2 characters for prefix */
1803 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001804 }
1805
Victor Stinnerd3f08822012-05-29 12:57:52 +02001806 if (writer) {
1807 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1808 return -1;
1809 kind = writer->kind;
1810 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 }
1812 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 v = PyUnicode_New(sz, 'x');
1814 if (v == NULL)
1815 return -1;
1816 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001818
Victor Stinnerd3f08822012-05-29 12:57:52 +02001819#define WRITE_DIGITS(TYPE) \
1820 do { \
1821 if (writer) \
1822 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1823 else \
1824 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1825 \
1826 if (size_a == 0) { \
1827 *--p = '0'; \
1828 } \
1829 else { \
1830 /* JRH: special case for power-of-2 bases */ \
1831 twodigits accum = 0; \
1832 int accumbits = 0; /* # of bits in accum */ \
1833 Py_ssize_t i; \
1834 for (i = 0; i < size_a; ++i) { \
1835 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1836 accumbits += PyLong_SHIFT; \
1837 assert(accumbits >= bits); \
1838 do { \
1839 char cdigit; \
1840 cdigit = (char)(accum & (base - 1)); \
1841 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1842 *--p = cdigit; \
1843 accumbits -= bits; \
1844 accum >>= bits; \
1845 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1846 } \
1847 } \
1848 \
1849 if (alternate) { \
1850 if (base == 16) \
1851 *--p = 'x'; \
1852 else if (base == 8) \
1853 *--p = 'o'; \
1854 else /* (base == 2) */ \
1855 *--p = 'b'; \
1856 *--p = '0'; \
1857 } \
1858 if (negative) \
1859 *--p = '-'; \
1860 if (writer) \
1861 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1862 else \
1863 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1864 } while (0)
1865
1866 if (kind == PyUnicode_1BYTE_KIND) {
1867 Py_UCS1 *p;
1868 WRITE_DIGITS(Py_UCS1);
1869 }
1870 else if (kind == PyUnicode_2BYTE_KIND) {
1871 Py_UCS2 *p;
1872 WRITE_DIGITS(Py_UCS2);
1873 }
1874 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001875 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001876 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001877 WRITE_DIGITS(Py_UCS4);
1878 }
1879#undef WRITE_DIGITS
1880
1881 if (writer) {
1882 writer->pos += sz;
1883 }
1884 else {
1885 assert(_PyUnicode_CheckConsistency(v, 1));
1886 *p_output = v;
1887 }
1888 return 0;
1889}
1890
1891PyObject *
1892_PyLong_Format(PyObject *obj, int base)
1893{
1894 PyObject *str;
1895 int err;
1896 if (base == 10)
1897 err = long_to_decimal_string_internal(obj, &str, NULL);
1898 else
1899 err = long_format_binary(obj, base, 1, &str, NULL);
1900 if (err == -1)
1901 return NULL;
1902 return str;
1903}
1904
1905int
1906_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1907 PyObject *obj,
1908 int base, int alternate)
1909{
1910 if (base == 10)
1911 return long_to_decimal_string_internal(obj, NULL, writer);
1912 else
1913 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001914}
1915
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916/* Table of digit values for 8-bit string -> integer conversion.
1917 * '0' maps to 0, ..., '9' maps to 9.
1918 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1919 * All other indices map to 37.
1920 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001921 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001922 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001923unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1925 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1926 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1927 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1928 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1929 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1930 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1931 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1932 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1933 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1934 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1935 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1936 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1937 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1938 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1939 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001940};
1941
1942/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001943 * is a power of 2 (2, 4, 8, 16, or 32). *str is set to point to the first
Serhiy Storchaka95949422013-08-27 19:40:23 +03001944 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001945 * The point to this routine is that it takes time linear in the number of
1946 * string characters.
1947 */
1948static PyLongObject *
1949long_from_binary_base(char **str, int base)
1950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 char *p = *str;
1952 char *start = p;
1953 int bits_per_char;
1954 Py_ssize_t n;
1955 PyLongObject *z;
1956 twodigits accum;
1957 int bits_in_accum;
1958 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1961 n = base;
1962 for (bits_per_char = -1; n; ++bits_per_char)
1963 n >>= 1;
1964 /* n <- total # of bits needed, while setting p to end-of-string */
1965 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1966 ++p;
1967 *str = p;
1968 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1969 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1970 if (n / bits_per_char < p - start) {
1971 PyErr_SetString(PyExc_ValueError,
1972 "int string too large to convert");
1973 return NULL;
1974 }
1975 n = n / PyLong_SHIFT;
1976 z = _PyLong_New(n);
1977 if (z == NULL)
1978 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001979 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 * from least to most significant in both.
1981 */
1982 accum = 0;
1983 bits_in_accum = 0;
1984 pdigit = z->ob_digit;
1985 while (--p >= start) {
1986 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1987 assert(k >= 0 && k < base);
1988 accum |= (twodigits)k << bits_in_accum;
1989 bits_in_accum += bits_per_char;
1990 if (bits_in_accum >= PyLong_SHIFT) {
1991 *pdigit++ = (digit)(accum & PyLong_MASK);
1992 assert(pdigit - z->ob_digit <= n);
1993 accum >>= PyLong_SHIFT;
1994 bits_in_accum -= PyLong_SHIFT;
1995 assert(bits_in_accum < PyLong_SHIFT);
1996 }
1997 }
1998 if (bits_in_accum) {
1999 assert(bits_in_accum <= PyLong_SHIFT);
2000 *pdigit++ = (digit)accum;
2001 assert(pdigit - z->ob_digit <= n);
2002 }
2003 while (pdigit - z->ob_digit < n)
2004 *pdigit++ = 0;
2005 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002006}
2007
Serhiy Storchaka95949422013-08-27 19:40:23 +03002008/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002009 * ignored.
2010 *
2011 * If successful, a PyLong object will be returned and 'pend' will be pointing
2012 * to the first unused byte unless it's NULL.
2013 *
2014 * If unsuccessful, NULL will be returned.
2015 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002016PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002017PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 int sign = 1, error_if_nonzero = 0;
2020 char *start, *orig_str = str;
2021 PyLongObject *z = NULL;
2022 PyObject *strobj;
2023 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 if ((base != 0 && base < 2) || base > 36) {
2026 PyErr_SetString(PyExc_ValueError,
2027 "int() arg 2 must be >= 2 and <= 36");
2028 return NULL;
2029 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002030 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 str++;
2032 if (*str == '+')
2033 ++str;
2034 else if (*str == '-') {
2035 ++str;
2036 sign = -1;
2037 }
2038 if (base == 0) {
2039 if (str[0] != '0')
2040 base = 10;
2041 else if (str[1] == 'x' || str[1] == 'X')
2042 base = 16;
2043 else if (str[1] == 'o' || str[1] == 'O')
2044 base = 8;
2045 else if (str[1] == 'b' || str[1] == 'B')
2046 base = 2;
2047 else {
2048 /* "old" (C-style) octal literal, now invalid.
2049 it might still be zero though */
2050 error_if_nonzero = 1;
2051 base = 10;
2052 }
2053 }
2054 if (str[0] == '0' &&
2055 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2056 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2057 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2058 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 start = str;
2061 if ((base & (base - 1)) == 0)
2062 z = long_from_binary_base(&str, base);
2063 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064/***
2065Binary bases can be converted in time linear in the number of digits, because
2066Python's representation base is binary. Other bases (including decimal!) use
2067the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002068
Thomas Wouters477c8d52006-05-27 19:21:47 +00002069First some math: the largest integer that can be expressed in N base-B digits
2070is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2071case number of Python digits needed to hold it is the smallest integer n s.t.
2072
2073 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2074 BASE**n >= B**N [taking logs to base BASE]
2075 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2076
2077The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002078this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002079and the result is computed into it.
2080
2081The input string is actually treated as being in base base**i (i.e., i digits
2082are processed at a time), where two more static arrays hold:
2083
2084 convwidth_base[base] = the largest integer i such that base**i <= BASE
2085 convmultmax_base[base] = base ** convwidth_base[base]
2086
2087The first of these is the largest i such that i consecutive input digits
2088must fit in a single Python digit. The second is effectively the input
2089base we're really using.
2090
2091Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2092convmultmax_base[base], the result is "simply"
2093
2094 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2095
2096where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002097
2098Error analysis: as above, the number of Python digits `n` needed is worst-
2099case
2100
2101 n >= N * log(B)/log(BASE)
2102
2103where `N` is the number of input digits in base `B`. This is computed via
2104
2105 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2106
2107below. Two numeric concerns are how much space this can waste, and whether
2108the computed result can be too small. To be concrete, assume BASE = 2**15,
2109which is the default (and it's unlikely anyone changes that).
2110
2111Waste isn't a problem: provided the first input digit isn't 0, the difference
2112between the worst-case input with N digits and the smallest input with N
2113digits is about a factor of B, but B is small compared to BASE so at most
2114one allocated Python digit can remain unused on that count. If
2115N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2116and adding 1 returns a result 1 larger than necessary. However, that can't
2117happen: whenever B is a power of 2, long_from_binary_base() is called
2118instead, and it's impossible for B**i to be an integer power of 2**15 when
2119B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2120an exact integer when B is not a power of 2, since B**i has a prime factor
2121other than 2 in that case, but (2**15)**j's only prime factor is 2).
2122
2123The computed result can be too small if the true value of N*log(B)/log(BASE)
2124is a little bit larger than an exact integer, but due to roundoff errors (in
2125computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2126yields a numeric result a little less than that integer. Unfortunately, "how
2127close can a transcendental function get to an integer over some range?"
2128questions are generally theoretically intractable. Computer analysis via
2129continued fractions is practical: expand log(B)/log(BASE) via continued
2130fractions, giving a sequence i/j of "the best" rational approximations. Then
2131j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2132we can get very close to being in trouble, but very rarely. For example,
213376573 is a denominator in one of the continued-fraction approximations to
2134log(10)/log(2**15), and indeed:
2135
2136 >>> log(10)/log(2**15)*76573
2137 16958.000000654003
2138
2139is very close to an integer. If we were working with IEEE single-precision,
2140rounding errors could kill us. Finding worst cases in IEEE double-precision
2141requires better-than-double-precision log() functions, and Tim didn't bother.
2142Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002143new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002144This should happen extremely rarely, and in fact I don't have a test case
2145that triggers it(!). Instead the code was tested by artificially allocating
2146just 1 digit at the start, so that the copying code was exercised for every
2147digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002148***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 register twodigits c; /* current input character */
2150 Py_ssize_t size_z;
2151 int i;
2152 int convwidth;
2153 twodigits convmultmax, convmult;
2154 digit *pz, *pzstop;
2155 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 static double log_base_BASE[37] = {0.0e0,};
2158 static int convwidth_base[37] = {0,};
2159 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (log_base_BASE[base] == 0.0) {
2162 twodigits convmax = base;
2163 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164
Mark Dickinson22b20182010-05-10 21:27:53 +00002165 log_base_BASE[base] = (log((double)base) /
2166 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 for (;;) {
2168 twodigits next = convmax * base;
2169 if (next > PyLong_BASE)
2170 break;
2171 convmax = next;
2172 ++i;
2173 }
2174 convmultmax_base[base] = convmax;
2175 assert(i > 0);
2176 convwidth_base[base] = i;
2177 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 /* Find length of the string of numeric characters. */
2180 scan = str;
2181 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2182 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002183
Serhiy Storchaka95949422013-08-27 19:40:23 +03002184 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 * integer with this base and length. Note that there's no
2186 * need to initialize z->ob_digit -- no slot is read up before
2187 * being stored into.
2188 */
2189 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2190 /* Uncomment next line to test exceedingly rare copy code */
2191 /* size_z = 1; */
2192 assert(size_z > 0);
2193 z = _PyLong_New(size_z);
2194 if (z == NULL)
2195 return NULL;
2196 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* `convwidth` consecutive input digits are treated as a single
2199 * digit in base `convmultmax`.
2200 */
2201 convwidth = convwidth_base[base];
2202 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 /* Work ;-) */
2205 while (str < scan) {
2206 /* grab up to convwidth digits from the input string */
2207 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2208 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2209 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002210 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 assert(c < PyLong_BASE);
2212 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 convmult = convmultmax;
2215 /* Calculate the shift only if we couldn't get
2216 * convwidth digits.
2217 */
2218 if (i != convwidth) {
2219 convmult = base;
2220 for ( ; i > 1; --i)
2221 convmult *= base;
2222 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Multiply z by convmult, and add c. */
2225 pz = z->ob_digit;
2226 pzstop = pz + Py_SIZE(z);
2227 for (; pz < pzstop; ++pz) {
2228 c += (twodigits)*pz * convmult;
2229 *pz = (digit)(c & PyLong_MASK);
2230 c >>= PyLong_SHIFT;
2231 }
2232 /* carry off the current end? */
2233 if (c) {
2234 assert(c < PyLong_BASE);
2235 if (Py_SIZE(z) < size_z) {
2236 *pz = (digit)c;
2237 ++Py_SIZE(z);
2238 }
2239 else {
2240 PyLongObject *tmp;
2241 /* Extremely rare. Get more space. */
2242 assert(Py_SIZE(z) == size_z);
2243 tmp = _PyLong_New(size_z + 1);
2244 if (tmp == NULL) {
2245 Py_DECREF(z);
2246 return NULL;
2247 }
2248 memcpy(tmp->ob_digit,
2249 z->ob_digit,
2250 sizeof(digit) * size_z);
2251 Py_DECREF(z);
2252 z = tmp;
2253 z->ob_digit[size_z] = (digit)c;
2254 ++size_z;
2255 }
2256 }
2257 }
2258 }
2259 if (z == NULL)
2260 return NULL;
2261 if (error_if_nonzero) {
2262 /* reset the base to 0, else the exception message
2263 doesn't make too much sense */
2264 base = 0;
2265 if (Py_SIZE(z) != 0)
2266 goto onError;
2267 /* there might still be other problems, therefore base
2268 remains zero here for the same reason */
2269 }
2270 if (str == start)
2271 goto onError;
2272 if (sign < 0)
2273 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002274 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 str++;
2276 if (*str != '\0')
2277 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002279 z = maybe_small_long(z);
2280 if (z == NULL)
2281 return NULL;
2282 if (pend != NULL)
2283 *pend = str;
2284 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002285
Mark Dickinson22b20182010-05-10 21:27:53 +00002286 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002287 if (pend != NULL)
2288 *pend = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 Py_XDECREF(z);
2290 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2291 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2292 if (strobj == NULL)
2293 return NULL;
2294 PyErr_Format(PyExc_ValueError,
2295 "invalid literal for int() with base %d: %R",
2296 base, strobj);
2297 Py_DECREF(strobj);
2298 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002299}
2300
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002301/* Since PyLong_FromString doesn't have a length parameter,
2302 * check here for possible NULs in the string.
2303 *
2304 * Reports an invalid literal as a bytes object.
2305 */
2306PyObject *
2307_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2308{
2309 PyObject *result, *strobj;
2310 char *end = NULL;
2311
2312 result = PyLong_FromString((char*)s, &end, base);
2313 if (end == NULL || (result != NULL && end == s + len))
2314 return result;
2315 Py_XDECREF(result);
2316 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2317 if (strobj != NULL) {
2318 PyErr_Format(PyExc_ValueError,
2319 "invalid literal for int() with base %d: %R",
2320 base, strobj);
2321 Py_DECREF(strobj);
2322 }
2323 return NULL;
2324}
2325
Guido van Rossum9e896b32000-04-05 20:11:21 +00002326PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002327PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002328{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2330 if (unicode == NULL)
2331 return NULL;
2332 v = PyLong_FromUnicodeObject(unicode, base);
2333 Py_DECREF(unicode);
2334 return v;
2335}
2336
2337PyObject *
2338PyLong_FromUnicodeObject(PyObject *u, int base)
2339{
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002340 PyObject *result, *asciidig, *strobj;
2341 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002342 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002343
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002344 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002345 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002347 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002348 if (buffer == NULL) {
2349 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002350 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2351 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002353 else {
2354 result = PyLong_FromString(buffer, &end, base);
2355 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2356 Py_DECREF(asciidig);
2357 return result;
2358 }
2359 Py_DECREF(asciidig);
2360 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002361 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002362 strobj = PySequence_GetSlice(u, 0, 200);
2363 if (strobj != NULL) {
2364 PyErr_Format(PyExc_ValueError,
2365 "invalid literal for int() with base %d: %R",
2366 base, strobj);
2367 Py_DECREF(strobj);
2368 }
2369 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370}
2371
Tim Peters9f688bf2000-07-07 15:53:28 +00002372/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002373static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002375static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376
Serhiy Storchaka95949422013-08-27 19:40:23 +03002377/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378
Guido van Rossume32e0141992-01-19 16:31:05 +00002379static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002380long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2384 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (size_b == 0) {
2387 PyErr_SetString(PyExc_ZeroDivisionError,
2388 "integer division or modulo by zero");
2389 return -1;
2390 }
2391 if (size_a < size_b ||
2392 (size_a == size_b &&
2393 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2394 /* |a| < |b|. */
2395 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2396 if (*pdiv == NULL)
2397 return -1;
2398 Py_INCREF(a);
2399 *prem = (PyLongObject *) a;
2400 return 0;
2401 }
2402 if (size_b == 1) {
2403 digit rem = 0;
2404 z = divrem1(a, b->ob_digit[0], &rem);
2405 if (z == NULL)
2406 return -1;
2407 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2408 if (*prem == NULL) {
2409 Py_DECREF(z);
2410 return -1;
2411 }
2412 }
2413 else {
2414 z = x_divrem(a, b, prem);
2415 if (z == NULL)
2416 return -1;
2417 }
2418 /* Set the signs.
2419 The quotient z has the sign of a*b;
2420 the remainder r has the sign of a,
2421 so a = b*z + r. */
2422 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2423 NEGATE(z);
2424 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2425 NEGATE(*prem);
2426 *pdiv = maybe_small_long(z);
2427 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002428}
2429
Serhiy Storchaka95949422013-08-27 19:40:23 +03002430/* Unsigned int division with remainder -- the algorithm. The arguments v1
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002431 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002433static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002434x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 PyLongObject *v, *w, *a;
2437 Py_ssize_t i, k, size_v, size_w;
2438 int d;
2439 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2440 twodigits vv;
2441 sdigit zhi;
2442 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2445 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2446 handle the special case when the initial estimate q for a quotient
2447 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2448 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 /* allocate space; w will also be used to hold the final remainder */
2451 size_v = ABS(Py_SIZE(v1));
2452 size_w = ABS(Py_SIZE(w1));
2453 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2454 v = _PyLong_New(size_v+1);
2455 if (v == NULL) {
2456 *prem = NULL;
2457 return NULL;
2458 }
2459 w = _PyLong_New(size_w);
2460 if (w == NULL) {
2461 Py_DECREF(v);
2462 *prem = NULL;
2463 return NULL;
2464 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2467 shift v1 left by the same amount. Results go into w and v. */
2468 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2469 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2470 assert(carry == 0);
2471 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2472 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2473 v->ob_digit[size_v] = carry;
2474 size_v++;
2475 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2478 at most (and usually exactly) k = size_v - size_w digits. */
2479 k = size_v - size_w;
2480 assert(k >= 0);
2481 a = _PyLong_New(k);
2482 if (a == NULL) {
2483 Py_DECREF(w);
2484 Py_DECREF(v);
2485 *prem = NULL;
2486 return NULL;
2487 }
2488 v0 = v->ob_digit;
2489 w0 = w->ob_digit;
2490 wm1 = w0[size_w-1];
2491 wm2 = w0[size_w-2];
2492 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2493 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2494 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002497 Py_DECREF(a);
2498 Py_DECREF(w);
2499 Py_DECREF(v);
2500 *prem = NULL;
2501 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002502 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* estimate quotient digit q; may overestimate by 1 (rare) */
2505 vtop = vk[size_w];
2506 assert(vtop <= wm1);
2507 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2508 q = (digit)(vv / wm1);
2509 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2510 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2511 | vk[size_w-2])) {
2512 --q;
2513 r += wm1;
2514 if (r >= PyLong_BASE)
2515 break;
2516 }
2517 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2520 zhi = 0;
2521 for (i = 0; i < size_w; ++i) {
2522 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2523 -PyLong_BASE * q <= z < PyLong_BASE */
2524 z = (sdigit)vk[i] + zhi -
2525 (stwodigits)q * (stwodigits)w0[i];
2526 vk[i] = (digit)z & PyLong_MASK;
2527 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002528 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 /* add w back if q was too large (this branch taken rarely) */
2532 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2533 if ((sdigit)vtop + zhi < 0) {
2534 carry = 0;
2535 for (i = 0; i < size_w; ++i) {
2536 carry += vk[i] + w0[i];
2537 vk[i] = carry & PyLong_MASK;
2538 carry >>= PyLong_SHIFT;
2539 }
2540 --q;
2541 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /* store quotient digit */
2544 assert(q < PyLong_BASE);
2545 *--ak = q;
2546 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 /* unshift remainder; we reuse w to store the result */
2549 carry = v_rshift(w0, v0, size_w, d);
2550 assert(carry==0);
2551 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 *prem = long_normalize(w);
2554 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002555}
2556
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002557/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2558 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2559 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2560 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2561 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2562 -1.0. */
2563
2564/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2565#if DBL_MANT_DIG == 53
2566#define EXP2_DBL_MANT_DIG 9007199254740992.0
2567#else
2568#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2569#endif
2570
2571double
2572_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2575 /* See below for why x_digits is always large enough. */
2576 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2577 double dx;
2578 /* Correction term for round-half-to-even rounding. For a digit x,
2579 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2580 multiple of 4, rounding ties to a multiple of 8. */
2581 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 a_size = ABS(Py_SIZE(a));
2584 if (a_size == 0) {
2585 /* Special case for 0: significand 0.0, exponent 0. */
2586 *e = 0;
2587 return 0.0;
2588 }
2589 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2590 /* The following is an overflow-free version of the check
2591 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2592 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2593 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2594 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002595 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2599 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 Number of digits needed for result: write // for floor division.
2602 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2611 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2614 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2615 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 in both cases.
2622 */
2623 if (a_bits <= DBL_MANT_DIG + 2) {
2624 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2625 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2626 x_size = 0;
2627 while (x_size < shift_digits)
2628 x_digits[x_size++] = 0;
2629 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2630 (int)shift_bits);
2631 x_size += a_size;
2632 x_digits[x_size++] = rem;
2633 }
2634 else {
2635 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2636 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2637 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2638 a_size - shift_digits, (int)shift_bits);
2639 x_size = a_size - shift_digits;
2640 /* For correct rounding below, we need the least significant
2641 bit of x to be 'sticky' for this shift: if any of the bits
2642 shifted out was nonzero, we set the least significant bit
2643 of x. */
2644 if (rem)
2645 x_digits[0] |= 1;
2646 else
2647 while (shift_digits > 0)
2648 if (a->ob_digit[--shift_digits]) {
2649 x_digits[0] |= 1;
2650 break;
2651 }
2652 }
Victor Stinner63941882011-09-29 00:42:28 +02002653 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 /* Round, and convert to double. */
2656 x_digits[0] += half_even_correction[x_digits[0] & 7];
2657 dx = x_digits[--x_size];
2658 while (x_size > 0)
2659 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 /* Rescale; make correction if result is 1.0. */
2662 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2663 if (dx == 1.0) {
2664 if (a_bits == PY_SSIZE_T_MAX)
2665 goto overflow;
2666 dx = 0.5;
2667 a_bits += 1;
2668 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 *e = a_bits;
2671 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002672
2673 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 /* exponent > PY_SSIZE_T_MAX */
2675 PyErr_SetString(PyExc_OverflowError,
2676 "huge integer: number of bits overflows a Py_ssize_t");
2677 *e = 0;
2678 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002679}
2680
Serhiy Storchaka95949422013-08-27 19:40:23 +03002681/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002682 using the round-half-to-even rule in the case of a tie. */
2683
2684double
2685PyLong_AsDouble(PyObject *v)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 Py_ssize_t exponent;
2688 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002689
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002690 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 PyErr_BadInternalCall();
2692 return -1.0;
2693 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002694 if (!PyLong_Check(v)) {
2695 PyErr_SetString(PyExc_TypeError, "an integer is required");
2696 return -1.0;
2697 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2699 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2700 PyErr_SetString(PyExc_OverflowError,
2701 "long int too large to convert to float");
2702 return -1.0;
2703 }
2704 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002705}
2706
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002707/* Methods */
2708
2709static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002710long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002713}
2714
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002715static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002716long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 if (Py_SIZE(a) != Py_SIZE(b)) {
2721 sign = Py_SIZE(a) - Py_SIZE(b);
2722 }
2723 else {
2724 Py_ssize_t i = ABS(Py_SIZE(a));
2725 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2726 ;
2727 if (i < 0)
2728 sign = 0;
2729 else {
2730 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2731 if (Py_SIZE(a) < 0)
2732 sign = -sign;
2733 }
2734 }
2735 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002736}
2737
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002738#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002740
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002741static PyObject *
2742long_richcompare(PyObject *self, PyObject *other, int op)
2743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 int result;
2745 PyObject *v;
2746 CHECK_BINOP(self, other);
2747 if (self == other)
2748 result = 0;
2749 else
2750 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2751 /* Convert the return value to a Boolean */
2752 switch (op) {
2753 case Py_EQ:
2754 v = TEST_COND(result == 0);
2755 break;
2756 case Py_NE:
2757 v = TEST_COND(result != 0);
2758 break;
2759 case Py_LE:
2760 v = TEST_COND(result <= 0);
2761 break;
2762 case Py_GE:
2763 v = TEST_COND(result >= 0);
2764 break;
2765 case Py_LT:
2766 v = TEST_COND(result == -1);
2767 break;
2768 case Py_GT:
2769 v = TEST_COND(result == 1);
2770 break;
2771 default:
2772 PyErr_BadArgument();
2773 return NULL;
2774 }
2775 Py_INCREF(v);
2776 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002777}
2778
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002779static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002780long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002781{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002782 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 Py_ssize_t i;
2784 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 i = Py_SIZE(v);
2787 switch(i) {
2788 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2789 case 0: return 0;
2790 case 1: return v->ob_digit[0];
2791 }
2792 sign = 1;
2793 x = 0;
2794 if (i < 0) {
2795 sign = -1;
2796 i = -(i);
2797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002799 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2800 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2801 _PyHASH_MODULUS.
2802
2803 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2804 amounts to a rotation of the bits of x. To see this, write
2805
2806 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2807
2808 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2809 PyLong_SHIFT bits of x (those that are shifted out of the
2810 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2811 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2812 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2813 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2814 congruent to y modulo _PyHASH_MODULUS. So
2815
2816 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2817
2818 The right-hand side is just the result of rotating the
2819 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2820 not all _PyHASH_BITS bits of x are 1s, the same is true
2821 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2822 the reduction of x*2**PyLong_SHIFT modulo
2823 _PyHASH_MODULUS. */
2824 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2825 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002827 if (x >= _PyHASH_MODULUS)
2828 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 }
2830 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002831 if (x == (Py_uhash_t)-1)
2832 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002833 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002834}
2835
2836
Serhiy Storchaka95949422013-08-27 19:40:23 +03002837/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002838
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002839static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002840x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2843 PyLongObject *z;
2844 Py_ssize_t i;
2845 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 /* Ensure a is the larger of the two: */
2848 if (size_a < size_b) {
2849 { PyLongObject *temp = a; a = b; b = temp; }
2850 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002851 size_a = size_b;
2852 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 }
2854 z = _PyLong_New(size_a+1);
2855 if (z == NULL)
2856 return NULL;
2857 for (i = 0; i < size_b; ++i) {
2858 carry += a->ob_digit[i] + b->ob_digit[i];
2859 z->ob_digit[i] = carry & PyLong_MASK;
2860 carry >>= PyLong_SHIFT;
2861 }
2862 for (; i < size_a; ++i) {
2863 carry += a->ob_digit[i];
2864 z->ob_digit[i] = carry & PyLong_MASK;
2865 carry >>= PyLong_SHIFT;
2866 }
2867 z->ob_digit[i] = carry;
2868 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002869}
2870
2871/* Subtract the absolute values of two integers. */
2872
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002873static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002874x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2877 PyLongObject *z;
2878 Py_ssize_t i;
2879 int sign = 1;
2880 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 /* Ensure a is the larger of the two: */
2883 if (size_a < size_b) {
2884 sign = -1;
2885 { PyLongObject *temp = a; a = b; b = temp; }
2886 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002887 size_a = size_b;
2888 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 }
2890 else if (size_a == size_b) {
2891 /* Find highest digit where a and b differ: */
2892 i = size_a;
2893 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2894 ;
2895 if (i < 0)
2896 return (PyLongObject *)PyLong_FromLong(0);
2897 if (a->ob_digit[i] < b->ob_digit[i]) {
2898 sign = -1;
2899 { PyLongObject *temp = a; a = b; b = temp; }
2900 }
2901 size_a = size_b = i+1;
2902 }
2903 z = _PyLong_New(size_a);
2904 if (z == NULL)
2905 return NULL;
2906 for (i = 0; i < size_b; ++i) {
2907 /* The following assumes unsigned arithmetic
2908 works module 2**N for some N>PyLong_SHIFT. */
2909 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2910 z->ob_digit[i] = borrow & PyLong_MASK;
2911 borrow >>= PyLong_SHIFT;
2912 borrow &= 1; /* Keep only one sign bit */
2913 }
2914 for (; i < size_a; ++i) {
2915 borrow = a->ob_digit[i] - borrow;
2916 z->ob_digit[i] = borrow & PyLong_MASK;
2917 borrow >>= PyLong_SHIFT;
2918 borrow &= 1; /* Keep only one sign bit */
2919 }
2920 assert(borrow == 0);
2921 if (sign < 0)
2922 NEGATE(z);
2923 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002924}
2925
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002926static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002927long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2934 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2935 MEDIUM_VALUE(b));
2936 return result;
2937 }
2938 if (Py_SIZE(a) < 0) {
2939 if (Py_SIZE(b) < 0) {
2940 z = x_add(a, b);
2941 if (z != NULL && Py_SIZE(z) != 0)
2942 Py_SIZE(z) = -(Py_SIZE(z));
2943 }
2944 else
2945 z = x_sub(b, a);
2946 }
2947 else {
2948 if (Py_SIZE(b) < 0)
2949 z = x_sub(a, b);
2950 else
2951 z = x_add(a, b);
2952 }
2953 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002954}
2955
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002956static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002957long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2964 PyObject* r;
2965 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2966 return r;
2967 }
2968 if (Py_SIZE(a) < 0) {
2969 if (Py_SIZE(b) < 0)
2970 z = x_sub(a, b);
2971 else
2972 z = x_add(a, b);
2973 if (z != NULL && Py_SIZE(z) != 0)
2974 Py_SIZE(z) = -(Py_SIZE(z));
2975 }
2976 else {
2977 if (Py_SIZE(b) < 0)
2978 z = x_add(a, b);
2979 else
2980 z = x_sub(a, b);
2981 }
2982 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002983}
2984
Tim Peters5af4e6c2002-08-12 02:31:19 +00002985/* Grade school multiplication, ignoring the signs.
2986 * Returns the absolute value of the product, or NULL if error.
2987 */
2988static PyLongObject *
2989x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002991 PyLongObject *z;
2992 Py_ssize_t size_a = ABS(Py_SIZE(a));
2993 Py_ssize_t size_b = ABS(Py_SIZE(b));
2994 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 z = _PyLong_New(size_a + size_b);
2997 if (z == NULL)
2998 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3001 if (a == b) {
3002 /* Efficient squaring per HAC, Algorithm 14.16:
3003 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3004 * Gives slightly less than a 2x speedup when a == b,
3005 * via exploiting that each entry in the multiplication
3006 * pyramid appears twice (except for the size_a squares).
3007 */
3008 for (i = 0; i < size_a; ++i) {
3009 twodigits carry;
3010 twodigits f = a->ob_digit[i];
3011 digit *pz = z->ob_digit + (i << 1);
3012 digit *pa = a->ob_digit + i + 1;
3013 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003015 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003016 Py_DECREF(z);
3017 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003018 });
Tim Peters0973b992004-08-29 22:16:50 +00003019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 carry = *pz + f * f;
3021 *pz++ = (digit)(carry & PyLong_MASK);
3022 carry >>= PyLong_SHIFT;
3023 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 /* Now f is added in twice in each column of the
3026 * pyramid it appears. Same as adding f<<1 once.
3027 */
3028 f <<= 1;
3029 while (pa < paend) {
3030 carry += *pz + *pa++ * f;
3031 *pz++ = (digit)(carry & PyLong_MASK);
3032 carry >>= PyLong_SHIFT;
3033 assert(carry <= (PyLong_MASK << 1));
3034 }
3035 if (carry) {
3036 carry += *pz;
3037 *pz++ = (digit)(carry & PyLong_MASK);
3038 carry >>= PyLong_SHIFT;
3039 }
3040 if (carry)
3041 *pz += (digit)(carry & PyLong_MASK);
3042 assert((carry >> PyLong_SHIFT) == 0);
3043 }
3044 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003045 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 for (i = 0; i < size_a; ++i) {
3047 twodigits carry = 0;
3048 twodigits f = a->ob_digit[i];
3049 digit *pz = z->ob_digit + i;
3050 digit *pb = b->ob_digit;
3051 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003054 Py_DECREF(z);
3055 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003056 });
Tim Peters0973b992004-08-29 22:16:50 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 while (pb < pbend) {
3059 carry += *pz + *pb++ * f;
3060 *pz++ = (digit)(carry & PyLong_MASK);
3061 carry >>= PyLong_SHIFT;
3062 assert(carry <= PyLong_MASK);
3063 }
3064 if (carry)
3065 *pz += (digit)(carry & PyLong_MASK);
3066 assert((carry >> PyLong_SHIFT) == 0);
3067 }
3068 }
3069 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003070}
3071
3072/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003073 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003074 split, and sets low and high such that abs(n) == (high << size) + low,
3075 viewing the shift as being by digits. The sign bit is ignored, and
3076 the return values are >= 0.
3077 Returns 0 on success, -1 on failure.
3078*/
3079static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003080kmul_split(PyLongObject *n,
3081 Py_ssize_t size,
3082 PyLongObject **high,
3083 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 PyLongObject *hi, *lo;
3086 Py_ssize_t size_lo, size_hi;
3087 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089 size_lo = MIN(size_n, size);
3090 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 if ((hi = _PyLong_New(size_hi)) == NULL)
3093 return -1;
3094 if ((lo = _PyLong_New(size_lo)) == NULL) {
3095 Py_DECREF(hi);
3096 return -1;
3097 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3100 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 *high = long_normalize(hi);
3103 *low = long_normalize(lo);
3104 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003105}
3106
Tim Peters60004642002-08-12 22:01:34 +00003107static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3108
Tim Peters5af4e6c2002-08-12 02:31:19 +00003109/* Karatsuba multiplication. Ignores the input signs, and returns the
3110 * absolute value of the product (or NULL if error).
3111 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3112 */
3113static PyLongObject *
3114k_mul(PyLongObject *a, PyLongObject *b)
3115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 Py_ssize_t asize = ABS(Py_SIZE(a));
3117 Py_ssize_t bsize = ABS(Py_SIZE(b));
3118 PyLongObject *ah = NULL;
3119 PyLongObject *al = NULL;
3120 PyLongObject *bh = NULL;
3121 PyLongObject *bl = NULL;
3122 PyLongObject *ret = NULL;
3123 PyLongObject *t1, *t2, *t3;
3124 Py_ssize_t shift; /* the number of digits we split off */
3125 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003127 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3128 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3129 * Then the original product is
3130 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3131 * By picking X to be a power of 2, "*X" is just shifting, and it's
3132 * been reduced to 3 multiplies on numbers half the size.
3133 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 /* We want to split based on the larger number; fiddle so that b
3136 * is largest.
3137 */
3138 if (asize > bsize) {
3139 t1 = a;
3140 a = b;
3141 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 i = asize;
3144 asize = bsize;
3145 bsize = i;
3146 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* Use gradeschool math when either number is too small. */
3149 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3150 if (asize <= i) {
3151 if (asize == 0)
3152 return (PyLongObject *)PyLong_FromLong(0);
3153 else
3154 return x_mul(a, b);
3155 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* If a is small compared to b, splitting on b gives a degenerate
3158 * case with ah==0, and Karatsuba may be (even much) less efficient
3159 * than "grade school" then. However, we can still win, by viewing
3160 * b as a string of "big digits", each of width a->ob_size. That
3161 * leads to a sequence of balanced calls to k_mul.
3162 */
3163 if (2 * asize <= bsize)
3164 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 /* Split a & b into hi & lo pieces. */
3167 shift = bsize >> 1;
3168 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3169 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 if (a == b) {
3172 bh = ah;
3173 bl = al;
3174 Py_INCREF(bh);
3175 Py_INCREF(bl);
3176 }
3177 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 /* The plan:
3180 * 1. Allocate result space (asize + bsize digits: that's always
3181 * enough).
3182 * 2. Compute ah*bh, and copy into result at 2*shift.
3183 * 3. Compute al*bl, and copy into result at 0. Note that this
3184 * can't overlap with #2.
3185 * 4. Subtract al*bl from the result, starting at shift. This may
3186 * underflow (borrow out of the high digit), but we don't care:
3187 * we're effectively doing unsigned arithmetic mod
3188 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3189 * borrows and carries out of the high digit can be ignored.
3190 * 5. Subtract ah*bh from the result, starting at shift.
3191 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3192 * at shift.
3193 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 /* 1. Allocate result space. */
3196 ret = _PyLong_New(asize + bsize);
3197 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003198#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 /* Fill with trash, to catch reference to uninitialized digits. */
3200 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003201#endif
Tim Peters44121a62002-08-12 06:17:58 +00003202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3204 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3205 assert(Py_SIZE(t1) >= 0);
3206 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3207 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3208 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* Zero-out the digits higher than the ah*bh copy. */
3211 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3212 if (i)
3213 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3214 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 /* 3. t2 <- al*bl, and copy into the low digits. */
3217 if ((t2 = k_mul(al, bl)) == NULL) {
3218 Py_DECREF(t1);
3219 goto fail;
3220 }
3221 assert(Py_SIZE(t2) >= 0);
3222 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3223 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 /* Zero out remaining digits. */
3226 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3227 if (i)
3228 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3231 * because it's fresher in cache.
3232 */
3233 i = Py_SIZE(ret) - shift; /* # digits after shift */
3234 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3235 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3238 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3241 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3242 Py_DECREF(ah);
3243 Py_DECREF(al);
3244 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003246 if (a == b) {
3247 t2 = t1;
3248 Py_INCREF(t2);
3249 }
3250 else if ((t2 = x_add(bh, bl)) == NULL) {
3251 Py_DECREF(t1);
3252 goto fail;
3253 }
3254 Py_DECREF(bh);
3255 Py_DECREF(bl);
3256 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 t3 = k_mul(t1, t2);
3259 Py_DECREF(t1);
3260 Py_DECREF(t2);
3261 if (t3 == NULL) goto fail;
3262 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 /* Add t3. It's not obvious why we can't run out of room here.
3265 * See the (*) comment after this function.
3266 */
3267 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3268 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003271
Mark Dickinson22b20182010-05-10 21:27:53 +00003272 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 Py_XDECREF(ret);
3274 Py_XDECREF(ah);
3275 Py_XDECREF(al);
3276 Py_XDECREF(bh);
3277 Py_XDECREF(bl);
3278 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003279}
3280
Tim Petersd6974a52002-08-13 20:37:51 +00003281/* (*) Why adding t3 can't "run out of room" above.
3282
Tim Petersab86c2b2002-08-15 20:06:00 +00003283Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3284to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003285
Tim Petersab86c2b2002-08-15 20:06:00 +000032861. For any integer i, i = c(i/2) + f(i/2). In particular,
3287 bsize = c(bsize/2) + f(bsize/2).
32882. shift = f(bsize/2)
32893. asize <= bsize
32904. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3291 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003292
Tim Petersab86c2b2002-08-15 20:06:00 +00003293We allocated asize + bsize result digits, and add t3 into them at an offset
3294of shift. This leaves asize+bsize-shift allocated digit positions for t3
3295to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3296asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003297
Tim Petersab86c2b2002-08-15 20:06:00 +00003298bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3299at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003300
Tim Petersab86c2b2002-08-15 20:06:00 +00003301If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3302digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3303most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003304
Tim Petersab86c2b2002-08-15 20:06:00 +00003305The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003306
Tim Petersab86c2b2002-08-15 20:06:00 +00003307 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003308
Tim Petersab86c2b2002-08-15 20:06:00 +00003309and we have asize + c(bsize/2) available digit positions. We need to show
3310this is always enough. An instance of c(bsize/2) cancels out in both, so
3311the question reduces to whether asize digits is enough to hold
3312(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3313then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3314asize 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 +00003315digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003316asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003317c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3318is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3319bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003320
Tim Peters48d52c02002-08-14 17:07:32 +00003321Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3322clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3323ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003324*/
3325
Tim Peters60004642002-08-12 22:01:34 +00003326/* b has at least twice the digits of a, and a is big enough that Karatsuba
3327 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3328 * of slices, each with a->ob_size digits, and multiply the slices by a,
3329 * one at a time. This gives k_mul balanced inputs to work with, and is
3330 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003331 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003332 * single-width slice overlap between successive partial sums).
3333 */
3334static PyLongObject *
3335k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 const Py_ssize_t asize = ABS(Py_SIZE(a));
3338 Py_ssize_t bsize = ABS(Py_SIZE(b));
3339 Py_ssize_t nbdone; /* # of b digits already multiplied */
3340 PyLongObject *ret;
3341 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 assert(asize > KARATSUBA_CUTOFF);
3344 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 /* Allocate result space, and zero it out. */
3347 ret = _PyLong_New(asize + bsize);
3348 if (ret == NULL)
3349 return NULL;
3350 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 /* Successive slices of b are copied into bslice. */
3353 bslice = _PyLong_New(asize);
3354 if (bslice == NULL)
3355 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 nbdone = 0;
3358 while (bsize > 0) {
3359 PyLongObject *product;
3360 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 /* Multiply the next slice of b by a. */
3363 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3364 nbtouse * sizeof(digit));
3365 Py_SIZE(bslice) = nbtouse;
3366 product = k_mul(a, bslice);
3367 if (product == NULL)
3368 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 /* Add into result. */
3371 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3372 product->ob_digit, Py_SIZE(product));
3373 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 bsize -= nbtouse;
3376 nbdone += nbtouse;
3377 }
Tim Peters60004642002-08-12 22:01:34 +00003378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003379 Py_DECREF(bslice);
3380 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003381
Mark Dickinson22b20182010-05-10 21:27:53 +00003382 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 Py_DECREF(ret);
3384 Py_XDECREF(bslice);
3385 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003386}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003387
3388static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003389long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 /* fast path for single-digit multiplication */
3396 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3397 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003398#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003400#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* if we don't have long long then we're almost certainly
3402 using 15-bit digits, so v will fit in a long. In the
3403 unlikely event that we're using 30-bit digits on a platform
3404 without long long, a large v will just cause us to fall
3405 through to the general multiplication code below. */
3406 if (v >= LONG_MIN && v <= LONG_MAX)
3407 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003408#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 z = k_mul(a, b);
3412 /* Negate if exactly one of the inputs is negative. */
3413 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3414 NEGATE(z);
3415 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003416}
3417
Guido van Rossume32e0141992-01-19 16:31:05 +00003418/* The / and % operators are now defined in terms of divmod().
3419 The expression a mod b has the value a - b*floor(a/b).
3420 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003421 |a| by |b|, with the sign of a. This is also expressed
3422 as a - b*trunc(a/b), if trunc truncates towards zero.
3423 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 a b a rem b a mod b
3425 13 10 3 3
3426 -13 10 -3 7
3427 13 -10 3 -7
3428 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003429 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003430 have different signs. We then subtract one from the 'div'
3431 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003432
Tim Peters47e52ee2004-08-30 02:44:38 +00003433/* Compute
3434 * *pdiv, *pmod = divmod(v, w)
3435 * NULL can be passed for pdiv or pmod, in which case that part of
3436 * the result is simply thrown away. The caller owns a reference to
3437 * each of these it requests (does not pass NULL for).
3438 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003439static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003440l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 if (long_divrem(v, w, &div, &mod) < 0)
3446 return -1;
3447 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3448 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3449 PyLongObject *temp;
3450 PyLongObject *one;
3451 temp = (PyLongObject *) long_add(mod, w);
3452 Py_DECREF(mod);
3453 mod = temp;
3454 if (mod == NULL) {
3455 Py_DECREF(div);
3456 return -1;
3457 }
3458 one = (PyLongObject *) PyLong_FromLong(1L);
3459 if (one == NULL ||
3460 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3461 Py_DECREF(mod);
3462 Py_DECREF(div);
3463 Py_XDECREF(one);
3464 return -1;
3465 }
3466 Py_DECREF(one);
3467 Py_DECREF(div);
3468 div = temp;
3469 }
3470 if (pdiv != NULL)
3471 *pdiv = div;
3472 else
3473 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003475 if (pmod != NULL)
3476 *pmod = mod;
3477 else
3478 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003481}
3482
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003483static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003484long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 CHECK_BINOP(a, b);
3489 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3490 div = NULL;
3491 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003492}
3493
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003494/* PyLong/PyLong -> float, with correctly rounded result. */
3495
3496#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3497#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3498
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003499static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003500long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 PyLongObject *a, *b, *x;
3503 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3504 digit mask, low;
3505 int inexact, negate, a_is_small, b_is_small;
3506 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003508 CHECK_BINOP(v, w);
3509 a = (PyLongObject *)v;
3510 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003512 /*
3513 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3516 1. choose a suitable integer 'shift'
3517 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3518 3. adjust x for correct rounding
3519 4. convert x to a double dx with the same value
3520 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3525 returns either 0.0 or -0.0, depending on the sign of b. For a and
3526 b both nonzero, ignore signs of a and b, and add the sign back in
3527 at the end. Now write a_bits and b_bits for the bit lengths of a
3528 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3529 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3534 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3535 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3536 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 1. The integer 'shift' is chosen so that x has the right number of
3541 bits for a double, plus two or three extra bits that will be used
3542 in the rounding decisions. Writing a_bits and b_bits for the
3543 number of significant bits in a and b respectively, a
3544 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 This is fine in the usual case, but if a/b is smaller than the
3549 smallest normal float then it can lead to double rounding on an
3550 IEEE 754 platform, giving incorrectly rounded results. So we
3551 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 2. The quantity x is computed by first shifting a (left -shift bits
3556 if shift <= 0, right shift bits if shift > 0) and then dividing by
3557 b. For both the shift and the division, we keep track of whether
3558 the result is inexact, in a flag 'inexact'; this information is
3559 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 With the choice of shift above, together with our assumption that
3562 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3563 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3566 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 For float representability, we need x/2**extra_bits <
3571 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3572 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 To round, we just modify the bottom digit of x in-place; this can
3577 end up giving a digit with value > PyLONG_MASK, but that's not a
3578 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 With the original choices for shift above, extra_bits will always
3581 be 2 or 3. Then rounding under the round-half-to-even rule, we
3582 round up iff the most significant of the extra bits is 1, and
3583 either: (a) the computation of x in step 2 had an inexact result,
3584 or (b) at least one other of the extra bits is 1, or (c) the least
3585 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 4. Conversion to a double is straightforward; all floating-point
3588 operations involved in the conversion are exact, so there's no
3589 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3592 The result will always be exactly representable as a double, except
3593 in the case that it overflows. To avoid dependence on the exact
3594 behaviour of ldexp on overflow, we check for overflow before
3595 applying ldexp. The result of ldexp is adjusted for sign before
3596 returning.
3597 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 /* Reduce to case where a and b are both positive. */
3600 a_size = ABS(Py_SIZE(a));
3601 b_size = ABS(Py_SIZE(b));
3602 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3603 if (b_size == 0) {
3604 PyErr_SetString(PyExc_ZeroDivisionError,
3605 "division by zero");
3606 goto error;
3607 }
3608 if (a_size == 0)
3609 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 /* Fast path for a and b small (exactly representable in a double).
3612 Relies on floating-point division being correctly rounded; results
3613 may be subject to double rounding on x86 machines that operate with
3614 the x87 FPU set to 64-bit precision. */
3615 a_is_small = a_size <= MANT_DIG_DIGITS ||
3616 (a_size == MANT_DIG_DIGITS+1 &&
3617 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3618 b_is_small = b_size <= MANT_DIG_DIGITS ||
3619 (b_size == MANT_DIG_DIGITS+1 &&
3620 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3621 if (a_is_small && b_is_small) {
3622 double da, db;
3623 da = a->ob_digit[--a_size];
3624 while (a_size > 0)
3625 da = da * PyLong_BASE + a->ob_digit[--a_size];
3626 db = b->ob_digit[--b_size];
3627 while (b_size > 0)
3628 db = db * PyLong_BASE + b->ob_digit[--b_size];
3629 result = da / db;
3630 goto success;
3631 }
Tim Peterse2a60002001-09-04 06:17:36 +00003632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003633 /* Catch obvious cases of underflow and overflow */
3634 diff = a_size - b_size;
3635 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3636 /* Extreme overflow */
3637 goto overflow;
3638 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3639 /* Extreme underflow */
3640 goto underflow_or_zero;
3641 /* Next line is now safe from overflowing a Py_ssize_t */
3642 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3643 bits_in_digit(b->ob_digit[b_size - 1]);
3644 /* Now diff = a_bits - b_bits. */
3645 if (diff > DBL_MAX_EXP)
3646 goto overflow;
3647 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3648 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 /* Choose value for shift; see comments for step 1 above. */
3651 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 /* x = abs(a * 2**-shift) */
3656 if (shift <= 0) {
3657 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3658 digit rem;
3659 /* x = a << -shift */
3660 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3661 /* In practice, it's probably impossible to end up
3662 here. Both a and b would have to be enormous,
3663 using close to SIZE_T_MAX bytes of memory each. */
3664 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003665 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 goto error;
3667 }
3668 x = _PyLong_New(a_size + shift_digits + 1);
3669 if (x == NULL)
3670 goto error;
3671 for (i = 0; i < shift_digits; i++)
3672 x->ob_digit[i] = 0;
3673 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3674 a_size, -shift % PyLong_SHIFT);
3675 x->ob_digit[a_size + shift_digits] = rem;
3676 }
3677 else {
3678 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3679 digit rem;
3680 /* x = a >> shift */
3681 assert(a_size >= shift_digits);
3682 x = _PyLong_New(a_size - shift_digits);
3683 if (x == NULL)
3684 goto error;
3685 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3686 a_size - shift_digits, shift % PyLong_SHIFT);
3687 /* set inexact if any of the bits shifted out is nonzero */
3688 if (rem)
3689 inexact = 1;
3690 while (!inexact && shift_digits > 0)
3691 if (a->ob_digit[--shift_digits])
3692 inexact = 1;
3693 }
3694 long_normalize(x);
3695 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3698 reference to x, so it's safe to modify it in-place. */
3699 if (b_size == 1) {
3700 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3701 b->ob_digit[0]);
3702 long_normalize(x);
3703 if (rem)
3704 inexact = 1;
3705 }
3706 else {
3707 PyLongObject *div, *rem;
3708 div = x_divrem(x, b, &rem);
3709 Py_DECREF(x);
3710 x = div;
3711 if (x == NULL)
3712 goto error;
3713 if (Py_SIZE(rem))
3714 inexact = 1;
3715 Py_DECREF(rem);
3716 }
3717 x_size = ABS(Py_SIZE(x));
3718 assert(x_size > 0); /* result of division is never zero */
3719 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 /* The number of extra bits that have to be rounded away. */
3722 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3723 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003725 /* Round by directly modifying the low digit of x. */
3726 mask = (digit)1 << (extra_bits - 1);
3727 low = x->ob_digit[0] | inexact;
3728 if (low & mask && low & (3*mask-1))
3729 low += mask;
3730 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 /* Convert x to a double dx; the conversion is exact. */
3733 dx = x->ob_digit[--x_size];
3734 while (x_size > 0)
3735 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3736 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 /* Check whether ldexp result will overflow a double. */
3739 if (shift + x_bits >= DBL_MAX_EXP &&
3740 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3741 goto overflow;
3742 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003743
3744 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003746
3747 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003749
3750 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 PyErr_SetString(PyExc_OverflowError,
3752 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003753 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003755}
3756
3757static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003758long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 CHECK_BINOP(a, b);
3763
3764 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3765 mod = NULL;
3766 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003767}
3768
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003769static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003770long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003772 PyLongObject *div, *mod;
3773 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3778 return NULL;
3779 }
3780 z = PyTuple_New(2);
3781 if (z != NULL) {
3782 PyTuple_SetItem(z, 0, (PyObject *) div);
3783 PyTuple_SetItem(z, 1, (PyObject *) mod);
3784 }
3785 else {
3786 Py_DECREF(div);
3787 Py_DECREF(mod);
3788 }
3789 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003790}
3791
Tim Peters47e52ee2004-08-30 02:44:38 +00003792/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003793static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003794long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3797 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 PyLongObject *z = NULL; /* accumulated result */
3800 Py_ssize_t i, j, k; /* counters */
3801 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 /* 5-ary values. If the exponent is large enough, table is
3804 * precomputed so that table[i] == a**i % c for i in range(32).
3805 */
3806 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3807 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003809 /* a, b, c = v, w, x */
3810 CHECK_BINOP(v, w);
3811 a = (PyLongObject*)v; Py_INCREF(a);
3812 b = (PyLongObject*)w; Py_INCREF(b);
3813 if (PyLong_Check(x)) {
3814 c = (PyLongObject *)x;
3815 Py_INCREF(x);
3816 }
3817 else if (x == Py_None)
3818 c = NULL;
3819 else {
3820 Py_DECREF(a);
3821 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003822 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 }
Tim Peters4c483c42001-09-05 06:24:58 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3826 if (c) {
3827 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003828 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 goto Error;
3830 }
3831 else {
3832 /* else return a float. This works because we know
3833 that this calls float_pow() which converts its
3834 arguments to double. */
3835 Py_DECREF(a);
3836 Py_DECREF(b);
3837 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3838 }
3839 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 if (c) {
3842 /* if modulus == 0:
3843 raise ValueError() */
3844 if (Py_SIZE(c) == 0) {
3845 PyErr_SetString(PyExc_ValueError,
3846 "pow() 3rd argument cannot be 0");
3847 goto Error;
3848 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003850 /* if modulus < 0:
3851 negativeOutput = True
3852 modulus = -modulus */
3853 if (Py_SIZE(c) < 0) {
3854 negativeOutput = 1;
3855 temp = (PyLongObject *)_PyLong_Copy(c);
3856 if (temp == NULL)
3857 goto Error;
3858 Py_DECREF(c);
3859 c = temp;
3860 temp = NULL;
3861 NEGATE(c);
3862 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003864 /* if modulus == 1:
3865 return 0 */
3866 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3867 z = (PyLongObject *)PyLong_FromLong(0L);
3868 goto Done;
3869 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003870
Tim Peters81a93152013-10-05 16:53:52 -05003871 /* Reduce base by modulus in some cases:
3872 1. If base < 0. Forcing the base non-negative makes things easier.
3873 2. If base is obviously larger than the modulus. The "small
3874 exponent" case later can multiply directly by base repeatedly,
3875 while the "large exponent" case multiplies directly by base 31
3876 times. It can be unboundedly faster to multiply by
3877 base % modulus instead.
3878 We could _always_ do this reduction, but l_divmod() isn't cheap,
3879 so we only do it when it buys something. */
3880 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 if (l_divmod(a, c, NULL, &temp) < 0)
3882 goto Error;
3883 Py_DECREF(a);
3884 a = temp;
3885 temp = NULL;
3886 }
3887 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 /* At this point a, b, and c are guaranteed non-negative UNLESS
3890 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003892 z = (PyLongObject *)PyLong_FromLong(1L);
3893 if (z == NULL)
3894 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 /* Perform a modular reduction, X = X % c, but leave X alone if c
3897 * is NULL.
3898 */
3899#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003900 do { \
3901 if (c != NULL) { \
3902 if (l_divmod(X, c, NULL, &temp) < 0) \
3903 goto Error; \
3904 Py_XDECREF(X); \
3905 X = temp; \
3906 temp = NULL; \
3907 } \
3908 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 /* Multiply two values, then reduce the result:
3911 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003912#define MULT(X, Y, result) \
3913 do { \
3914 temp = (PyLongObject *)long_mul(X, Y); \
3915 if (temp == NULL) \
3916 goto Error; \
3917 Py_XDECREF(result); \
3918 result = temp; \
3919 temp = NULL; \
3920 REDUCE(result); \
3921 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3924 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3925 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3926 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3927 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003930 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003932 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 }
3934 }
3935 }
3936 else {
3937 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3938 Py_INCREF(z); /* still holds 1L */
3939 table[0] = z;
3940 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003941 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3944 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3947 const int index = (bi >> j) & 0x1f;
3948 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003949 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003951 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 }
3953 }
3954 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003956 if (negativeOutput && (Py_SIZE(z) != 0)) {
3957 temp = (PyLongObject *)long_sub(z, c);
3958 if (temp == NULL)
3959 goto Error;
3960 Py_DECREF(z);
3961 z = temp;
3962 temp = NULL;
3963 }
3964 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003965
Mark Dickinson22b20182010-05-10 21:27:53 +00003966 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 if (z != NULL) {
3968 Py_DECREF(z);
3969 z = NULL;
3970 }
3971 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003972 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3974 for (i = 0; i < 32; ++i)
3975 Py_XDECREF(table[i]);
3976 }
3977 Py_DECREF(a);
3978 Py_DECREF(b);
3979 Py_XDECREF(c);
3980 Py_XDECREF(temp);
3981 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003982}
3983
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003984static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003985long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 /* Implement ~x as -(x+1) */
3988 PyLongObject *x;
3989 PyLongObject *w;
3990 if (ABS(Py_SIZE(v)) <=1)
3991 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3992 w = (PyLongObject *)PyLong_FromLong(1L);
3993 if (w == NULL)
3994 return NULL;
3995 x = (PyLongObject *) long_add(v, w);
3996 Py_DECREF(w);
3997 if (x == NULL)
3998 return NULL;
3999 Py_SIZE(x) = -(Py_SIZE(x));
4000 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004001}
4002
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004003static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004004long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 PyLongObject *z;
4007 if (ABS(Py_SIZE(v)) <= 1)
4008 return PyLong_FromLong(-MEDIUM_VALUE(v));
4009 z = (PyLongObject *)_PyLong_Copy(v);
4010 if (z != NULL)
4011 Py_SIZE(z) = -(Py_SIZE(v));
4012 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004013}
4014
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004015static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004016long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004018 if (Py_SIZE(v) < 0)
4019 return long_neg(v);
4020 else
4021 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004022}
4023
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004024static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004025long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004027 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004028}
4029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004030static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004031long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 PyLongObject *z = NULL;
4034 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4035 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004039 if (Py_SIZE(a) < 0) {
4040 /* Right shifting negative numbers is harder */
4041 PyLongObject *a1, *a2;
4042 a1 = (PyLongObject *) long_invert(a);
4043 if (a1 == NULL)
4044 goto rshift_error;
4045 a2 = (PyLongObject *) long_rshift(a1, b);
4046 Py_DECREF(a1);
4047 if (a2 == NULL)
4048 goto rshift_error;
4049 z = (PyLongObject *) long_invert(a2);
4050 Py_DECREF(a2);
4051 }
4052 else {
4053 shiftby = PyLong_AsSsize_t((PyObject *)b);
4054 if (shiftby == -1L && PyErr_Occurred())
4055 goto rshift_error;
4056 if (shiftby < 0) {
4057 PyErr_SetString(PyExc_ValueError,
4058 "negative shift count");
4059 goto rshift_error;
4060 }
4061 wordshift = shiftby / PyLong_SHIFT;
4062 newsize = ABS(Py_SIZE(a)) - wordshift;
4063 if (newsize <= 0)
4064 return PyLong_FromLong(0);
4065 loshift = shiftby % PyLong_SHIFT;
4066 hishift = PyLong_SHIFT - loshift;
4067 lomask = ((digit)1 << hishift) - 1;
4068 himask = PyLong_MASK ^ lomask;
4069 z = _PyLong_New(newsize);
4070 if (z == NULL)
4071 goto rshift_error;
4072 if (Py_SIZE(a) < 0)
4073 Py_SIZE(z) = -(Py_SIZE(z));
4074 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4075 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4076 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004077 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 }
4079 z = long_normalize(z);
4080 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004081 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004083
Guido van Rossumc6913e71991-11-19 20:26:46 +00004084}
4085
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004086static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004087long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 /* This version due to Tim Peters */
4090 PyLongObject *a = (PyLongObject*)v;
4091 PyLongObject *b = (PyLongObject*)w;
4092 PyLongObject *z = NULL;
4093 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4094 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 shiftby = PyLong_AsSsize_t((PyObject *)b);
4099 if (shiftby == -1L && PyErr_Occurred())
4100 goto lshift_error;
4101 if (shiftby < 0) {
4102 PyErr_SetString(PyExc_ValueError, "negative shift count");
4103 goto lshift_error;
4104 }
4105 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4106 wordshift = shiftby / PyLong_SHIFT;
4107 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004109 oldsize = ABS(Py_SIZE(a));
4110 newsize = oldsize + wordshift;
4111 if (remshift)
4112 ++newsize;
4113 z = _PyLong_New(newsize);
4114 if (z == NULL)
4115 goto lshift_error;
4116 if (Py_SIZE(a) < 0)
4117 NEGATE(z);
4118 for (i = 0; i < wordshift; i++)
4119 z->ob_digit[i] = 0;
4120 accum = 0;
4121 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4122 accum |= (twodigits)a->ob_digit[j] << remshift;
4123 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4124 accum >>= PyLong_SHIFT;
4125 }
4126 if (remshift)
4127 z->ob_digit[newsize-1] = (digit)accum;
4128 else
4129 assert(!accum);
4130 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004131 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004132 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004133}
4134
Mark Dickinson27a87a22009-10-25 20:43:34 +00004135/* Compute two's complement of digit vector a[0:m], writing result to
4136 z[0:m]. The digit vector a need not be normalized, but should not
4137 be entirely zero. a and z may point to the same digit vector. */
4138
4139static void
4140v_complement(digit *z, digit *a, Py_ssize_t m)
4141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004142 Py_ssize_t i;
4143 digit carry = 1;
4144 for (i = 0; i < m; ++i) {
4145 carry += a[i] ^ PyLong_MASK;
4146 z[i] = carry & PyLong_MASK;
4147 carry >>= PyLong_SHIFT;
4148 }
4149 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004150}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004151
4152/* Bitwise and/xor/or operations */
4153
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004154static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004155long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004156 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004157 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 int nega, negb, negz;
4160 Py_ssize_t size_a, size_b, size_z, i;
4161 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 /* Bitwise operations for negative numbers operate as though
4164 on a two's complement representation. So convert arguments
4165 from sign-magnitude to two's complement, and convert the
4166 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004168 /* If a is negative, replace it by its two's complement. */
4169 size_a = ABS(Py_SIZE(a));
4170 nega = Py_SIZE(a) < 0;
4171 if (nega) {
4172 z = _PyLong_New(size_a);
4173 if (z == NULL)
4174 return NULL;
4175 v_complement(z->ob_digit, a->ob_digit, size_a);
4176 a = z;
4177 }
4178 else
4179 /* Keep reference count consistent. */
4180 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004182 /* Same for b. */
4183 size_b = ABS(Py_SIZE(b));
4184 negb = Py_SIZE(b) < 0;
4185 if (negb) {
4186 z = _PyLong_New(size_b);
4187 if (z == NULL) {
4188 Py_DECREF(a);
4189 return NULL;
4190 }
4191 v_complement(z->ob_digit, b->ob_digit, size_b);
4192 b = z;
4193 }
4194 else
4195 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 /* Swap a and b if necessary to ensure size_a >= size_b. */
4198 if (size_a < size_b) {
4199 z = a; a = b; b = z;
4200 size_z = size_a; size_a = size_b; size_b = size_z;
4201 negz = nega; nega = negb; negb = negz;
4202 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 /* JRH: The original logic here was to allocate the result value (z)
4205 as the longer of the two operands. However, there are some cases
4206 where the result is guaranteed to be shorter than that: AND of two
4207 positives, OR of two negatives: use the shorter number. AND with
4208 mixed signs: use the positive number. OR with mixed signs: use the
4209 negative number.
4210 */
4211 switch (op) {
4212 case '^':
4213 negz = nega ^ negb;
4214 size_z = size_a;
4215 break;
4216 case '&':
4217 negz = nega & negb;
4218 size_z = negb ? size_a : size_b;
4219 break;
4220 case '|':
4221 negz = nega | negb;
4222 size_z = negb ? size_b : size_a;
4223 break;
4224 default:
4225 PyErr_BadArgument();
4226 return NULL;
4227 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004229 /* We allow an extra digit if z is negative, to make sure that
4230 the final two's complement of z doesn't overflow. */
4231 z = _PyLong_New(size_z + negz);
4232 if (z == NULL) {
4233 Py_DECREF(a);
4234 Py_DECREF(b);
4235 return NULL;
4236 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004238 /* Compute digits for overlap of a and b. */
4239 switch(op) {
4240 case '&':
4241 for (i = 0; i < size_b; ++i)
4242 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4243 break;
4244 case '|':
4245 for (i = 0; i < size_b; ++i)
4246 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4247 break;
4248 case '^':
4249 for (i = 0; i < size_b; ++i)
4250 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4251 break;
4252 default:
4253 PyErr_BadArgument();
4254 return NULL;
4255 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 /* Copy any remaining digits of a, inverting if necessary. */
4258 if (op == '^' && negb)
4259 for (; i < size_z; ++i)
4260 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4261 else if (i < size_z)
4262 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4263 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 /* Complement result if negative. */
4266 if (negz) {
4267 Py_SIZE(z) = -(Py_SIZE(z));
4268 z->ob_digit[size_z] = PyLong_MASK;
4269 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4270 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 Py_DECREF(a);
4273 Py_DECREF(b);
4274 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004275}
4276
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004277static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004278long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 PyObject *c;
4281 CHECK_BINOP(a, b);
4282 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4283 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004284}
4285
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004286static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004287long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 PyObject *c;
4290 CHECK_BINOP(a, b);
4291 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4292 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004293}
4294
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004295static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004296long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004298 PyObject *c;
4299 CHECK_BINOP(a, b);
4300 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4301 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004302}
4303
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004304static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004305long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004307 if (PyLong_CheckExact(v))
4308 Py_INCREF(v);
4309 else
4310 v = _PyLong_Copy((PyLongObject *)v);
4311 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004312}
4313
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004314static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004315long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004317 double result;
4318 result = PyLong_AsDouble(v);
4319 if (result == -1.0 && PyErr_Occurred())
4320 return NULL;
4321 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004322}
4323
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004324static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004325long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004326
Tim Peters6d6c1a32001-08-02 04:15:00 +00004327static PyObject *
4328long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4329{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004330 PyObject *obase = NULL, *x = NULL;
4331 long base;
4332 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004335 if (type != &PyLong_Type)
4336 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004337 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4338 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004339 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004340 if (x == NULL) {
4341 if (obase != NULL) {
4342 PyErr_SetString(PyExc_TypeError,
4343 "int() missing string argument");
4344 return NULL;
4345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004347 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004348 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004350
4351 base = PyLong_AsLongAndOverflow(obase, &overflow);
4352 if (base == -1 && PyErr_Occurred())
4353 return NULL;
4354 if (overflow || (base != 0 && base < 2) || base > 36) {
4355 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004356 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004357 return NULL;
4358 }
4359
4360 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004361 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 if (PyByteArray_Check(x))
4365 string = PyByteArray_AS_STRING(x);
4366 else
4367 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004368 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 }
4370 else {
4371 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004372 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 return NULL;
4374 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004375}
4376
Serhiy Storchaka95949422013-08-27 19:40:23 +03004377/* Wimpy, slow approach to tp_new calls for subtypes of int:
4378 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004379 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004380 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004381*/
4382static PyObject *
4383long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 PyLongObject *tmp, *newobj;
4386 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 assert(PyType_IsSubtype(type, &PyLong_Type));
4389 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4390 if (tmp == NULL)
4391 return NULL;
4392 assert(PyLong_CheckExact(tmp));
4393 n = Py_SIZE(tmp);
4394 if (n < 0)
4395 n = -n;
4396 newobj = (PyLongObject *)type->tp_alloc(type, n);
4397 if (newobj == NULL) {
4398 Py_DECREF(tmp);
4399 return NULL;
4400 }
4401 assert(PyLong_Check(newobj));
4402 Py_SIZE(newobj) = Py_SIZE(tmp);
4403 for (i = 0; i < n; i++)
4404 newobj->ob_digit[i] = tmp->ob_digit[i];
4405 Py_DECREF(tmp);
4406 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004407}
4408
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004409static PyObject *
4410long_getnewargs(PyLongObject *v)
4411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004413}
4414
Guido van Rossumb43daf72007-08-01 18:08:08 +00004415static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004416long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004418}
4419
4420static PyObject *
4421long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004422 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004423}
4424
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004425static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004426long__format__(PyObject *self, PyObject *args)
4427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004429 _PyUnicodeWriter writer;
4430 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4433 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004434
4435 _PyUnicodeWriter_Init(&writer, 0);
4436 ret = _PyLong_FormatAdvancedWriter(
4437 &writer,
4438 self,
4439 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4440 if (ret == -1) {
4441 _PyUnicodeWriter_Dealloc(&writer);
4442 return NULL;
4443 }
4444 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004445}
4446
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004447/* Return a pair (q, r) such that a = b * q + r, and
4448 abs(r) <= abs(b)/2, with equality possible only if q is even.
4449 In other words, q == a / b, rounded to the nearest integer using
4450 round-half-to-even. */
4451
4452PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004453_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004454{
4455 PyLongObject *quo = NULL, *rem = NULL;
4456 PyObject *one = NULL, *twice_rem, *result, *temp;
4457 int cmp, quo_is_odd, quo_is_neg;
4458
4459 /* Equivalent Python code:
4460
4461 def divmod_near(a, b):
4462 q, r = divmod(a, b)
4463 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4464 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4465 # positive, 2 * r < b if b negative.
4466 greater_than_half = 2*r > b if b > 0 else 2*r < b
4467 exactly_half = 2*r == b
4468 if greater_than_half or exactly_half and q % 2 == 1:
4469 q += 1
4470 r -= b
4471 return q, r
4472
4473 */
4474 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4475 PyErr_SetString(PyExc_TypeError,
4476 "non-integer arguments in division");
4477 return NULL;
4478 }
4479
4480 /* Do a and b have different signs? If so, quotient is negative. */
4481 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4482
4483 one = PyLong_FromLong(1L);
4484 if (one == NULL)
4485 return NULL;
4486
4487 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4488 goto error;
4489
4490 /* compare twice the remainder with the divisor, to see
4491 if we need to adjust the quotient and remainder */
4492 twice_rem = long_lshift((PyObject *)rem, one);
4493 if (twice_rem == NULL)
4494 goto error;
4495 if (quo_is_neg) {
4496 temp = long_neg((PyLongObject*)twice_rem);
4497 Py_DECREF(twice_rem);
4498 twice_rem = temp;
4499 if (twice_rem == NULL)
4500 goto error;
4501 }
4502 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4503 Py_DECREF(twice_rem);
4504
4505 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4506 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4507 /* fix up quotient */
4508 if (quo_is_neg)
4509 temp = long_sub(quo, (PyLongObject *)one);
4510 else
4511 temp = long_add(quo, (PyLongObject *)one);
4512 Py_DECREF(quo);
4513 quo = (PyLongObject *)temp;
4514 if (quo == NULL)
4515 goto error;
4516 /* and remainder */
4517 if (quo_is_neg)
4518 temp = long_add(rem, (PyLongObject *)b);
4519 else
4520 temp = long_sub(rem, (PyLongObject *)b);
4521 Py_DECREF(rem);
4522 rem = (PyLongObject *)temp;
4523 if (rem == NULL)
4524 goto error;
4525 }
4526
4527 result = PyTuple_New(2);
4528 if (result == NULL)
4529 goto error;
4530
4531 /* PyTuple_SET_ITEM steals references */
4532 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4533 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4534 Py_DECREF(one);
4535 return result;
4536
4537 error:
4538 Py_XDECREF(quo);
4539 Py_XDECREF(rem);
4540 Py_XDECREF(one);
4541 return NULL;
4542}
4543
Eric Smith8c663262007-08-25 02:26:07 +00004544static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004545long_round(PyObject *self, PyObject *args)
4546{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004547 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004548
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004549 /* To round an integer m to the nearest 10**n (n positive), we make use of
4550 * the divmod_near operation, defined by:
4551 *
4552 * divmod_near(a, b) = (q, r)
4553 *
4554 * where q is the nearest integer to the quotient a / b (the
4555 * nearest even integer in the case of a tie) and r == a - q * b.
4556 * Hence q * b = a - r is the nearest multiple of b to a,
4557 * preferring even multiples in the case of a tie.
4558 *
4559 * So the nearest multiple of 10**n to m is:
4560 *
4561 * m - divmod_near(m, 10**n)[1].
4562 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004563 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4564 return NULL;
4565 if (o_ndigits == NULL)
4566 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004567
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004568 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004569 if (ndigits == NULL)
4570 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004571
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004572 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004573 if (Py_SIZE(ndigits) >= 0) {
4574 Py_DECREF(ndigits);
4575 return long_long(self);
4576 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004577
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004578 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4579 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004581 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004582 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004583 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004584
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004585 result = PyLong_FromLong(10L);
4586 if (result == NULL) {
4587 Py_DECREF(ndigits);
4588 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004590
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004591 temp = long_pow(result, ndigits, Py_None);
4592 Py_DECREF(ndigits);
4593 Py_DECREF(result);
4594 result = temp;
4595 if (result == NULL)
4596 return NULL;
4597
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004598 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004599 Py_DECREF(result);
4600 result = temp;
4601 if (result == NULL)
4602 return NULL;
4603
4604 temp = long_sub((PyLongObject *)self,
4605 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4606 Py_DECREF(result);
4607 result = temp;
4608
4609 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004610}
4611
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004612static PyObject *
4613long_sizeof(PyLongObject *v)
4614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4618 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004619}
4620
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004621static PyObject *
4622long_bit_length(PyLongObject *v)
4623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 PyLongObject *result, *x, *y;
4625 Py_ssize_t ndigits, msd_bits = 0;
4626 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 assert(v != NULL);
4629 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 ndigits = ABS(Py_SIZE(v));
4632 if (ndigits == 0)
4633 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 msd = v->ob_digit[ndigits-1];
4636 while (msd >= 32) {
4637 msd_bits += 6;
4638 msd >>= 6;
4639 }
4640 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4643 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 /* expression above may overflow; use Python integers instead */
4646 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4647 if (result == NULL)
4648 return NULL;
4649 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4650 if (x == NULL)
4651 goto error;
4652 y = (PyLongObject *)long_mul(result, x);
4653 Py_DECREF(x);
4654 if (y == NULL)
4655 goto error;
4656 Py_DECREF(result);
4657 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4660 if (x == NULL)
4661 goto error;
4662 y = (PyLongObject *)long_add(result, x);
4663 Py_DECREF(x);
4664 if (y == NULL)
4665 goto error;
4666 Py_DECREF(result);
4667 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004669 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004670
Mark Dickinson22b20182010-05-10 21:27:53 +00004671 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 Py_DECREF(result);
4673 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004674}
4675
4676PyDoc_STRVAR(long_bit_length_doc,
4677"int.bit_length() -> int\n\
4678\n\
4679Number of bits necessary to represent self in binary.\n\
4680>>> bin(37)\n\
4681'0b100101'\n\
4682>>> (37).bit_length()\n\
46836");
4684
Christian Heimes53876d92008-04-19 00:31:39 +00004685#if 0
4686static PyObject *
4687long_is_finite(PyObject *v)
4688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004689 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004690}
4691#endif
4692
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004693
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004694static PyObject *
4695long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 PyObject *byteorder_str;
4698 PyObject *is_signed_obj = NULL;
4699 Py_ssize_t length;
4700 int little_endian;
4701 int is_signed;
4702 PyObject *bytes;
4703 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4706 &length, &byteorder_str,
4707 &is_signed_obj))
4708 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 if (args != NULL && Py_SIZE(args) > 2) {
4711 PyErr_SetString(PyExc_TypeError,
4712 "'signed' is a keyword-only argument");
4713 return NULL;
4714 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4717 little_endian = 1;
4718 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4719 little_endian = 0;
4720 else {
4721 PyErr_SetString(PyExc_ValueError,
4722 "byteorder must be either 'little' or 'big'");
4723 return NULL;
4724 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 if (is_signed_obj != NULL) {
4727 int cmp = PyObject_IsTrue(is_signed_obj);
4728 if (cmp < 0)
4729 return NULL;
4730 is_signed = cmp ? 1 : 0;
4731 }
4732 else {
4733 /* If the signed argument was omitted, use False as the
4734 default. */
4735 is_signed = 0;
4736 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 if (length < 0) {
4739 PyErr_SetString(PyExc_ValueError,
4740 "length argument must be non-negative");
4741 return NULL;
4742 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004744 bytes = PyBytes_FromStringAndSize(NULL, length);
4745 if (bytes == NULL)
4746 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4749 length, little_endian, is_signed) < 0) {
4750 Py_DECREF(bytes);
4751 return NULL;
4752 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004755}
4756
Mark Dickinson078c2532010-01-30 18:06:17 +00004757PyDoc_STRVAR(long_to_bytes_doc,
4758"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004759\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004760Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004761\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004763raised if the integer is not representable with the given number of\n\
4764bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004765\n\
4766The byteorder argument determines the byte order used to represent the\n\
4767integer. If byteorder is 'big', the most significant byte is at the\n\
4768beginning of the byte array. If byteorder is 'little', the most\n\
4769significant byte is at the end of the byte array. To request the native\n\
4770byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4771\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004772The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004773used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004774is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004775
4776static PyObject *
4777long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779 PyObject *byteorder_str;
4780 PyObject *is_signed_obj = NULL;
4781 int little_endian;
4782 int is_signed;
4783 PyObject *obj;
4784 PyObject *bytes;
4785 PyObject *long_obj;
4786 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4789 &obj, &byteorder_str,
4790 &is_signed_obj))
4791 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 if (args != NULL && Py_SIZE(args) > 2) {
4794 PyErr_SetString(PyExc_TypeError,
4795 "'signed' is a keyword-only argument");
4796 return NULL;
4797 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004799 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4800 little_endian = 1;
4801 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4802 little_endian = 0;
4803 else {
4804 PyErr_SetString(PyExc_ValueError,
4805 "byteorder must be either 'little' or 'big'");
4806 return NULL;
4807 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 if (is_signed_obj != NULL) {
4810 int cmp = PyObject_IsTrue(is_signed_obj);
4811 if (cmp < 0)
4812 return NULL;
4813 is_signed = cmp ? 1 : 0;
4814 }
4815 else {
4816 /* If the signed argument was omitted, use False as the
4817 default. */
4818 is_signed = 0;
4819 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004821 bytes = PyObject_Bytes(obj);
4822 if (bytes == NULL)
4823 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 long_obj = _PyLong_FromByteArray(
4826 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4827 little_endian, is_signed);
4828 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004831 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 */
4833 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4834 PyLongObject *newobj;
4835 int i;
4836 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004838 newobj = (PyLongObject *)type->tp_alloc(type, n);
4839 if (newobj == NULL) {
4840 Py_DECREF(long_obj);
4841 return NULL;
4842 }
4843 assert(PyLong_Check(newobj));
4844 Py_SIZE(newobj) = Py_SIZE(long_obj);
4845 for (i = 0; i < n; i++) {
4846 newobj->ob_digit[i] =
4847 ((PyLongObject *)long_obj)->ob_digit[i];
4848 }
4849 Py_DECREF(long_obj);
4850 return (PyObject *)newobj;
4851 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004854}
4855
Mark Dickinson078c2532010-01-30 18:06:17 +00004856PyDoc_STRVAR(long_from_bytes_doc,
4857"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4858\n\
4859Return the integer represented by the given array of bytes.\n\
4860\n\
4861The bytes argument must either support the buffer protocol or be an\n\
4862iterable object producing bytes. Bytes and bytearray are examples of\n\
4863built-in objects that support the buffer protocol.\n\
4864\n\
4865The byteorder argument determines the byte order used to represent the\n\
4866integer. If byteorder is 'big', the most significant byte is at the\n\
4867beginning of the byte array. If byteorder is 'little', the most\n\
4868significant byte is at the end of the byte array. To request the native\n\
4869byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4870\n\
4871The signed keyword-only argument indicates whether two's complement is\n\
4872used to represent the integer.");
4873
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004874static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4876 "Returns self, the complex conjugate of any int."},
4877 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4878 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004879#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004880 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4881 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004882#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004883 {"to_bytes", (PyCFunction)long_to_bytes,
4884 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4885 {"from_bytes", (PyCFunction)long_from_bytes,
4886 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4887 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4888 "Truncating an Integral returns itself."},
4889 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4890 "Flooring an Integral returns itself."},
4891 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4892 "Ceiling of an Integral returns itself."},
4893 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4894 "Rounding an Integral returns itself.\n"
4895 "Rounding with an ndigits argument also returns an integer."},
4896 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4897 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4898 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4899 "Returns size in memory, in bytes"},
4900 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004901};
4902
Guido van Rossumb43daf72007-08-01 18:08:08 +00004903static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004904 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004905 (getter)long_long, (setter)NULL,
4906 "the real part of a complex number",
4907 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004908 {"imag",
4909 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004910 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004911 NULL},
4912 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004913 (getter)long_long, (setter)NULL,
4914 "the numerator of a rational number in lowest terms",
4915 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004916 {"denominator",
4917 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004918 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004919 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004920 {NULL} /* Sentinel */
4921};
4922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004923PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004924"int(x=0) -> integer\n\
4925int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004926\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004927Convert a number or string to an integer, or return 0 if no arguments\n\
4928are given. If x is a number, return x.__int__(). For floating point\n\
4929numbers, this truncates towards zero.\n\
4930\n\
4931If x is not a number or if base is given, then x must be a string,\n\
4932bytes, or bytearray instance representing an integer literal in the\n\
4933given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4934by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4935Base 0 means to interpret the base from the string as an integer literal.\n\
4936>>> int('0b100', base=0)\n\
49374");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004938
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004939static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004940 (binaryfunc)long_add, /*nb_add*/
4941 (binaryfunc)long_sub, /*nb_subtract*/
4942 (binaryfunc)long_mul, /*nb_multiply*/
4943 long_mod, /*nb_remainder*/
4944 long_divmod, /*nb_divmod*/
4945 long_pow, /*nb_power*/
4946 (unaryfunc)long_neg, /*nb_negative*/
4947 (unaryfunc)long_long, /*tp_positive*/
4948 (unaryfunc)long_abs, /*tp_absolute*/
4949 (inquiry)long_bool, /*tp_bool*/
4950 (unaryfunc)long_invert, /*nb_invert*/
4951 long_lshift, /*nb_lshift*/
4952 (binaryfunc)long_rshift, /*nb_rshift*/
4953 long_and, /*nb_and*/
4954 long_xor, /*nb_xor*/
4955 long_or, /*nb_or*/
4956 long_long, /*nb_int*/
4957 0, /*nb_reserved*/
4958 long_float, /*nb_float*/
4959 0, /* nb_inplace_add */
4960 0, /* nb_inplace_subtract */
4961 0, /* nb_inplace_multiply */
4962 0, /* nb_inplace_remainder */
4963 0, /* nb_inplace_power */
4964 0, /* nb_inplace_lshift */
4965 0, /* nb_inplace_rshift */
4966 0, /* nb_inplace_and */
4967 0, /* nb_inplace_xor */
4968 0, /* nb_inplace_or */
4969 long_div, /* nb_floor_divide */
4970 long_true_divide, /* nb_true_divide */
4971 0, /* nb_inplace_floor_divide */
4972 0, /* nb_inplace_true_divide */
4973 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004974};
4975
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004976PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4978 "int", /* tp_name */
4979 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4980 sizeof(digit), /* tp_itemsize */
4981 long_dealloc, /* tp_dealloc */
4982 0, /* tp_print */
4983 0, /* tp_getattr */
4984 0, /* tp_setattr */
4985 0, /* tp_reserved */
4986 long_to_decimal_string, /* tp_repr */
4987 &long_as_number, /* tp_as_number */
4988 0, /* tp_as_sequence */
4989 0, /* tp_as_mapping */
4990 (hashfunc)long_hash, /* tp_hash */
4991 0, /* tp_call */
4992 long_to_decimal_string, /* tp_str */
4993 PyObject_GenericGetAttr, /* tp_getattro */
4994 0, /* tp_setattro */
4995 0, /* tp_as_buffer */
4996 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4997 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4998 long_doc, /* tp_doc */
4999 0, /* tp_traverse */
5000 0, /* tp_clear */
5001 long_richcompare, /* tp_richcompare */
5002 0, /* tp_weaklistoffset */
5003 0, /* tp_iter */
5004 0, /* tp_iternext */
5005 long_methods, /* tp_methods */
5006 0, /* tp_members */
5007 long_getset, /* tp_getset */
5008 0, /* tp_base */
5009 0, /* tp_dict */
5010 0, /* tp_descr_get */
5011 0, /* tp_descr_set */
5012 0, /* tp_dictoffset */
5013 0, /* tp_init */
5014 0, /* tp_alloc */
5015 long_new, /* tp_new */
5016 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005017};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005018
Mark Dickinsonbd792642009-03-18 20:06:12 +00005019static PyTypeObject Int_InfoType;
5020
5021PyDoc_STRVAR(int_info__doc__,
5022"sys.int_info\n\
5023\n\
5024A struct sequence that holds information about Python's\n\
5025internal representation of integers. The attributes are read only.");
5026
5027static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005029 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005030 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005031};
5032
5033static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 "sys.int_info", /* name */
5035 int_info__doc__, /* doc */
5036 int_info_fields, /* fields */
5037 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005038};
5039
5040PyObject *
5041PyLong_GetInfo(void)
5042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 PyObject* int_info;
5044 int field = 0;
5045 int_info = PyStructSequence_New(&Int_InfoType);
5046 if (int_info == NULL)
5047 return NULL;
5048 PyStructSequence_SET_ITEM(int_info, field++,
5049 PyLong_FromLong(PyLong_SHIFT));
5050 PyStructSequence_SET_ITEM(int_info, field++,
5051 PyLong_FromLong(sizeof(digit)));
5052 if (PyErr_Occurred()) {
5053 Py_CLEAR(int_info);
5054 return NULL;
5055 }
5056 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005057}
5058
Guido van Rossumddefaf32007-01-14 03:31:43 +00005059int
5060_PyLong_Init(void)
5061{
5062#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 int ival, size;
5064 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5067 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5068 if (Py_TYPE(v) == &PyLong_Type) {
5069 /* The element is already initialized, most likely
5070 * the Python interpreter was initialized before.
5071 */
5072 Py_ssize_t refcnt;
5073 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5076 _Py_NewReference(op);
5077 /* _Py_NewReference sets the ref count to 1 but
5078 * the ref count might be larger. Set the refcnt
5079 * to the original refcnt + 1 */
5080 Py_REFCNT(op) = refcnt + 1;
5081 assert(Py_SIZE(op) == size);
5082 assert(v->ob_digit[0] == abs(ival));
5083 }
5084 else {
5085 PyObject_INIT(v, &PyLong_Type);
5086 }
5087 Py_SIZE(v) = size;
5088 v->ob_digit[0] = abs(ival);
5089 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005090#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 /* initialize int_info */
5092 if (Int_InfoType.tp_name == 0)
5093 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005096}
5097
5098void
5099PyLong_Fini(void)
5100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 /* Integers are currently statically allocated. Py_DECREF is not
5102 needed, but Python must forget about the reference or multiple
5103 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005104#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 int i;
5106 PyLongObject *v = small_ints;
5107 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5108 _Py_DEC_REFTOTAL;
5109 _Py_ForgetReference((PyObject*)v);
5110 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005111#endif
5112}