blob: 4ae22ef31b6eb61f19471164033b6bc48ee81339 [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 Storchaka31a65542013-12-11 21:07:54 +0200119/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
120 using the nb_int slot, if available. Raise TypeError if either the
121 nb_int slot is not available or the result of the call to nb_int
122 returns something not of type int.
123*/
124PyLongObject *
125_PyLong_FromNbInt(PyObject *integral)
126{
127 PyNumberMethods *nb;
128 PyObject *result;
129
130 /* Fast path for the case that we already have an int. */
131 if (PyLong_CheckExact(integral)) {
132 Py_INCREF(integral);
133 return (PyLongObject *)integral;
134 }
135
136 nb = Py_TYPE(integral)->tp_as_number;
137 if (nb == NULL || nb->nb_int == NULL) {
138 PyErr_Format(PyExc_TypeError,
139 "an integer is required (got type %.200s)",
140 Py_TYPE(integral)->tp_name);
141 return NULL;
142 }
143
144 /* Convert using the nb_int slot, which should return something
145 of exact type int. */
146 result = nb->nb_int(integral);
147 if (!result || PyLong_CheckExact(result))
148 return (PyLongObject *)result;
149 if (!PyLong_Check(result)) {
150 PyErr_Format(PyExc_TypeError,
151 "__int__ returned non-int (type %.200s)",
152 result->ob_type->tp_name);
153 Py_DECREF(result);
154 return NULL;
155 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200156 return (PyLongObject *)result;
157}
158
159
Serhiy Storchaka95949422013-08-27 19:40:23 +0300160/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000161 Return NULL and set exception if we run out of memory. */
162
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000163#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000165
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000166PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000167_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 PyLongObject *result;
170 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
171 sizeof(digit)*size. Previous incarnations of this code used
172 sizeof(PyVarObject) instead of the offsetof, but this risks being
173 incorrect in the presence of padding between the PyVarObject header
174 and the digits. */
175 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
176 PyErr_SetString(PyExc_OverflowError,
177 "too many digits in integer");
178 return NULL;
179 }
180 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
181 size*sizeof(digit));
182 if (!result) {
183 PyErr_NoMemory();
184 return NULL;
185 }
186 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000187}
188
Tim Peters64b5ce32001-09-10 20:52:51 +0000189PyObject *
190_PyLong_Copy(PyLongObject *src)
191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyLongObject *result;
193 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 assert(src != NULL);
196 i = Py_SIZE(src);
197 if (i < 0)
198 i = -(i);
199 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100200 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 CHECK_SMALL_INT(ival);
202 }
203 result = _PyLong_New(i);
204 if (result != NULL) {
205 Py_SIZE(result) = Py_SIZE(src);
206 while (--i >= 0)
207 result->ob_digit[i] = src->ob_digit[i];
208 }
209 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000210}
211
Serhiy Storchaka95949422013-08-27 19:40:23 +0300212/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000213
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000215PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyLongObject *v;
218 unsigned long abs_ival;
219 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
220 int ndigits = 0;
221 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (ival < 0) {
226 /* negate: can't write this as abs_ival = -ival since that
227 invokes undefined behaviour when ival is LONG_MIN */
228 abs_ival = 0U-(unsigned long)ival;
229 sign = -1;
230 }
231 else {
232 abs_ival = (unsigned long)ival;
233 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 /* Fast path for single-digit ints */
236 if (!(abs_ival >> PyLong_SHIFT)) {
237 v = _PyLong_New(1);
238 if (v) {
239 Py_SIZE(v) = sign;
240 v->ob_digit[0] = Py_SAFE_DOWNCAST(
241 abs_ival, unsigned long, digit);
242 }
243 return (PyObject*)v;
244 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000245
Mark Dickinson249b8982009-04-27 19:41:00 +0000246#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 /* 2 digits */
248 if (!(abs_ival >> 2*PyLong_SHIFT)) {
249 v = _PyLong_New(2);
250 if (v) {
251 Py_SIZE(v) = 2*sign;
252 v->ob_digit[0] = Py_SAFE_DOWNCAST(
253 abs_ival & PyLong_MASK, unsigned long, digit);
254 v->ob_digit[1] = Py_SAFE_DOWNCAST(
255 abs_ival >> PyLong_SHIFT, unsigned long, digit);
256 }
257 return (PyObject*)v;
258 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000259#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* Larger numbers: loop to determine number of digits */
262 t = abs_ival;
263 while (t) {
264 ++ndigits;
265 t >>= PyLong_SHIFT;
266 }
267 v = _PyLong_New(ndigits);
268 if (v != NULL) {
269 digit *p = v->ob_digit;
270 Py_SIZE(v) = ndigits*sign;
271 t = abs_ival;
272 while (t) {
273 *p++ = Py_SAFE_DOWNCAST(
274 t & PyLong_MASK, unsigned long, digit);
275 t >>= PyLong_SHIFT;
276 }
277 }
278 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000279}
280
Serhiy Storchaka95949422013-08-27 19:40:23 +0300281/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000282
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000284PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 PyLongObject *v;
287 unsigned long t;
288 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 if (ival < PyLong_BASE)
291 return PyLong_FromLong(ival);
292 /* Count the number of Python digits. */
293 t = (unsigned long)ival;
294 while (t) {
295 ++ndigits;
296 t >>= PyLong_SHIFT;
297 }
298 v = _PyLong_New(ndigits);
299 if (v != NULL) {
300 digit *p = v->ob_digit;
301 Py_SIZE(v) = ndigits;
302 while (ival) {
303 *p++ = (digit)(ival & PyLong_MASK);
304 ival >>= PyLong_SHIFT;
305 }
306 }
307 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000308}
309
Serhiy Storchaka95949422013-08-27 19:40:23 +0300310/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyLongObject *v;
316 double frac;
317 int i, ndig, expo, neg;
318 neg = 0;
319 if (Py_IS_INFINITY(dval)) {
320 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000321 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return NULL;
323 }
324 if (Py_IS_NAN(dval)) {
325 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000326 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 return NULL;
328 }
329 if (dval < 0.0) {
330 neg = 1;
331 dval = -dval;
332 }
333 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
334 if (expo <= 0)
335 return PyLong_FromLong(0L);
336 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
337 v = _PyLong_New(ndig);
338 if (v == NULL)
339 return NULL;
340 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
341 for (i = ndig; --i >= 0; ) {
342 digit bits = (digit)frac;
343 v->ob_digit[i] = bits;
344 frac = frac - (double)bits;
345 frac = ldexp(frac, PyLong_SHIFT);
346 }
347 if (neg)
348 Py_SIZE(v) = -(Py_SIZE(v));
349 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000350}
351
Thomas Wouters89f507f2006-12-13 04:49:30 +0000352/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
353 * anything about what happens when a signed integer operation overflows,
354 * and some compilers think they're doing you a favor by being "clever"
355 * then. The bit pattern for the largest postive signed long is
356 * (unsigned long)LONG_MAX, and for the smallest negative signed long
357 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
358 * However, some other compilers warn about applying unary minus to an
359 * unsigned operand. Hence the weird "0-".
360 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
362#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000363
Serhiy Storchaka95949422013-08-27 19:40:23 +0300364/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100365 method.
366
367 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
368 the result. Otherwise *overflow is 0.
369
370 For other errors (e.g., TypeError), return -1 and set an error condition.
371 In this case *overflow will be 0.
372*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000373
374long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000375PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* This version by Tim Peters */
378 register PyLongObject *v;
379 unsigned long x, prev;
380 long res;
381 Py_ssize_t i;
382 int sign;
383 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 *overflow = 0;
386 if (vv == NULL) {
387 PyErr_BadInternalCall();
388 return -1;
389 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000390
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200391 if (PyLong_Check(vv)) {
392 v = (PyLongObject *)vv;
393 }
394 else {
395 v = _PyLong_FromNbInt(vv);
396 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 return -1;
398 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 switch (i) {
405 case -1:
406 res = -(sdigit)v->ob_digit[0];
407 break;
408 case 0:
409 res = 0;
410 break;
411 case 1:
412 res = v->ob_digit[0];
413 break;
414 default:
415 sign = 1;
416 x = 0;
417 if (i < 0) {
418 sign = -1;
419 i = -(i);
420 }
421 while (--i >= 0) {
422 prev = x;
423 x = (x << PyLong_SHIFT) | v->ob_digit[i];
424 if ((x >> PyLong_SHIFT) != prev) {
425 *overflow = sign;
426 goto exit;
427 }
428 }
429 /* Haven't lost any bits, but casting to long requires extra
430 * care (see comment above).
431 */
432 if (x <= (unsigned long)LONG_MAX) {
433 res = (long)x * sign;
434 }
435 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
436 res = LONG_MIN;
437 }
438 else {
439 *overflow = sign;
440 /* res is already set to -1 */
441 }
442 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000443 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200445 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 }
447 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000448}
449
Serhiy Storchaka95949422013-08-27 19:40:23 +0300450/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100451 method. Return -1 and set an error if overflow occurs. */
452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000454PyLong_AsLong(PyObject *obj)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 int overflow;
457 long result = PyLong_AsLongAndOverflow(obj, &overflow);
458 if (overflow) {
459 /* XXX: could be cute and give a different
460 message for overflow == -1 */
461 PyErr_SetString(PyExc_OverflowError,
462 "Python int too large to convert to C long");
463 }
464 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000465}
466
Serhiy Storchaka95949422013-08-27 19:40:23 +0300467/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka441d30f2013-01-19 12:26:26 +0200468 method. Return -1 and set an error if overflow occurs. */
469
470int
471_PyLong_AsInt(PyObject *obj)
472{
473 int overflow;
474 long result = PyLong_AsLongAndOverflow(obj, &overflow);
475 if (overflow || result > INT_MAX || result < INT_MIN) {
476 /* XXX: could be cute and give a different
477 message for overflow == -1 */
478 PyErr_SetString(PyExc_OverflowError,
479 "Python int too large to convert to C int");
480 return -1;
481 }
482 return (int)result;
483}
484
Serhiy Storchaka95949422013-08-27 19:40:23 +0300485/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000486 Returns -1 and sets an error condition if overflow occurs. */
487
488Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000489PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 register PyLongObject *v;
491 size_t x, prev;
492 Py_ssize_t i;
493 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (vv == NULL) {
496 PyErr_BadInternalCall();
497 return -1;
498 }
499 if (!PyLong_Check(vv)) {
500 PyErr_SetString(PyExc_TypeError, "an integer is required");
501 return -1;
502 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 v = (PyLongObject *)vv;
505 i = Py_SIZE(v);
506 switch (i) {
507 case -1: return -(sdigit)v->ob_digit[0];
508 case 0: return 0;
509 case 1: return v->ob_digit[0];
510 }
511 sign = 1;
512 x = 0;
513 if (i < 0) {
514 sign = -1;
515 i = -(i);
516 }
517 while (--i >= 0) {
518 prev = x;
519 x = (x << PyLong_SHIFT) | v->ob_digit[i];
520 if ((x >> PyLong_SHIFT) != prev)
521 goto overflow;
522 }
523 /* Haven't lost any bits, but casting to a signed type requires
524 * extra care (see comment above).
525 */
526 if (x <= (size_t)PY_SSIZE_T_MAX) {
527 return (Py_ssize_t)x * sign;
528 }
529 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
530 return PY_SSIZE_T_MIN;
531 }
532 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000533
Mark Dickinson22b20182010-05-10 21:27:53 +0000534 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyErr_SetString(PyExc_OverflowError,
536 "Python int too large to convert to C ssize_t");
537 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000538}
539
Serhiy Storchaka95949422013-08-27 19:40:23 +0300540/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000541 Returns -1 and sets an error condition if overflow occurs. */
542
543unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000544PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 register PyLongObject *v;
547 unsigned long x, prev;
548 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (vv == NULL) {
551 PyErr_BadInternalCall();
552 return (unsigned long)-1;
553 }
554 if (!PyLong_Check(vv)) {
555 PyErr_SetString(PyExc_TypeError, "an integer is required");
556 return (unsigned long)-1;
557 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 v = (PyLongObject *)vv;
560 i = Py_SIZE(v);
561 x = 0;
562 if (i < 0) {
563 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000564 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return (unsigned long) -1;
566 }
567 switch (i) {
568 case 0: return 0;
569 case 1: return v->ob_digit[0];
570 }
571 while (--i >= 0) {
572 prev = x;
573 x = (x << PyLong_SHIFT) | v->ob_digit[i];
574 if ((x >> PyLong_SHIFT) != prev) {
575 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000576 "python int too large to convert "
577 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 return (unsigned long) -1;
579 }
580 }
581 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000582}
583
Serhiy Storchaka95949422013-08-27 19:40:23 +0300584/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200585 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000586
587size_t
588PyLong_AsSize_t(PyObject *vv)
589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 register PyLongObject *v;
591 size_t x, prev;
592 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (vv == NULL) {
595 PyErr_BadInternalCall();
596 return (size_t) -1;
597 }
598 if (!PyLong_Check(vv)) {
599 PyErr_SetString(PyExc_TypeError, "an integer is required");
600 return (size_t)-1;
601 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 v = (PyLongObject *)vv;
604 i = Py_SIZE(v);
605 x = 0;
606 if (i < 0) {
607 PyErr_SetString(PyExc_OverflowError,
608 "can't convert negative value to size_t");
609 return (size_t) -1;
610 }
611 switch (i) {
612 case 0: return 0;
613 case 1: return v->ob_digit[0];
614 }
615 while (--i >= 0) {
616 prev = x;
617 x = (x << PyLong_SHIFT) | v->ob_digit[i];
618 if ((x >> PyLong_SHIFT) != prev) {
619 PyErr_SetString(PyExc_OverflowError,
620 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200621 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 }
623 }
624 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000625}
626
Serhiy Storchaka95949422013-08-27 19:40:23 +0300627/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000628 Returns -1 and sets an error condition if an error occurs. */
629
Guido van Rossumddefaf32007-01-14 03:31:43 +0000630static unsigned long
631_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 register PyLongObject *v;
634 unsigned long x;
635 Py_ssize_t i;
636 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 if (vv == NULL || !PyLong_Check(vv)) {
639 PyErr_BadInternalCall();
640 return (unsigned long) -1;
641 }
642 v = (PyLongObject *)vv;
643 i = Py_SIZE(v);
644 switch (i) {
645 case 0: return 0;
646 case 1: return v->ob_digit[0];
647 }
648 sign = 1;
649 x = 0;
650 if (i < 0) {
651 sign = -1;
652 i = -i;
653 }
654 while (--i >= 0) {
655 x = (x << PyLong_SHIFT) | v->ob_digit[i];
656 }
657 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000658}
659
Guido van Rossumddefaf32007-01-14 03:31:43 +0000660unsigned long
661PyLong_AsUnsignedLongMask(register PyObject *op)
662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyLongObject *lo;
664 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000665
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200666 if (op == NULL) {
667 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return (unsigned long)-1;
669 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000670
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200671 if (PyLong_Check(op)) {
672 return _PyLong_AsUnsignedLongMask(op);
673 }
674
675 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (lo == NULL)
677 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200678
679 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
680 Py_DECREF(lo);
681 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000682}
683
Tim Peters5b8132f2003-01-31 15:52:05 +0000684int
685_PyLong_Sign(PyObject *vv)
686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 assert(v != NULL);
690 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000693}
694
Tim Petersbaefd9e2003-01-28 20:37:45 +0000695size_t
696_PyLong_NumBits(PyObject *vv)
697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyLongObject *v = (PyLongObject *)vv;
699 size_t result = 0;
700 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 assert(v != NULL);
703 assert(PyLong_Check(v));
704 ndigits = ABS(Py_SIZE(v));
705 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
706 if (ndigits > 0) {
707 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100708 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100710 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 do {
712 ++result;
713 if (result == 0)
714 goto Overflow;
715 msd >>= 1;
716 } while (msd);
717 }
718 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000719
Mark Dickinson22b20182010-05-10 21:27:53 +0000720 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
722 "to express in a platform size_t");
723 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000724}
725
Tim Peters2a9b3672001-06-11 21:23:58 +0000726PyObject *
727_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000729{
Mark Dickinson22b20182010-05-10 21:27:53 +0000730 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 int incr; /* direction to move pstartbyte */
732 const unsigned char* pendbyte; /* MSB of bytes */
733 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300734 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyLongObject* v; /* result */
736 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 if (n == 0)
739 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (little_endian) {
742 pstartbyte = bytes;
743 pendbyte = bytes + n - 1;
744 incr = 1;
745 }
746 else {
747 pstartbyte = bytes + n - 1;
748 pendbyte = bytes;
749 incr = -1;
750 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (is_signed)
753 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200756 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 is positive, and leading 0xff bytes if negative. */
758 {
759 size_t i;
760 const unsigned char* p = pendbyte;
761 const int pincr = -incr; /* search MSB to LSB */
762 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 for (i = 0; i < n; ++i, p += pincr) {
765 if (*p != insignficant)
766 break;
767 }
768 numsignificantbytes = n - i;
769 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
770 actually has 2 significant bytes. OTOH, 0xff0001 ==
771 -0x00ffff, so we wouldn't *need* to bump it there; but we
772 do for 0xffff = -0x0001. To be safe without bothering to
773 check every case, bump it regardless. */
774 if (is_signed && numsignificantbytes < n)
775 ++numsignificantbytes;
776 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000777
Serhiy Storchaka95949422013-08-27 19:40:23 +0300778 /* How many Python int digits do we need? We have
779 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
781 /* catch overflow before it happens */
782 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
783 PyErr_SetString(PyExc_OverflowError,
784 "byte array too long to convert to int");
785 return NULL;
786 }
787 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
788 v = _PyLong_New(ndigits);
789 if (v == NULL)
790 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* Copy the bits over. The tricky parts are computing 2's-comp on
793 the fly for signed numbers, and dealing with the mismatch between
794 8-bit bytes and (probably) 15-bit Python digits.*/
795 {
796 size_t i;
797 twodigits carry = 1; /* for 2's-comp calculation */
798 twodigits accum = 0; /* sliding register */
799 unsigned int accumbits = 0; /* number of bits in accum */
800 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
803 twodigits thisbyte = *p;
804 /* Compute correction for 2's comp, if needed. */
805 if (is_signed) {
806 thisbyte = (0xff ^ thisbyte) + carry;
807 carry = thisbyte >> 8;
808 thisbyte &= 0xff;
809 }
810 /* Because we're going LSB to MSB, thisbyte is
811 more significant than what's already in accum,
812 so needs to be prepended to accum. */
813 accum |= (twodigits)thisbyte << accumbits;
814 accumbits += 8;
815 if (accumbits >= PyLong_SHIFT) {
816 /* There's enough to fill a Python digit. */
817 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000818 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 ++idigit;
820 accum >>= PyLong_SHIFT;
821 accumbits -= PyLong_SHIFT;
822 assert(accumbits < PyLong_SHIFT);
823 }
824 }
825 assert(accumbits < PyLong_SHIFT);
826 if (accumbits) {
827 assert(idigit < ndigits);
828 v->ob_digit[idigit] = (digit)accum;
829 ++idigit;
830 }
831 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 Py_SIZE(v) = is_signed ? -idigit : idigit;
834 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000835}
836
837int
838_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 unsigned char* bytes, size_t n,
840 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000843 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000845 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
847 digit carry; /* for computing 2's-comp */
848 size_t j; /* # bytes filled */
849 unsigned char* p; /* pointer to next byte in bytes */
850 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (Py_SIZE(v) < 0) {
855 ndigits = -(Py_SIZE(v));
856 if (!is_signed) {
857 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000858 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return -1;
860 }
861 do_twos_comp = 1;
862 }
863 else {
864 ndigits = Py_SIZE(v);
865 do_twos_comp = 0;
866 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (little_endian) {
869 p = bytes;
870 pincr = 1;
871 }
872 else {
873 p = bytes + n - 1;
874 pincr = -1;
875 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Copy over all the Python digits.
878 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300879 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 normalized. */
881 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
882 j = 0;
883 accum = 0;
884 accumbits = 0;
885 carry = do_twos_comp ? 1 : 0;
886 for (i = 0; i < ndigits; ++i) {
887 digit thisdigit = v->ob_digit[i];
888 if (do_twos_comp) {
889 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
890 carry = thisdigit >> PyLong_SHIFT;
891 thisdigit &= PyLong_MASK;
892 }
893 /* Because we're going LSB to MSB, thisdigit is more
894 significant than what's already in accum, so needs to be
895 prepended to accum. */
896 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* The most-significant digit may be (probably is) at least
899 partly empty. */
900 if (i == ndigits - 1) {
901 /* Count # of sign bits -- they needn't be stored,
902 * although for signed conversion we need later to
903 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000904 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 while (s != 0) {
906 s >>= 1;
907 accumbits++;
908 }
909 }
910 else
911 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Store as many bytes as possible. */
914 while (accumbits >= 8) {
915 if (j >= n)
916 goto Overflow;
917 ++j;
918 *p = (unsigned char)(accum & 0xff);
919 p += pincr;
920 accumbits -= 8;
921 accum >>= 8;
922 }
923 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Store the straggler (if any). */
926 assert(accumbits < 8);
927 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
928 if (accumbits > 0) {
929 if (j >= n)
930 goto Overflow;
931 ++j;
932 if (do_twos_comp) {
933 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300934 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 infinite supply of sign bits). */
936 accum |= (~(twodigits)0) << accumbits;
937 }
938 *p = (unsigned char)(accum & 0xff);
939 p += pincr;
940 }
941 else if (j == n && n > 0 && is_signed) {
942 /* The main loop filled the byte array exactly, so the code
943 just above didn't get to ensure there's a sign bit, and the
944 loop below wouldn't add one either. Make sure a sign bit
945 exists. */
946 unsigned char msb = *(p - pincr);
947 int sign_bit_set = msb >= 0x80;
948 assert(accumbits == 0);
949 if (sign_bit_set == do_twos_comp)
950 return 0;
951 else
952 goto Overflow;
953 }
Tim Peters05607ad2001-06-13 21:01:27 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Fill remaining bytes with copies of the sign bit. */
956 {
957 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
958 for ( ; j < n; ++j, p += pincr)
959 *p = signbyte;
960 }
Tim Peters05607ad2001-06-13 21:01:27 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000963
Mark Dickinson22b20182010-05-10 21:27:53 +0000964 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
966 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000967
Tim Peters2a9b3672001-06-11 21:23:58 +0000968}
969
Serhiy Storchaka95949422013-08-27 19:40:23 +0300970/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000971
972PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000973PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000974{
Mark Dickinson91044792012-10-18 19:21:43 +0100975#if SIZEOF_VOID_P <= SIZEOF_LONG
976 /* special-case null pointer */
977 if (!p)
978 return PyLong_FromLong(0);
979 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
980#else
981
Tim Peters70128a12001-06-16 08:48:40 +0000982#ifndef HAVE_LONG_LONG
983# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
984#endif
985#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000986# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000987#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* special-case null pointer */
989 if (!p)
990 return PyLong_FromLong(0);
991 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +0100992#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +0000993
Guido van Rossum78694d91998-09-18 14:14:13 +0000994}
995
Serhiy Storchaka95949422013-08-27 19:40:23 +0300996/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +0000997
998void *
Tim Peters9f688bf2000-07-07 15:53:28 +0000999PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001000{
Tim Peters70128a12001-06-16 08:48:40 +00001001#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1005 x = PyLong_AsLong(vv);
1006 else
1007 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001008#else
Tim Peters70128a12001-06-16 08:48:40 +00001009
1010#ifndef HAVE_LONG_LONG
1011# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1012#endif
1013#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001014# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001015#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1019 x = PyLong_AsLongLong(vv);
1020 else
1021 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001022
1023#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (x == -1 && PyErr_Occurred())
1026 return NULL;
1027 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001028}
1029
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001030#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001031
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001032/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001033 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001034 */
1035
Tim Peterscf37dfc2001-06-14 18:42:50 +00001036#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +00001037#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001038
Serhiy Storchaka95949422013-08-27 19:40:23 +03001039/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040
1041PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001042PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 PyLongObject *v;
1045 unsigned PY_LONG_LONG abs_ival;
1046 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1047 int ndigits = 0;
1048 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 CHECK_SMALL_INT(ival);
1051 if (ival < 0) {
1052 /* avoid signed overflow on negation; see comments
1053 in PyLong_FromLong above. */
1054 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1055 negative = 1;
1056 }
1057 else {
1058 abs_ival = (unsigned PY_LONG_LONG)ival;
1059 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 /* Count the number of Python digits.
1062 We used to pick 5 ("big enough for anything"), but that's a
1063 waste of time and space given that 5*15 = 75 bits are rarely
1064 needed. */
1065 t = abs_ival;
1066 while (t) {
1067 ++ndigits;
1068 t >>= PyLong_SHIFT;
1069 }
1070 v = _PyLong_New(ndigits);
1071 if (v != NULL) {
1072 digit *p = v->ob_digit;
1073 Py_SIZE(v) = negative ? -ndigits : ndigits;
1074 t = abs_ival;
1075 while (t) {
1076 *p++ = (digit)(t & PyLong_MASK);
1077 t >>= PyLong_SHIFT;
1078 }
1079 }
1080 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001081}
1082
Serhiy Storchaka95949422013-08-27 19:40:23 +03001083/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001084
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001085PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001086PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyLongObject *v;
1089 unsigned PY_LONG_LONG t;
1090 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (ival < PyLong_BASE)
1093 return PyLong_FromLong((long)ival);
1094 /* Count the number of Python digits. */
1095 t = (unsigned PY_LONG_LONG)ival;
1096 while (t) {
1097 ++ndigits;
1098 t >>= PyLong_SHIFT;
1099 }
1100 v = _PyLong_New(ndigits);
1101 if (v != NULL) {
1102 digit *p = v->ob_digit;
1103 Py_SIZE(v) = ndigits;
1104 while (ival) {
1105 *p++ = (digit)(ival & PyLong_MASK);
1106 ival >>= PyLong_SHIFT;
1107 }
1108 }
1109 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001110}
1111
Serhiy Storchaka95949422013-08-27 19:40:23 +03001112/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001113
1114PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001115PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyLongObject *v;
1118 size_t abs_ival;
1119 size_t t; /* unsigned so >> doesn't propagate sign bit */
1120 int ndigits = 0;
1121 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 CHECK_SMALL_INT(ival);
1124 if (ival < 0) {
1125 /* avoid signed overflow when ival = SIZE_T_MIN */
1126 abs_ival = (size_t)(-1-ival)+1;
1127 negative = 1;
1128 }
1129 else {
1130 abs_ival = (size_t)ival;
1131 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 /* Count the number of Python digits. */
1134 t = abs_ival;
1135 while (t) {
1136 ++ndigits;
1137 t >>= PyLong_SHIFT;
1138 }
1139 v = _PyLong_New(ndigits);
1140 if (v != NULL) {
1141 digit *p = v->ob_digit;
1142 Py_SIZE(v) = negative ? -ndigits : ndigits;
1143 t = abs_ival;
1144 while (t) {
1145 *p++ = (digit)(t & PyLong_MASK);
1146 t >>= PyLong_SHIFT;
1147 }
1148 }
1149 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001150}
1151
Serhiy Storchaka95949422013-08-27 19:40:23 +03001152/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001153
1154PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001155PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 PyLongObject *v;
1158 size_t t;
1159 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (ival < PyLong_BASE)
1162 return PyLong_FromLong((long)ival);
1163 /* Count the number of Python digits. */
1164 t = ival;
1165 while (t) {
1166 ++ndigits;
1167 t >>= PyLong_SHIFT;
1168 }
1169 v = _PyLong_New(ndigits);
1170 if (v != NULL) {
1171 digit *p = v->ob_digit;
1172 Py_SIZE(v) = ndigits;
1173 while (ival) {
1174 *p++ = (digit)(ival & PyLong_MASK);
1175 ival >>= PyLong_SHIFT;
1176 }
1177 }
1178 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001179}
1180
Serhiy Storchaka95949422013-08-27 19:40:23 +03001181/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001182 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001183
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001184PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001185PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 PyLongObject *v;
1188 PY_LONG_LONG bytes;
1189 int one = 1;
1190 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001191 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (vv == NULL) {
1194 PyErr_BadInternalCall();
1195 return -1;
1196 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001197
1198 if (PyLong_Check(vv)) {
1199 v = (PyLongObject *)vv;
1200 }
1201 else {
1202 v = _PyLong_FromNbInt(vv);
1203 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001205 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001207
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001208 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001210 case -1:
1211 bytes = -(sdigit)v->ob_digit[0];
1212 break;
1213 case 0:
1214 bytes = 0;
1215 break;
1216 case 1:
1217 bytes = v->ob_digit[0];
1218 break;
1219 default:
1220 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
1221 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001223 if (do_decref) {
1224 Py_DECREF(v);
1225 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1228 if (res < 0)
1229 return (PY_LONG_LONG)-1;
1230 else
1231 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001232}
1233
Serhiy Storchaka95949422013-08-27 19:40:23 +03001234/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001235 Return -1 and set an error if overflow occurs. */
1236
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001237unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001238PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 PyLongObject *v;
1241 unsigned PY_LONG_LONG bytes;
1242 int one = 1;
1243 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001244
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001245 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyErr_BadInternalCall();
1247 return (unsigned PY_LONG_LONG)-1;
1248 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001249 if (!PyLong_Check(vv)) {
1250 PyErr_SetString(PyExc_TypeError, "an integer is required");
1251 return (unsigned PY_LONG_LONG)-1;
1252 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 v = (PyLongObject*)vv;
1255 switch(Py_SIZE(v)) {
1256 case 0: return 0;
1257 case 1: return v->ob_digit[0];
1258 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001259
Mark Dickinson22b20182010-05-10 21:27:53 +00001260 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1261 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1264 if (res < 0)
1265 return (unsigned PY_LONG_LONG)res;
1266 else
1267 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001268}
Tim Petersd1a7da62001-06-13 00:35:57 +00001269
Serhiy Storchaka95949422013-08-27 19:40:23 +03001270/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001271 Returns -1 and sets an error condition if an error occurs. */
1272
Guido van Rossumddefaf32007-01-14 03:31:43 +00001273static unsigned PY_LONG_LONG
1274_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 register PyLongObject *v;
1277 unsigned PY_LONG_LONG x;
1278 Py_ssize_t i;
1279 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (vv == NULL || !PyLong_Check(vv)) {
1282 PyErr_BadInternalCall();
1283 return (unsigned long) -1;
1284 }
1285 v = (PyLongObject *)vv;
1286 switch(Py_SIZE(v)) {
1287 case 0: return 0;
1288 case 1: return v->ob_digit[0];
1289 }
1290 i = Py_SIZE(v);
1291 sign = 1;
1292 x = 0;
1293 if (i < 0) {
1294 sign = -1;
1295 i = -i;
1296 }
1297 while (--i >= 0) {
1298 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1299 }
1300 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001301}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001302
1303unsigned PY_LONG_LONG
1304PyLong_AsUnsignedLongLongMask(register PyObject *op)
1305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyLongObject *lo;
1307 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001308
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001309 if (op == NULL) {
1310 PyErr_BadInternalCall();
1311 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001313
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001314 if (PyLong_Check(op)) {
1315 return _PyLong_AsUnsignedLongLongMask(op);
1316 }
1317
1318 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (lo == NULL)
1320 return (unsigned PY_LONG_LONG)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001321
1322 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1323 Py_DECREF(lo);
1324 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001325}
Tim Petersd1a7da62001-06-13 00:35:57 +00001326#undef IS_LITTLE_ENDIAN
1327
Serhiy Storchaka95949422013-08-27 19:40:23 +03001328/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001329 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001330
Mark Dickinson8d48b432011-10-23 20:47:14 +01001331 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1332 the result. Otherwise *overflow is 0.
1333
1334 For other errors (e.g., TypeError), return -1 and set an error condition.
1335 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001336*/
1337
1338PY_LONG_LONG
1339PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* This version by Tim Peters */
1342 register PyLongObject *v;
1343 unsigned PY_LONG_LONG x, prev;
1344 PY_LONG_LONG res;
1345 Py_ssize_t i;
1346 int sign;
1347 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 *overflow = 0;
1350 if (vv == NULL) {
1351 PyErr_BadInternalCall();
1352 return -1;
1353 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001354
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001355 if (PyLong_Check(vv)) {
1356 v = (PyLongObject *)vv;
1357 }
1358 else {
1359 v = _PyLong_FromNbInt(vv);
1360 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 return -1;
1362 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 switch (i) {
1369 case -1:
1370 res = -(sdigit)v->ob_digit[0];
1371 break;
1372 case 0:
1373 res = 0;
1374 break;
1375 case 1:
1376 res = v->ob_digit[0];
1377 break;
1378 default:
1379 sign = 1;
1380 x = 0;
1381 if (i < 0) {
1382 sign = -1;
1383 i = -(i);
1384 }
1385 while (--i >= 0) {
1386 prev = x;
1387 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1388 if ((x >> PyLong_SHIFT) != prev) {
1389 *overflow = sign;
1390 goto exit;
1391 }
1392 }
1393 /* Haven't lost any bits, but casting to long requires extra
1394 * care (see comment above).
1395 */
1396 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1397 res = (PY_LONG_LONG)x * sign;
1398 }
1399 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1400 res = PY_LLONG_MIN;
1401 }
1402 else {
1403 *overflow = sign;
1404 /* res is already set to -1 */
1405 }
1406 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001407 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001409 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 }
1411 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001412}
1413
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001414#endif /* HAVE_LONG_LONG */
1415
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001416#define CHECK_BINOP(v,w) \
1417 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001418 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1419 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001420 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001421
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001422/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1423 2**k if d is nonzero, else 0. */
1424
1425static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1427 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001428};
1429
1430static int
1431bits_in_digit(digit d)
1432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 int d_bits = 0;
1434 while (d >= 32) {
1435 d_bits += 6;
1436 d >>= 6;
1437 }
1438 d_bits += (int)BitLengthTable[d];
1439 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001440}
1441
Tim Peters877a2122002-08-12 05:09:36 +00001442/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1443 * is modified in place, by adding y to it. Carries are propagated as far as
1444 * x[m-1], and the remaining carry (0 or 1) is returned.
1445 */
1446static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001447v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 Py_ssize_t i;
1450 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 assert(m >= n);
1453 for (i = 0; i < n; ++i) {
1454 carry += x[i] + y[i];
1455 x[i] = carry & PyLong_MASK;
1456 carry >>= PyLong_SHIFT;
1457 assert((carry & 1) == carry);
1458 }
1459 for (; carry && i < m; ++i) {
1460 carry += x[i];
1461 x[i] = carry & PyLong_MASK;
1462 carry >>= PyLong_SHIFT;
1463 assert((carry & 1) == carry);
1464 }
1465 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001466}
1467
1468/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1469 * is modified in place, by subtracting y from it. Borrows are propagated as
1470 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1471 */
1472static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001473v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 Py_ssize_t i;
1476 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 assert(m >= n);
1479 for (i = 0; i < n; ++i) {
1480 borrow = x[i] - y[i] - borrow;
1481 x[i] = borrow & PyLong_MASK;
1482 borrow >>= PyLong_SHIFT;
1483 borrow &= 1; /* keep only 1 sign bit */
1484 }
1485 for (; borrow && i < m; ++i) {
1486 borrow = x[i] - borrow;
1487 x[i] = borrow & PyLong_MASK;
1488 borrow >>= PyLong_SHIFT;
1489 borrow &= 1;
1490 }
1491 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001492}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001493
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001494/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1495 * result in z[0:m], and return the d bits shifted out of the top.
1496 */
1497static digit
1498v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_ssize_t i;
1501 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 assert(0 <= d && d < PyLong_SHIFT);
1504 for (i=0; i < m; i++) {
1505 twodigits acc = (twodigits)a[i] << d | carry;
1506 z[i] = (digit)acc & PyLong_MASK;
1507 carry = (digit)(acc >> PyLong_SHIFT);
1508 }
1509 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001510}
1511
1512/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1513 * result in z[0:m], and return the d bits shifted out of the bottom.
1514 */
1515static digit
1516v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 Py_ssize_t i;
1519 digit carry = 0;
1520 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 assert(0 <= d && d < PyLong_SHIFT);
1523 for (i=m; i-- > 0;) {
1524 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1525 carry = (digit)acc & mask;
1526 z[i] = (digit)(acc >> d);
1527 }
1528 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001529}
1530
Tim Peters212e6142001-07-14 12:23:19 +00001531/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1532 in pout, and returning the remainder. pin and pout point at the LSD.
1533 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001534 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001535 immutable. */
1536
1537static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001538inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 assert(n > 0 && n <= PyLong_MASK);
1543 pin += size;
1544 pout += size;
1545 while (--size >= 0) {
1546 digit hi;
1547 rem = (rem << PyLong_SHIFT) | *--pin;
1548 *--pout = hi = (digit)(rem / n);
1549 rem -= (twodigits)hi * n;
1550 }
1551 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001552}
1553
Serhiy Storchaka95949422013-08-27 19:40:23 +03001554/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001555 (as function result) and the remainder (through *prem).
1556 The sign of a is ignored; n should not be zero. */
1557
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001558static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001559divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 const Py_ssize_t size = ABS(Py_SIZE(a));
1562 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 assert(n > 0 && n <= PyLong_MASK);
1565 z = _PyLong_New(size);
1566 if (z == NULL)
1567 return NULL;
1568 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1569 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001570}
1571
Serhiy Storchaka95949422013-08-27 19:40:23 +03001572/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001573 string. (Return value is non-shared so that callers can modify the
1574 returned value if necessary.) */
1575
Victor Stinnerd3f08822012-05-29 12:57:52 +02001576static int
1577long_to_decimal_string_internal(PyObject *aa,
1578 PyObject **p_output,
1579 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 PyLongObject *scratch, *a;
1582 PyObject *str;
1583 Py_ssize_t size, strlen, size_a, i, j;
1584 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001586 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 a = (PyLongObject *)aa;
1589 if (a == NULL || !PyLong_Check(a)) {
1590 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001591 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 }
1593 size_a = ABS(Py_SIZE(a));
1594 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 /* quick and dirty upper bound for the number of digits
1597 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 But log2(a) < size_a * PyLong_SHIFT, and
1602 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1603 > 3 * _PyLong_DECIMAL_SHIFT
1604 */
1605 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1606 PyErr_SetString(PyExc_OverflowError,
1607 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001608 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 }
1610 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1611 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1612 scratch = _PyLong_New(size);
1613 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001614 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 /* convert array of base _PyLong_BASE digits in pin to an array of
1617 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1618 Volume 2 (3rd edn), section 4.4, Method 1b). */
1619 pin = a->ob_digit;
1620 pout = scratch->ob_digit;
1621 size = 0;
1622 for (i = size_a; --i >= 0; ) {
1623 digit hi = pin[i];
1624 for (j = 0; j < size; j++) {
1625 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1626 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1627 pout[j] = (digit)(z - (twodigits)hi *
1628 _PyLong_DECIMAL_BASE);
1629 }
1630 while (hi) {
1631 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1632 hi /= _PyLong_DECIMAL_BASE;
1633 }
1634 /* check for keyboard interrupt */
1635 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001636 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001637 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001638 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 }
1640 /* pout should have at least one digit, so that the case when a = 0
1641 works correctly */
1642 if (size == 0)
1643 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 /* calculate exact length of output string, and allocate */
1646 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1647 tenpow = 10;
1648 rem = pout[size-1];
1649 while (rem >= tenpow) {
1650 tenpow *= 10;
1651 strlen++;
1652 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001653 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001654 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1655 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001656 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001657 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001658 kind = writer->kind;
1659 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001661 else {
1662 str = PyUnicode_New(strlen, '9');
1663 if (str == NULL) {
1664 Py_DECREF(scratch);
1665 return -1;
1666 }
1667 kind = PyUnicode_KIND(str);
1668 }
1669
1670#define WRITE_DIGITS(TYPE) \
1671 do { \
1672 if (writer) \
1673 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1674 else \
1675 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1676 \
1677 *p = '\0'; \
1678 /* pout[0] through pout[size-2] contribute exactly \
1679 _PyLong_DECIMAL_SHIFT digits each */ \
1680 for (i=0; i < size - 1; i++) { \
1681 rem = pout[i]; \
1682 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1683 *--p = '0' + rem % 10; \
1684 rem /= 10; \
1685 } \
1686 } \
1687 /* pout[size-1]: always produce at least one decimal digit */ \
1688 rem = pout[i]; \
1689 do { \
1690 *--p = '0' + rem % 10; \
1691 rem /= 10; \
1692 } while (rem != 0); \
1693 \
1694 /* and sign */ \
1695 if (negative) \
1696 *--p = '-'; \
1697 \
1698 /* check we've counted correctly */ \
1699 if (writer) \
1700 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1701 else \
1702 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1703 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001706 if (kind == PyUnicode_1BYTE_KIND) {
1707 Py_UCS1 *p;
1708 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001710 else if (kind == PyUnicode_2BYTE_KIND) {
1711 Py_UCS2 *p;
1712 WRITE_DIGITS(Py_UCS2);
1713 }
1714 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001715 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001716 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001717 WRITE_DIGITS(Py_UCS4);
1718 }
1719#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001722 if (writer) {
1723 writer->pos += strlen;
1724 }
1725 else {
1726 assert(_PyUnicode_CheckConsistency(str, 1));
1727 *p_output = (PyObject *)str;
1728 }
1729 return 0;
1730}
1731
1732static PyObject *
1733long_to_decimal_string(PyObject *aa)
1734{
1735 PyObject *v;
1736 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1737 return NULL;
1738 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001739}
1740
Serhiy Storchaka95949422013-08-27 19:40:23 +03001741/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001742 which should be one of 2, 8 or 16. Return a string object.
1743 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1744 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001745
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746static int
1747long_format_binary(PyObject *aa, int base, int alternate,
1748 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001751 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001752 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001754 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001755 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001757
Victor Stinnerd3f08822012-05-29 12:57:52 +02001758 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 if (a == NULL || !PyLong_Check(a)) {
1760 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001761 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 }
1763 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001764 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* Compute a rough upper bound for the length of the string */
1767 switch (base) {
1768 case 16:
1769 bits = 4;
1770 break;
1771 case 8:
1772 bits = 3;
1773 break;
1774 case 2:
1775 bits = 1;
1776 break;
1777 default:
1778 assert(0); /* shouldn't ever get here */
1779 bits = 0; /* to silence gcc warning */
1780 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001781
Mark Dickinsone2846542012-04-20 21:21:24 +01001782 /* Compute exact length 'sz' of output string. */
1783 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001784 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001785 }
1786 else {
1787 Py_ssize_t size_a_in_bits;
1788 /* Ensure overflow doesn't occur during computation of sz. */
1789 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1790 PyErr_SetString(PyExc_OverflowError,
1791 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001793 }
1794 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1795 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001796 /* Allow 1 character for a '-' sign. */
1797 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1798 }
1799 if (alternate) {
1800 /* 2 characters for prefix */
1801 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001802 }
1803
Victor Stinnerd3f08822012-05-29 12:57:52 +02001804 if (writer) {
1805 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1806 return -1;
1807 kind = writer->kind;
1808 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 }
1810 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001811 v = PyUnicode_New(sz, 'x');
1812 if (v == NULL)
1813 return -1;
1814 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001816
Victor Stinnerd3f08822012-05-29 12:57:52 +02001817#define WRITE_DIGITS(TYPE) \
1818 do { \
1819 if (writer) \
1820 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1821 else \
1822 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1823 \
1824 if (size_a == 0) { \
1825 *--p = '0'; \
1826 } \
1827 else { \
1828 /* JRH: special case for power-of-2 bases */ \
1829 twodigits accum = 0; \
1830 int accumbits = 0; /* # of bits in accum */ \
1831 Py_ssize_t i; \
1832 for (i = 0; i < size_a; ++i) { \
1833 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1834 accumbits += PyLong_SHIFT; \
1835 assert(accumbits >= bits); \
1836 do { \
1837 char cdigit; \
1838 cdigit = (char)(accum & (base - 1)); \
1839 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1840 *--p = cdigit; \
1841 accumbits -= bits; \
1842 accum >>= bits; \
1843 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1844 } \
1845 } \
1846 \
1847 if (alternate) { \
1848 if (base == 16) \
1849 *--p = 'x'; \
1850 else if (base == 8) \
1851 *--p = 'o'; \
1852 else /* (base == 2) */ \
1853 *--p = 'b'; \
1854 *--p = '0'; \
1855 } \
1856 if (negative) \
1857 *--p = '-'; \
1858 if (writer) \
1859 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1860 else \
1861 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1862 } while (0)
1863
1864 if (kind == PyUnicode_1BYTE_KIND) {
1865 Py_UCS1 *p;
1866 WRITE_DIGITS(Py_UCS1);
1867 }
1868 else if (kind == PyUnicode_2BYTE_KIND) {
1869 Py_UCS2 *p;
1870 WRITE_DIGITS(Py_UCS2);
1871 }
1872 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001873 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001874 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001875 WRITE_DIGITS(Py_UCS4);
1876 }
1877#undef WRITE_DIGITS
1878
1879 if (writer) {
1880 writer->pos += sz;
1881 }
1882 else {
1883 assert(_PyUnicode_CheckConsistency(v, 1));
1884 *p_output = v;
1885 }
1886 return 0;
1887}
1888
1889PyObject *
1890_PyLong_Format(PyObject *obj, int base)
1891{
1892 PyObject *str;
1893 int err;
1894 if (base == 10)
1895 err = long_to_decimal_string_internal(obj, &str, NULL);
1896 else
1897 err = long_format_binary(obj, base, 1, &str, NULL);
1898 if (err == -1)
1899 return NULL;
1900 return str;
1901}
1902
1903int
1904_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1905 PyObject *obj,
1906 int base, int alternate)
1907{
1908 if (base == 10)
1909 return long_to_decimal_string_internal(obj, NULL, writer);
1910 else
1911 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001912}
1913
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914/* Table of digit values for 8-bit string -> integer conversion.
1915 * '0' maps to 0, ..., '9' maps to 9.
1916 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1917 * All other indices map to 37.
1918 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001919 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001920 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001921unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1923 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1924 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1925 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1926 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1927 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 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, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1931 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001938};
1939
1940/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001941 * 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 +03001942 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001943 * The point to this routine is that it takes time linear in the number of
1944 * string characters.
1945 */
1946static PyLongObject *
1947long_from_binary_base(char **str, int base)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 char *p = *str;
1950 char *start = p;
1951 int bits_per_char;
1952 Py_ssize_t n;
1953 PyLongObject *z;
1954 twodigits accum;
1955 int bits_in_accum;
1956 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1959 n = base;
1960 for (bits_per_char = -1; n; ++bits_per_char)
1961 n >>= 1;
1962 /* n <- total # of bits needed, while setting p to end-of-string */
1963 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1964 ++p;
1965 *str = p;
1966 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1967 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1968 if (n / bits_per_char < p - start) {
1969 PyErr_SetString(PyExc_ValueError,
1970 "int string too large to convert");
1971 return NULL;
1972 }
1973 n = n / PyLong_SHIFT;
1974 z = _PyLong_New(n);
1975 if (z == NULL)
1976 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001977 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 * from least to most significant in both.
1979 */
1980 accum = 0;
1981 bits_in_accum = 0;
1982 pdigit = z->ob_digit;
1983 while (--p >= start) {
1984 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1985 assert(k >= 0 && k < base);
1986 accum |= (twodigits)k << bits_in_accum;
1987 bits_in_accum += bits_per_char;
1988 if (bits_in_accum >= PyLong_SHIFT) {
1989 *pdigit++ = (digit)(accum & PyLong_MASK);
1990 assert(pdigit - z->ob_digit <= n);
1991 accum >>= PyLong_SHIFT;
1992 bits_in_accum -= PyLong_SHIFT;
1993 assert(bits_in_accum < PyLong_SHIFT);
1994 }
1995 }
1996 if (bits_in_accum) {
1997 assert(bits_in_accum <= PyLong_SHIFT);
1998 *pdigit++ = (digit)accum;
1999 assert(pdigit - z->ob_digit <= n);
2000 }
2001 while (pdigit - z->ob_digit < n)
2002 *pdigit++ = 0;
2003 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002004}
2005
Serhiy Storchaka95949422013-08-27 19:40:23 +03002006/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002007 * ignored.
2008 *
2009 * If successful, a PyLong object will be returned and 'pend' will be pointing
2010 * to the first unused byte unless it's NULL.
2011 *
2012 * If unsuccessful, NULL will be returned.
2013 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002014PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002015PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 int sign = 1, error_if_nonzero = 0;
2018 char *start, *orig_str = str;
2019 PyLongObject *z = NULL;
2020 PyObject *strobj;
2021 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if ((base != 0 && base < 2) || base > 36) {
2024 PyErr_SetString(PyExc_ValueError,
2025 "int() arg 2 must be >= 2 and <= 36");
2026 return NULL;
2027 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002028 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 str++;
2030 if (*str == '+')
2031 ++str;
2032 else if (*str == '-') {
2033 ++str;
2034 sign = -1;
2035 }
2036 if (base == 0) {
2037 if (str[0] != '0')
2038 base = 10;
2039 else if (str[1] == 'x' || str[1] == 'X')
2040 base = 16;
2041 else if (str[1] == 'o' || str[1] == 'O')
2042 base = 8;
2043 else if (str[1] == 'b' || str[1] == 'B')
2044 base = 2;
2045 else {
2046 /* "old" (C-style) octal literal, now invalid.
2047 it might still be zero though */
2048 error_if_nonzero = 1;
2049 base = 10;
2050 }
2051 }
2052 if (str[0] == '0' &&
2053 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2054 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2055 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2056 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 start = str;
2059 if ((base & (base - 1)) == 0)
2060 z = long_from_binary_base(&str, base);
2061 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062/***
2063Binary bases can be converted in time linear in the number of digits, because
2064Python's representation base is binary. Other bases (including decimal!) use
2065the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002066
Thomas Wouters477c8d52006-05-27 19:21:47 +00002067First some math: the largest integer that can be expressed in N base-B digits
2068is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2069case number of Python digits needed to hold it is the smallest integer n s.t.
2070
2071 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2072 BASE**n >= B**N [taking logs to base BASE]
2073 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2074
2075The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002076this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002077and the result is computed into it.
2078
2079The input string is actually treated as being in base base**i (i.e., i digits
2080are processed at a time), where two more static arrays hold:
2081
2082 convwidth_base[base] = the largest integer i such that base**i <= BASE
2083 convmultmax_base[base] = base ** convwidth_base[base]
2084
2085The first of these is the largest i such that i consecutive input digits
2086must fit in a single Python digit. The second is effectively the input
2087base we're really using.
2088
2089Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2090convmultmax_base[base], the result is "simply"
2091
2092 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2093
2094where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002095
2096Error analysis: as above, the number of Python digits `n` needed is worst-
2097case
2098
2099 n >= N * log(B)/log(BASE)
2100
2101where `N` is the number of input digits in base `B`. This is computed via
2102
2103 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2104
2105below. Two numeric concerns are how much space this can waste, and whether
2106the computed result can be too small. To be concrete, assume BASE = 2**15,
2107which is the default (and it's unlikely anyone changes that).
2108
2109Waste isn't a problem: provided the first input digit isn't 0, the difference
2110between the worst-case input with N digits and the smallest input with N
2111digits is about a factor of B, but B is small compared to BASE so at most
2112one allocated Python digit can remain unused on that count. If
2113N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2114and adding 1 returns a result 1 larger than necessary. However, that can't
2115happen: whenever B is a power of 2, long_from_binary_base() is called
2116instead, and it's impossible for B**i to be an integer power of 2**15 when
2117B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2118an exact integer when B is not a power of 2, since B**i has a prime factor
2119other than 2 in that case, but (2**15)**j's only prime factor is 2).
2120
2121The computed result can be too small if the true value of N*log(B)/log(BASE)
2122is a little bit larger than an exact integer, but due to roundoff errors (in
2123computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2124yields a numeric result a little less than that integer. Unfortunately, "how
2125close can a transcendental function get to an integer over some range?"
2126questions are generally theoretically intractable. Computer analysis via
2127continued fractions is practical: expand log(B)/log(BASE) via continued
2128fractions, giving a sequence i/j of "the best" rational approximations. Then
2129j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2130we can get very close to being in trouble, but very rarely. For example,
213176573 is a denominator in one of the continued-fraction approximations to
2132log(10)/log(2**15), and indeed:
2133
2134 >>> log(10)/log(2**15)*76573
2135 16958.000000654003
2136
2137is very close to an integer. If we were working with IEEE single-precision,
2138rounding errors could kill us. Finding worst cases in IEEE double-precision
2139requires better-than-double-precision log() functions, and Tim didn't bother.
2140Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002141new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002142This should happen extremely rarely, and in fact I don't have a test case
2143that triggers it(!). Instead the code was tested by artificially allocating
2144just 1 digit at the start, so that the copying code was exercised for every
2145digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002146***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 register twodigits c; /* current input character */
2148 Py_ssize_t size_z;
2149 int i;
2150 int convwidth;
2151 twodigits convmultmax, convmult;
2152 digit *pz, *pzstop;
2153 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 static double log_base_BASE[37] = {0.0e0,};
2156 static int convwidth_base[37] = {0,};
2157 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (log_base_BASE[base] == 0.0) {
2160 twodigits convmax = base;
2161 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002162
Mark Dickinson22b20182010-05-10 21:27:53 +00002163 log_base_BASE[base] = (log((double)base) /
2164 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 for (;;) {
2166 twodigits next = convmax * base;
2167 if (next > PyLong_BASE)
2168 break;
2169 convmax = next;
2170 ++i;
2171 }
2172 convmultmax_base[base] = convmax;
2173 assert(i > 0);
2174 convwidth_base[base] = i;
2175 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 /* Find length of the string of numeric characters. */
2178 scan = str;
2179 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2180 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002181
Serhiy Storchaka95949422013-08-27 19:40:23 +03002182 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 * integer with this base and length. Note that there's no
2184 * need to initialize z->ob_digit -- no slot is read up before
2185 * being stored into.
2186 */
2187 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2188 /* Uncomment next line to test exceedingly rare copy code */
2189 /* size_z = 1; */
2190 assert(size_z > 0);
2191 z = _PyLong_New(size_z);
2192 if (z == NULL)
2193 return NULL;
2194 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 /* `convwidth` consecutive input digits are treated as a single
2197 * digit in base `convmultmax`.
2198 */
2199 convwidth = convwidth_base[base];
2200 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* Work ;-) */
2203 while (str < scan) {
2204 /* grab up to convwidth digits from the input string */
2205 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2206 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2207 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002208 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 assert(c < PyLong_BASE);
2210 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 convmult = convmultmax;
2213 /* Calculate the shift only if we couldn't get
2214 * convwidth digits.
2215 */
2216 if (i != convwidth) {
2217 convmult = base;
2218 for ( ; i > 1; --i)
2219 convmult *= base;
2220 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /* Multiply z by convmult, and add c. */
2223 pz = z->ob_digit;
2224 pzstop = pz + Py_SIZE(z);
2225 for (; pz < pzstop; ++pz) {
2226 c += (twodigits)*pz * convmult;
2227 *pz = (digit)(c & PyLong_MASK);
2228 c >>= PyLong_SHIFT;
2229 }
2230 /* carry off the current end? */
2231 if (c) {
2232 assert(c < PyLong_BASE);
2233 if (Py_SIZE(z) < size_z) {
2234 *pz = (digit)c;
2235 ++Py_SIZE(z);
2236 }
2237 else {
2238 PyLongObject *tmp;
2239 /* Extremely rare. Get more space. */
2240 assert(Py_SIZE(z) == size_z);
2241 tmp = _PyLong_New(size_z + 1);
2242 if (tmp == NULL) {
2243 Py_DECREF(z);
2244 return NULL;
2245 }
2246 memcpy(tmp->ob_digit,
2247 z->ob_digit,
2248 sizeof(digit) * size_z);
2249 Py_DECREF(z);
2250 z = tmp;
2251 z->ob_digit[size_z] = (digit)c;
2252 ++size_z;
2253 }
2254 }
2255 }
2256 }
2257 if (z == NULL)
2258 return NULL;
2259 if (error_if_nonzero) {
2260 /* reset the base to 0, else the exception message
2261 doesn't make too much sense */
2262 base = 0;
2263 if (Py_SIZE(z) != 0)
2264 goto onError;
2265 /* there might still be other problems, therefore base
2266 remains zero here for the same reason */
2267 }
2268 if (str == start)
2269 goto onError;
2270 if (sign < 0)
2271 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002272 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 str++;
2274 if (*str != '\0')
2275 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002277 z = maybe_small_long(z);
2278 if (z == NULL)
2279 return NULL;
2280 if (pend != NULL)
2281 *pend = str;
2282 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002283
Mark Dickinson22b20182010-05-10 21:27:53 +00002284 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002285 if (pend != NULL)
2286 *pend = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 Py_XDECREF(z);
2288 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2289 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2290 if (strobj == NULL)
2291 return NULL;
2292 PyErr_Format(PyExc_ValueError,
2293 "invalid literal for int() with base %d: %R",
2294 base, strobj);
2295 Py_DECREF(strobj);
2296 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002297}
2298
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002299/* Since PyLong_FromString doesn't have a length parameter,
2300 * check here for possible NULs in the string.
2301 *
2302 * Reports an invalid literal as a bytes object.
2303 */
2304PyObject *
2305_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2306{
2307 PyObject *result, *strobj;
2308 char *end = NULL;
2309
2310 result = PyLong_FromString((char*)s, &end, base);
2311 if (end == NULL || (result != NULL && end == s + len))
2312 return result;
2313 Py_XDECREF(result);
2314 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2315 if (strobj != NULL) {
2316 PyErr_Format(PyExc_ValueError,
2317 "invalid literal for int() with base %d: %R",
2318 base, strobj);
2319 Py_DECREF(strobj);
2320 }
2321 return NULL;
2322}
2323
Guido van Rossum9e896b32000-04-05 20:11:21 +00002324PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002325PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002327 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2328 if (unicode == NULL)
2329 return NULL;
2330 v = PyLong_FromUnicodeObject(unicode, base);
2331 Py_DECREF(unicode);
2332 return v;
2333}
2334
2335PyObject *
2336PyLong_FromUnicodeObject(PyObject *u, int base)
2337{
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002338 PyObject *result, *asciidig, *strobj;
2339 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002340 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002342 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002343 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002345 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002346 if (buffer == NULL) {
2347 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002348 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2349 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002351 else {
2352 result = PyLong_FromString(buffer, &end, base);
2353 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2354 Py_DECREF(asciidig);
2355 return result;
2356 }
2357 Py_DECREF(asciidig);
2358 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002359 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002360 strobj = PySequence_GetSlice(u, 0, 200);
2361 if (strobj != NULL) {
2362 PyErr_Format(PyExc_ValueError,
2363 "invalid literal for int() with base %d: %R",
2364 base, strobj);
2365 Py_DECREF(strobj);
2366 }
2367 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002368}
2369
Tim Peters9f688bf2000-07-07 15:53:28 +00002370/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002371static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002373static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374
Serhiy Storchaka95949422013-08-27 19:40:23 +03002375/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376
Guido van Rossume32e0141992-01-19 16:31:05 +00002377static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002378long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2382 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (size_b == 0) {
2385 PyErr_SetString(PyExc_ZeroDivisionError,
2386 "integer division or modulo by zero");
2387 return -1;
2388 }
2389 if (size_a < size_b ||
2390 (size_a == size_b &&
2391 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2392 /* |a| < |b|. */
2393 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2394 if (*pdiv == NULL)
2395 return -1;
2396 Py_INCREF(a);
2397 *prem = (PyLongObject *) a;
2398 return 0;
2399 }
2400 if (size_b == 1) {
2401 digit rem = 0;
2402 z = divrem1(a, b->ob_digit[0], &rem);
2403 if (z == NULL)
2404 return -1;
2405 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2406 if (*prem == NULL) {
2407 Py_DECREF(z);
2408 return -1;
2409 }
2410 }
2411 else {
2412 z = x_divrem(a, b, prem);
2413 if (z == NULL)
2414 return -1;
2415 }
2416 /* Set the signs.
2417 The quotient z has the sign of a*b;
2418 the remainder r has the sign of a,
2419 so a = b*z + r. */
2420 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2421 NEGATE(z);
2422 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2423 NEGATE(*prem);
2424 *pdiv = maybe_small_long(z);
2425 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002426}
2427
Serhiy Storchaka95949422013-08-27 19:40:23 +03002428/* Unsigned int division with remainder -- the algorithm. The arguments v1
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002429 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002431static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002432x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 PyLongObject *v, *w, *a;
2435 Py_ssize_t i, k, size_v, size_w;
2436 int d;
2437 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2438 twodigits vv;
2439 sdigit zhi;
2440 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2443 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2444 handle the special case when the initial estimate q for a quotient
2445 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2446 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* allocate space; w will also be used to hold the final remainder */
2449 size_v = ABS(Py_SIZE(v1));
2450 size_w = ABS(Py_SIZE(w1));
2451 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2452 v = _PyLong_New(size_v+1);
2453 if (v == NULL) {
2454 *prem = NULL;
2455 return NULL;
2456 }
2457 w = _PyLong_New(size_w);
2458 if (w == NULL) {
2459 Py_DECREF(v);
2460 *prem = NULL;
2461 return NULL;
2462 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2465 shift v1 left by the same amount. Results go into w and v. */
2466 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2467 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2468 assert(carry == 0);
2469 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2470 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2471 v->ob_digit[size_v] = carry;
2472 size_v++;
2473 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2476 at most (and usually exactly) k = size_v - size_w digits. */
2477 k = size_v - size_w;
2478 assert(k >= 0);
2479 a = _PyLong_New(k);
2480 if (a == NULL) {
2481 Py_DECREF(w);
2482 Py_DECREF(v);
2483 *prem = NULL;
2484 return NULL;
2485 }
2486 v0 = v->ob_digit;
2487 w0 = w->ob_digit;
2488 wm1 = w0[size_w-1];
2489 wm2 = w0[size_w-2];
2490 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2491 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2492 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002495 Py_DECREF(a);
2496 Py_DECREF(w);
2497 Py_DECREF(v);
2498 *prem = NULL;
2499 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002500 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 /* estimate quotient digit q; may overestimate by 1 (rare) */
2503 vtop = vk[size_w];
2504 assert(vtop <= wm1);
2505 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2506 q = (digit)(vv / wm1);
2507 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2508 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2509 | vk[size_w-2])) {
2510 --q;
2511 r += wm1;
2512 if (r >= PyLong_BASE)
2513 break;
2514 }
2515 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2518 zhi = 0;
2519 for (i = 0; i < size_w; ++i) {
2520 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2521 -PyLong_BASE * q <= z < PyLong_BASE */
2522 z = (sdigit)vk[i] + zhi -
2523 (stwodigits)q * (stwodigits)w0[i];
2524 vk[i] = (digit)z & PyLong_MASK;
2525 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002526 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 /* add w back if q was too large (this branch taken rarely) */
2530 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2531 if ((sdigit)vtop + zhi < 0) {
2532 carry = 0;
2533 for (i = 0; i < size_w; ++i) {
2534 carry += vk[i] + w0[i];
2535 vk[i] = carry & PyLong_MASK;
2536 carry >>= PyLong_SHIFT;
2537 }
2538 --q;
2539 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* store quotient digit */
2542 assert(q < PyLong_BASE);
2543 *--ak = q;
2544 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /* unshift remainder; we reuse w to store the result */
2547 carry = v_rshift(w0, v0, size_w, d);
2548 assert(carry==0);
2549 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 *prem = long_normalize(w);
2552 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002553}
2554
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002555/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2556 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2557 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2558 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2559 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2560 -1.0. */
2561
2562/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2563#if DBL_MANT_DIG == 53
2564#define EXP2_DBL_MANT_DIG 9007199254740992.0
2565#else
2566#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2567#endif
2568
2569double
2570_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2573 /* See below for why x_digits is always large enough. */
2574 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2575 double dx;
2576 /* Correction term for round-half-to-even rounding. For a digit x,
2577 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2578 multiple of 4, rounding ties to a multiple of 8. */
2579 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 a_size = ABS(Py_SIZE(a));
2582 if (a_size == 0) {
2583 /* Special case for 0: significand 0.0, exponent 0. */
2584 *e = 0;
2585 return 0.0;
2586 }
2587 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2588 /* The following is an overflow-free version of the check
2589 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2590 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2591 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2592 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002593 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2597 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 Number of digits needed for result: write // for floor division.
2600 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2609 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2612 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2613 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 in both cases.
2620 */
2621 if (a_bits <= DBL_MANT_DIG + 2) {
2622 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2623 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2624 x_size = 0;
2625 while (x_size < shift_digits)
2626 x_digits[x_size++] = 0;
2627 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2628 (int)shift_bits);
2629 x_size += a_size;
2630 x_digits[x_size++] = rem;
2631 }
2632 else {
2633 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2634 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2635 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2636 a_size - shift_digits, (int)shift_bits);
2637 x_size = a_size - shift_digits;
2638 /* For correct rounding below, we need the least significant
2639 bit of x to be 'sticky' for this shift: if any of the bits
2640 shifted out was nonzero, we set the least significant bit
2641 of x. */
2642 if (rem)
2643 x_digits[0] |= 1;
2644 else
2645 while (shift_digits > 0)
2646 if (a->ob_digit[--shift_digits]) {
2647 x_digits[0] |= 1;
2648 break;
2649 }
2650 }
Victor Stinner63941882011-09-29 00:42:28 +02002651 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 /* Round, and convert to double. */
2654 x_digits[0] += half_even_correction[x_digits[0] & 7];
2655 dx = x_digits[--x_size];
2656 while (x_size > 0)
2657 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 /* Rescale; make correction if result is 1.0. */
2660 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2661 if (dx == 1.0) {
2662 if (a_bits == PY_SSIZE_T_MAX)
2663 goto overflow;
2664 dx = 0.5;
2665 a_bits += 1;
2666 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 *e = a_bits;
2669 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002670
2671 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* exponent > PY_SSIZE_T_MAX */
2673 PyErr_SetString(PyExc_OverflowError,
2674 "huge integer: number of bits overflows a Py_ssize_t");
2675 *e = 0;
2676 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002677}
2678
Serhiy Storchaka95949422013-08-27 19:40:23 +03002679/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002680 using the round-half-to-even rule in the case of a tie. */
2681
2682double
2683PyLong_AsDouble(PyObject *v)
2684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 Py_ssize_t exponent;
2686 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002687
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002688 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 PyErr_BadInternalCall();
2690 return -1.0;
2691 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002692 if (!PyLong_Check(v)) {
2693 PyErr_SetString(PyExc_TypeError, "an integer is required");
2694 return -1.0;
2695 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2697 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2698 PyErr_SetString(PyExc_OverflowError,
2699 "long int too large to convert to float");
2700 return -1.0;
2701 }
2702 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002703}
2704
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002705/* Methods */
2706
2707static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002708long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002711}
2712
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002713static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002714long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 if (Py_SIZE(a) != Py_SIZE(b)) {
2719 sign = Py_SIZE(a) - Py_SIZE(b);
2720 }
2721 else {
2722 Py_ssize_t i = ABS(Py_SIZE(a));
2723 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2724 ;
2725 if (i < 0)
2726 sign = 0;
2727 else {
2728 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2729 if (Py_SIZE(a) < 0)
2730 sign = -sign;
2731 }
2732 }
2733 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002734}
2735
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002736#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002738
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002739static PyObject *
2740long_richcompare(PyObject *self, PyObject *other, int op)
2741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 int result;
2743 PyObject *v;
2744 CHECK_BINOP(self, other);
2745 if (self == other)
2746 result = 0;
2747 else
2748 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2749 /* Convert the return value to a Boolean */
2750 switch (op) {
2751 case Py_EQ:
2752 v = TEST_COND(result == 0);
2753 break;
2754 case Py_NE:
2755 v = TEST_COND(result != 0);
2756 break;
2757 case Py_LE:
2758 v = TEST_COND(result <= 0);
2759 break;
2760 case Py_GE:
2761 v = TEST_COND(result >= 0);
2762 break;
2763 case Py_LT:
2764 v = TEST_COND(result == -1);
2765 break;
2766 case Py_GT:
2767 v = TEST_COND(result == 1);
2768 break;
2769 default:
2770 PyErr_BadArgument();
2771 return NULL;
2772 }
2773 Py_INCREF(v);
2774 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002775}
2776
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002777static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002778long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002779{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002780 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 Py_ssize_t i;
2782 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 i = Py_SIZE(v);
2785 switch(i) {
2786 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2787 case 0: return 0;
2788 case 1: return v->ob_digit[0];
2789 }
2790 sign = 1;
2791 x = 0;
2792 if (i < 0) {
2793 sign = -1;
2794 i = -(i);
2795 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002797 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2798 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2799 _PyHASH_MODULUS.
2800
2801 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2802 amounts to a rotation of the bits of x. To see this, write
2803
2804 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2805
2806 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2807 PyLong_SHIFT bits of x (those that are shifted out of the
2808 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2809 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2810 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2811 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2812 congruent to y modulo _PyHASH_MODULUS. So
2813
2814 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2815
2816 The right-hand side is just the result of rotating the
2817 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2818 not all _PyHASH_BITS bits of x are 1s, the same is true
2819 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2820 the reduction of x*2**PyLong_SHIFT modulo
2821 _PyHASH_MODULUS. */
2822 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2823 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002825 if (x >= _PyHASH_MODULUS)
2826 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 }
2828 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002829 if (x == (Py_uhash_t)-1)
2830 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002831 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002832}
2833
2834
Serhiy Storchaka95949422013-08-27 19:40:23 +03002835/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002836
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002837static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002838x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2841 PyLongObject *z;
2842 Py_ssize_t i;
2843 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 /* Ensure a is the larger of the two: */
2846 if (size_a < size_b) {
2847 { PyLongObject *temp = a; a = b; b = temp; }
2848 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002849 size_a = size_b;
2850 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 }
2852 z = _PyLong_New(size_a+1);
2853 if (z == NULL)
2854 return NULL;
2855 for (i = 0; i < size_b; ++i) {
2856 carry += a->ob_digit[i] + b->ob_digit[i];
2857 z->ob_digit[i] = carry & PyLong_MASK;
2858 carry >>= PyLong_SHIFT;
2859 }
2860 for (; i < size_a; ++i) {
2861 carry += a->ob_digit[i];
2862 z->ob_digit[i] = carry & PyLong_MASK;
2863 carry >>= PyLong_SHIFT;
2864 }
2865 z->ob_digit[i] = carry;
2866 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002867}
2868
2869/* Subtract the absolute values of two integers. */
2870
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002871static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002872x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002874 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2875 PyLongObject *z;
2876 Py_ssize_t i;
2877 int sign = 1;
2878 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 /* Ensure a is the larger of the two: */
2881 if (size_a < size_b) {
2882 sign = -1;
2883 { PyLongObject *temp = a; a = b; b = temp; }
2884 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002885 size_a = size_b;
2886 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 }
2888 else if (size_a == size_b) {
2889 /* Find highest digit where a and b differ: */
2890 i = size_a;
2891 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2892 ;
2893 if (i < 0)
2894 return (PyLongObject *)PyLong_FromLong(0);
2895 if (a->ob_digit[i] < b->ob_digit[i]) {
2896 sign = -1;
2897 { PyLongObject *temp = a; a = b; b = temp; }
2898 }
2899 size_a = size_b = i+1;
2900 }
2901 z = _PyLong_New(size_a);
2902 if (z == NULL)
2903 return NULL;
2904 for (i = 0; i < size_b; ++i) {
2905 /* The following assumes unsigned arithmetic
2906 works module 2**N for some N>PyLong_SHIFT. */
2907 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2908 z->ob_digit[i] = borrow & PyLong_MASK;
2909 borrow >>= PyLong_SHIFT;
2910 borrow &= 1; /* Keep only one sign bit */
2911 }
2912 for (; i < size_a; ++i) {
2913 borrow = a->ob_digit[i] - borrow;
2914 z->ob_digit[i] = borrow & PyLong_MASK;
2915 borrow >>= PyLong_SHIFT;
2916 borrow &= 1; /* Keep only one sign bit */
2917 }
2918 assert(borrow == 0);
2919 if (sign < 0)
2920 NEGATE(z);
2921 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002922}
2923
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002924static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002925long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2932 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2933 MEDIUM_VALUE(b));
2934 return result;
2935 }
2936 if (Py_SIZE(a) < 0) {
2937 if (Py_SIZE(b) < 0) {
2938 z = x_add(a, b);
2939 if (z != NULL && Py_SIZE(z) != 0)
2940 Py_SIZE(z) = -(Py_SIZE(z));
2941 }
2942 else
2943 z = x_sub(b, a);
2944 }
2945 else {
2946 if (Py_SIZE(b) < 0)
2947 z = x_sub(a, b);
2948 else
2949 z = x_add(a, b);
2950 }
2951 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002952}
2953
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002954static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002955long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2962 PyObject* r;
2963 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2964 return r;
2965 }
2966 if (Py_SIZE(a) < 0) {
2967 if (Py_SIZE(b) < 0)
2968 z = x_sub(a, b);
2969 else
2970 z = x_add(a, b);
2971 if (z != NULL && Py_SIZE(z) != 0)
2972 Py_SIZE(z) = -(Py_SIZE(z));
2973 }
2974 else {
2975 if (Py_SIZE(b) < 0)
2976 z = x_add(a, b);
2977 else
2978 z = x_sub(a, b);
2979 }
2980 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002981}
2982
Tim Peters5af4e6c2002-08-12 02:31:19 +00002983/* Grade school multiplication, ignoring the signs.
2984 * Returns the absolute value of the product, or NULL if error.
2985 */
2986static PyLongObject *
2987x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 PyLongObject *z;
2990 Py_ssize_t size_a = ABS(Py_SIZE(a));
2991 Py_ssize_t size_b = ABS(Py_SIZE(b));
2992 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 z = _PyLong_New(size_a + size_b);
2995 if (z == NULL)
2996 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
2999 if (a == b) {
3000 /* Efficient squaring per HAC, Algorithm 14.16:
3001 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3002 * Gives slightly less than a 2x speedup when a == b,
3003 * via exploiting that each entry in the multiplication
3004 * pyramid appears twice (except for the size_a squares).
3005 */
3006 for (i = 0; i < size_a; ++i) {
3007 twodigits carry;
3008 twodigits f = a->ob_digit[i];
3009 digit *pz = z->ob_digit + (i << 1);
3010 digit *pa = a->ob_digit + i + 1;
3011 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003014 Py_DECREF(z);
3015 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003016 });
Tim Peters0973b992004-08-29 22:16:50 +00003017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 carry = *pz + f * f;
3019 *pz++ = (digit)(carry & PyLong_MASK);
3020 carry >>= PyLong_SHIFT;
3021 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 /* Now f is added in twice in each column of the
3024 * pyramid it appears. Same as adding f<<1 once.
3025 */
3026 f <<= 1;
3027 while (pa < paend) {
3028 carry += *pz + *pa++ * f;
3029 *pz++ = (digit)(carry & PyLong_MASK);
3030 carry >>= PyLong_SHIFT;
3031 assert(carry <= (PyLong_MASK << 1));
3032 }
3033 if (carry) {
3034 carry += *pz;
3035 *pz++ = (digit)(carry & PyLong_MASK);
3036 carry >>= PyLong_SHIFT;
3037 }
3038 if (carry)
3039 *pz += (digit)(carry & PyLong_MASK);
3040 assert((carry >> PyLong_SHIFT) == 0);
3041 }
3042 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003043 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 for (i = 0; i < size_a; ++i) {
3045 twodigits carry = 0;
3046 twodigits f = a->ob_digit[i];
3047 digit *pz = z->ob_digit + i;
3048 digit *pb = b->ob_digit;
3049 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003052 Py_DECREF(z);
3053 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003054 });
Tim Peters0973b992004-08-29 22:16:50 +00003055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 while (pb < pbend) {
3057 carry += *pz + *pb++ * f;
3058 *pz++ = (digit)(carry & PyLong_MASK);
3059 carry >>= PyLong_SHIFT;
3060 assert(carry <= PyLong_MASK);
3061 }
3062 if (carry)
3063 *pz += (digit)(carry & PyLong_MASK);
3064 assert((carry >> PyLong_SHIFT) == 0);
3065 }
3066 }
3067 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003068}
3069
3070/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003071 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003072 split, and sets low and high such that abs(n) == (high << size) + low,
3073 viewing the shift as being by digits. The sign bit is ignored, and
3074 the return values are >= 0.
3075 Returns 0 on success, -1 on failure.
3076*/
3077static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003078kmul_split(PyLongObject *n,
3079 Py_ssize_t size,
3080 PyLongObject **high,
3081 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 PyLongObject *hi, *lo;
3084 Py_ssize_t size_lo, size_hi;
3085 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 size_lo = MIN(size_n, size);
3088 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 if ((hi = _PyLong_New(size_hi)) == NULL)
3091 return -1;
3092 if ((lo = _PyLong_New(size_lo)) == NULL) {
3093 Py_DECREF(hi);
3094 return -1;
3095 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3098 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 *high = long_normalize(hi);
3101 *low = long_normalize(lo);
3102 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003103}
3104
Tim Peters60004642002-08-12 22:01:34 +00003105static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3106
Tim Peters5af4e6c2002-08-12 02:31:19 +00003107/* Karatsuba multiplication. Ignores the input signs, and returns the
3108 * absolute value of the product (or NULL if error).
3109 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3110 */
3111static PyLongObject *
3112k_mul(PyLongObject *a, PyLongObject *b)
3113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 Py_ssize_t asize = ABS(Py_SIZE(a));
3115 Py_ssize_t bsize = ABS(Py_SIZE(b));
3116 PyLongObject *ah = NULL;
3117 PyLongObject *al = NULL;
3118 PyLongObject *bh = NULL;
3119 PyLongObject *bl = NULL;
3120 PyLongObject *ret = NULL;
3121 PyLongObject *t1, *t2, *t3;
3122 Py_ssize_t shift; /* the number of digits we split off */
3123 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3126 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3127 * Then the original product is
3128 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3129 * By picking X to be a power of 2, "*X" is just shifting, and it's
3130 * been reduced to 3 multiplies on numbers half the size.
3131 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 /* We want to split based on the larger number; fiddle so that b
3134 * is largest.
3135 */
3136 if (asize > bsize) {
3137 t1 = a;
3138 a = b;
3139 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 i = asize;
3142 asize = bsize;
3143 bsize = i;
3144 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 /* Use gradeschool math when either number is too small. */
3147 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3148 if (asize <= i) {
3149 if (asize == 0)
3150 return (PyLongObject *)PyLong_FromLong(0);
3151 else
3152 return x_mul(a, b);
3153 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 /* If a is small compared to b, splitting on b gives a degenerate
3156 * case with ah==0, and Karatsuba may be (even much) less efficient
3157 * than "grade school" then. However, we can still win, by viewing
3158 * b as a string of "big digits", each of width a->ob_size. That
3159 * leads to a sequence of balanced calls to k_mul.
3160 */
3161 if (2 * asize <= bsize)
3162 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* Split a & b into hi & lo pieces. */
3165 shift = bsize >> 1;
3166 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3167 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 if (a == b) {
3170 bh = ah;
3171 bl = al;
3172 Py_INCREF(bh);
3173 Py_INCREF(bl);
3174 }
3175 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 /* The plan:
3178 * 1. Allocate result space (asize + bsize digits: that's always
3179 * enough).
3180 * 2. Compute ah*bh, and copy into result at 2*shift.
3181 * 3. Compute al*bl, and copy into result at 0. Note that this
3182 * can't overlap with #2.
3183 * 4. Subtract al*bl from the result, starting at shift. This may
3184 * underflow (borrow out of the high digit), but we don't care:
3185 * we're effectively doing unsigned arithmetic mod
3186 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3187 * borrows and carries out of the high digit can be ignored.
3188 * 5. Subtract ah*bh from the result, starting at shift.
3189 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3190 * at shift.
3191 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* 1. Allocate result space. */
3194 ret = _PyLong_New(asize + bsize);
3195 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003196#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 /* Fill with trash, to catch reference to uninitialized digits. */
3198 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199#endif
Tim Peters44121a62002-08-12 06:17:58 +00003200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3202 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3203 assert(Py_SIZE(t1) >= 0);
3204 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3205 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3206 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* Zero-out the digits higher than the ah*bh copy. */
3209 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3210 if (i)
3211 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3212 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 /* 3. t2 <- al*bl, and copy into the low digits. */
3215 if ((t2 = k_mul(al, bl)) == NULL) {
3216 Py_DECREF(t1);
3217 goto fail;
3218 }
3219 assert(Py_SIZE(t2) >= 0);
3220 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3221 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 /* Zero out remaining digits. */
3224 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3225 if (i)
3226 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3229 * because it's fresher in cache.
3230 */
3231 i = Py_SIZE(ret) - shift; /* # digits after shift */
3232 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3233 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3236 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3239 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3240 Py_DECREF(ah);
3241 Py_DECREF(al);
3242 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 if (a == b) {
3245 t2 = t1;
3246 Py_INCREF(t2);
3247 }
3248 else if ((t2 = x_add(bh, bl)) == NULL) {
3249 Py_DECREF(t1);
3250 goto fail;
3251 }
3252 Py_DECREF(bh);
3253 Py_DECREF(bl);
3254 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 t3 = k_mul(t1, t2);
3257 Py_DECREF(t1);
3258 Py_DECREF(t2);
3259 if (t3 == NULL) goto fail;
3260 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 /* Add t3. It's not obvious why we can't run out of room here.
3263 * See the (*) comment after this function.
3264 */
3265 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3266 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269
Mark Dickinson22b20182010-05-10 21:27:53 +00003270 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 Py_XDECREF(ret);
3272 Py_XDECREF(ah);
3273 Py_XDECREF(al);
3274 Py_XDECREF(bh);
3275 Py_XDECREF(bl);
3276 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277}
3278
Tim Petersd6974a52002-08-13 20:37:51 +00003279/* (*) Why adding t3 can't "run out of room" above.
3280
Tim Petersab86c2b2002-08-15 20:06:00 +00003281Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3282to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003283
Tim Petersab86c2b2002-08-15 20:06:00 +000032841. For any integer i, i = c(i/2) + f(i/2). In particular,
3285 bsize = c(bsize/2) + f(bsize/2).
32862. shift = f(bsize/2)
32873. asize <= bsize
32884. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3289 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003290
Tim Petersab86c2b2002-08-15 20:06:00 +00003291We allocated asize + bsize result digits, and add t3 into them at an offset
3292of shift. This leaves asize+bsize-shift allocated digit positions for t3
3293to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3294asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003295
Tim Petersab86c2b2002-08-15 20:06:00 +00003296bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3297at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003298
Tim Petersab86c2b2002-08-15 20:06:00 +00003299If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3300digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3301most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003302
Tim Petersab86c2b2002-08-15 20:06:00 +00003303The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003304
Tim Petersab86c2b2002-08-15 20:06:00 +00003305 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003306
Tim Petersab86c2b2002-08-15 20:06:00 +00003307and we have asize + c(bsize/2) available digit positions. We need to show
3308this is always enough. An instance of c(bsize/2) cancels out in both, so
3309the question reduces to whether asize digits is enough to hold
3310(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3311then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3312asize 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 +00003313digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003314asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003315c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3316is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3317bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003318
Tim Peters48d52c02002-08-14 17:07:32 +00003319Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3320clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3321ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003322*/
3323
Tim Peters60004642002-08-12 22:01:34 +00003324/* b has at least twice the digits of a, and a is big enough that Karatsuba
3325 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3326 * of slices, each with a->ob_size digits, and multiply the slices by a,
3327 * one at a time. This gives k_mul balanced inputs to work with, and is
3328 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003329 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003330 * single-width slice overlap between successive partial sums).
3331 */
3332static PyLongObject *
3333k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 const Py_ssize_t asize = ABS(Py_SIZE(a));
3336 Py_ssize_t bsize = ABS(Py_SIZE(b));
3337 Py_ssize_t nbdone; /* # of b digits already multiplied */
3338 PyLongObject *ret;
3339 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 assert(asize > KARATSUBA_CUTOFF);
3342 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 /* Allocate result space, and zero it out. */
3345 ret = _PyLong_New(asize + bsize);
3346 if (ret == NULL)
3347 return NULL;
3348 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 /* Successive slices of b are copied into bslice. */
3351 bslice = _PyLong_New(asize);
3352 if (bslice == NULL)
3353 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 nbdone = 0;
3356 while (bsize > 0) {
3357 PyLongObject *product;
3358 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* Multiply the next slice of b by a. */
3361 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3362 nbtouse * sizeof(digit));
3363 Py_SIZE(bslice) = nbtouse;
3364 product = k_mul(a, bslice);
3365 if (product == NULL)
3366 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 /* Add into result. */
3369 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3370 product->ob_digit, Py_SIZE(product));
3371 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003373 bsize -= nbtouse;
3374 nbdone += nbtouse;
3375 }
Tim Peters60004642002-08-12 22:01:34 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 Py_DECREF(bslice);
3378 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003379
Mark Dickinson22b20182010-05-10 21:27:53 +00003380 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003381 Py_DECREF(ret);
3382 Py_XDECREF(bslice);
3383 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003384}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003385
3386static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003387long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 /* fast path for single-digit multiplication */
3394 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3395 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003396#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003398#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003399 /* if we don't have long long then we're almost certainly
3400 using 15-bit digits, so v will fit in a long. In the
3401 unlikely event that we're using 30-bit digits on a platform
3402 without long long, a large v will just cause us to fall
3403 through to the general multiplication code below. */
3404 if (v >= LONG_MIN && v <= LONG_MAX)
3405 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003406#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 z = k_mul(a, b);
3410 /* Negate if exactly one of the inputs is negative. */
3411 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3412 NEGATE(z);
3413 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003414}
3415
Guido van Rossume32e0141992-01-19 16:31:05 +00003416/* The / and % operators are now defined in terms of divmod().
3417 The expression a mod b has the value a - b*floor(a/b).
3418 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003419 |a| by |b|, with the sign of a. This is also expressed
3420 as a - b*trunc(a/b), if trunc truncates towards zero.
3421 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 a b a rem b a mod b
3423 13 10 3 3
3424 -13 10 -3 7
3425 13 -10 3 -7
3426 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003427 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003428 have different signs. We then subtract one from the 'div'
3429 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003430
Tim Peters47e52ee2004-08-30 02:44:38 +00003431/* Compute
3432 * *pdiv, *pmod = divmod(v, w)
3433 * NULL can be passed for pdiv or pmod, in which case that part of
3434 * the result is simply thrown away. The caller owns a reference to
3435 * each of these it requests (does not pass NULL for).
3436 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003437static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003438l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 if (long_divrem(v, w, &div, &mod) < 0)
3444 return -1;
3445 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3446 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3447 PyLongObject *temp;
3448 PyLongObject *one;
3449 temp = (PyLongObject *) long_add(mod, w);
3450 Py_DECREF(mod);
3451 mod = temp;
3452 if (mod == NULL) {
3453 Py_DECREF(div);
3454 return -1;
3455 }
3456 one = (PyLongObject *) PyLong_FromLong(1L);
3457 if (one == NULL ||
3458 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3459 Py_DECREF(mod);
3460 Py_DECREF(div);
3461 Py_XDECREF(one);
3462 return -1;
3463 }
3464 Py_DECREF(one);
3465 Py_DECREF(div);
3466 div = temp;
3467 }
3468 if (pdiv != NULL)
3469 *pdiv = div;
3470 else
3471 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003473 if (pmod != NULL)
3474 *pmod = mod;
3475 else
3476 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003479}
3480
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003481static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003482long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003484 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 CHECK_BINOP(a, b);
3487 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3488 div = NULL;
3489 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003490}
3491
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003492/* PyLong/PyLong -> float, with correctly rounded result. */
3493
3494#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3495#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003497static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003498long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 PyLongObject *a, *b, *x;
3501 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3502 digit mask, low;
3503 int inexact, negate, a_is_small, b_is_small;
3504 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003506 CHECK_BINOP(v, w);
3507 a = (PyLongObject *)v;
3508 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003510 /*
3511 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3514 1. choose a suitable integer 'shift'
3515 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3516 3. adjust x for correct rounding
3517 4. convert x to a double dx with the same value
3518 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3523 returns either 0.0 or -0.0, depending on the sign of b. For a and
3524 b both nonzero, ignore signs of a and b, and add the sign back in
3525 at the end. Now write a_bits and b_bits for the bit lengths of a
3526 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3527 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3532 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3533 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3534 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003536 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 1. The integer 'shift' is chosen so that x has the right number of
3539 bits for a double, plus two or three extra bits that will be used
3540 in the rounding decisions. Writing a_bits and b_bits for the
3541 number of significant bits in a and b respectively, a
3542 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 This is fine in the usual case, but if a/b is smaller than the
3547 smallest normal float then it can lead to double rounding on an
3548 IEEE 754 platform, giving incorrectly rounded results. So we
3549 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 2. The quantity x is computed by first shifting a (left -shift bits
3554 if shift <= 0, right shift bits if shift > 0) and then dividing by
3555 b. For both the shift and the division, we keep track of whether
3556 the result is inexact, in a flag 'inexact'; this information is
3557 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 With the choice of shift above, together with our assumption that
3560 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3561 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3564 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003566 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 For float representability, we need x/2**extra_bits <
3569 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3570 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003574 To round, we just modify the bottom digit of x in-place; this can
3575 end up giving a digit with value > PyLONG_MASK, but that's not a
3576 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 With the original choices for shift above, extra_bits will always
3579 be 2 or 3. Then rounding under the round-half-to-even rule, we
3580 round up iff the most significant of the extra bits is 1, and
3581 either: (a) the computation of x in step 2 had an inexact result,
3582 or (b) at least one other of the extra bits is 1, or (c) the least
3583 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 4. Conversion to a double is straightforward; all floating-point
3586 operations involved in the conversion are exact, so there's no
3587 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3590 The result will always be exactly representable as a double, except
3591 in the case that it overflows. To avoid dependence on the exact
3592 behaviour of ldexp on overflow, we check for overflow before
3593 applying ldexp. The result of ldexp is adjusted for sign before
3594 returning.
3595 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 /* Reduce to case where a and b are both positive. */
3598 a_size = ABS(Py_SIZE(a));
3599 b_size = ABS(Py_SIZE(b));
3600 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3601 if (b_size == 0) {
3602 PyErr_SetString(PyExc_ZeroDivisionError,
3603 "division by zero");
3604 goto error;
3605 }
3606 if (a_size == 0)
3607 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 /* Fast path for a and b small (exactly representable in a double).
3610 Relies on floating-point division being correctly rounded; results
3611 may be subject to double rounding on x86 machines that operate with
3612 the x87 FPU set to 64-bit precision. */
3613 a_is_small = a_size <= MANT_DIG_DIGITS ||
3614 (a_size == MANT_DIG_DIGITS+1 &&
3615 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3616 b_is_small = b_size <= MANT_DIG_DIGITS ||
3617 (b_size == MANT_DIG_DIGITS+1 &&
3618 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3619 if (a_is_small && b_is_small) {
3620 double da, db;
3621 da = a->ob_digit[--a_size];
3622 while (a_size > 0)
3623 da = da * PyLong_BASE + a->ob_digit[--a_size];
3624 db = b->ob_digit[--b_size];
3625 while (b_size > 0)
3626 db = db * PyLong_BASE + b->ob_digit[--b_size];
3627 result = da / db;
3628 goto success;
3629 }
Tim Peterse2a60002001-09-04 06:17:36 +00003630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 /* Catch obvious cases of underflow and overflow */
3632 diff = a_size - b_size;
3633 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3634 /* Extreme overflow */
3635 goto overflow;
3636 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3637 /* Extreme underflow */
3638 goto underflow_or_zero;
3639 /* Next line is now safe from overflowing a Py_ssize_t */
3640 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3641 bits_in_digit(b->ob_digit[b_size - 1]);
3642 /* Now diff = a_bits - b_bits. */
3643 if (diff > DBL_MAX_EXP)
3644 goto overflow;
3645 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3646 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* Choose value for shift; see comments for step 1 above. */
3649 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 /* x = abs(a * 2**-shift) */
3654 if (shift <= 0) {
3655 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3656 digit rem;
3657 /* x = a << -shift */
3658 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3659 /* In practice, it's probably impossible to end up
3660 here. Both a and b would have to be enormous,
3661 using close to SIZE_T_MAX bytes of memory each. */
3662 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003663 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 goto error;
3665 }
3666 x = _PyLong_New(a_size + shift_digits + 1);
3667 if (x == NULL)
3668 goto error;
3669 for (i = 0; i < shift_digits; i++)
3670 x->ob_digit[i] = 0;
3671 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3672 a_size, -shift % PyLong_SHIFT);
3673 x->ob_digit[a_size + shift_digits] = rem;
3674 }
3675 else {
3676 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3677 digit rem;
3678 /* x = a >> shift */
3679 assert(a_size >= shift_digits);
3680 x = _PyLong_New(a_size - shift_digits);
3681 if (x == NULL)
3682 goto error;
3683 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3684 a_size - shift_digits, shift % PyLong_SHIFT);
3685 /* set inexact if any of the bits shifted out is nonzero */
3686 if (rem)
3687 inexact = 1;
3688 while (!inexact && shift_digits > 0)
3689 if (a->ob_digit[--shift_digits])
3690 inexact = 1;
3691 }
3692 long_normalize(x);
3693 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003695 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3696 reference to x, so it's safe to modify it in-place. */
3697 if (b_size == 1) {
3698 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3699 b->ob_digit[0]);
3700 long_normalize(x);
3701 if (rem)
3702 inexact = 1;
3703 }
3704 else {
3705 PyLongObject *div, *rem;
3706 div = x_divrem(x, b, &rem);
3707 Py_DECREF(x);
3708 x = div;
3709 if (x == NULL)
3710 goto error;
3711 if (Py_SIZE(rem))
3712 inexact = 1;
3713 Py_DECREF(rem);
3714 }
3715 x_size = ABS(Py_SIZE(x));
3716 assert(x_size > 0); /* result of division is never zero */
3717 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 /* The number of extra bits that have to be rounded away. */
3720 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3721 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003723 /* Round by directly modifying the low digit of x. */
3724 mask = (digit)1 << (extra_bits - 1);
3725 low = x->ob_digit[0] | inexact;
3726 if (low & mask && low & (3*mask-1))
3727 low += mask;
3728 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 /* Convert x to a double dx; the conversion is exact. */
3731 dx = x->ob_digit[--x_size];
3732 while (x_size > 0)
3733 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3734 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 /* Check whether ldexp result will overflow a double. */
3737 if (shift + x_bits >= DBL_MAX_EXP &&
3738 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3739 goto overflow;
3740 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003741
3742 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003744
3745 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003746 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003747
3748 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 PyErr_SetString(PyExc_OverflowError,
3750 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003751 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003753}
3754
3755static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003756long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 CHECK_BINOP(a, b);
3761
3762 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3763 mod = NULL;
3764 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003765}
3766
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003767static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003768long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 PyLongObject *div, *mod;
3771 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3776 return NULL;
3777 }
3778 z = PyTuple_New(2);
3779 if (z != NULL) {
3780 PyTuple_SetItem(z, 0, (PyObject *) div);
3781 PyTuple_SetItem(z, 1, (PyObject *) mod);
3782 }
3783 else {
3784 Py_DECREF(div);
3785 Py_DECREF(mod);
3786 }
3787 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003788}
3789
Tim Peters47e52ee2004-08-30 02:44:38 +00003790/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003791static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003792long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3795 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 PyLongObject *z = NULL; /* accumulated result */
3798 Py_ssize_t i, j, k; /* counters */
3799 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003801 /* 5-ary values. If the exponent is large enough, table is
3802 * precomputed so that table[i] == a**i % c for i in range(32).
3803 */
3804 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3805 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003807 /* a, b, c = v, w, x */
3808 CHECK_BINOP(v, w);
3809 a = (PyLongObject*)v; Py_INCREF(a);
3810 b = (PyLongObject*)w; Py_INCREF(b);
3811 if (PyLong_Check(x)) {
3812 c = (PyLongObject *)x;
3813 Py_INCREF(x);
3814 }
3815 else if (x == Py_None)
3816 c = NULL;
3817 else {
3818 Py_DECREF(a);
3819 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003820 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003821 }
Tim Peters4c483c42001-09-05 06:24:58 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3824 if (c) {
3825 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003826 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 goto Error;
3828 }
3829 else {
3830 /* else return a float. This works because we know
3831 that this calls float_pow() which converts its
3832 arguments to double. */
3833 Py_DECREF(a);
3834 Py_DECREF(b);
3835 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3836 }
3837 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 if (c) {
3840 /* if modulus == 0:
3841 raise ValueError() */
3842 if (Py_SIZE(c) == 0) {
3843 PyErr_SetString(PyExc_ValueError,
3844 "pow() 3rd argument cannot be 0");
3845 goto Error;
3846 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 /* if modulus < 0:
3849 negativeOutput = True
3850 modulus = -modulus */
3851 if (Py_SIZE(c) < 0) {
3852 negativeOutput = 1;
3853 temp = (PyLongObject *)_PyLong_Copy(c);
3854 if (temp == NULL)
3855 goto Error;
3856 Py_DECREF(c);
3857 c = temp;
3858 temp = NULL;
3859 NEGATE(c);
3860 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003862 /* if modulus == 1:
3863 return 0 */
3864 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3865 z = (PyLongObject *)PyLong_FromLong(0L);
3866 goto Done;
3867 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003868
Tim Peters81a93152013-10-05 16:53:52 -05003869 /* Reduce base by modulus in some cases:
3870 1. If base < 0. Forcing the base non-negative makes things easier.
3871 2. If base is obviously larger than the modulus. The "small
3872 exponent" case later can multiply directly by base repeatedly,
3873 while the "large exponent" case multiplies directly by base 31
3874 times. It can be unboundedly faster to multiply by
3875 base % modulus instead.
3876 We could _always_ do this reduction, but l_divmod() isn't cheap,
3877 so we only do it when it buys something. */
3878 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 if (l_divmod(a, c, NULL, &temp) < 0)
3880 goto Error;
3881 Py_DECREF(a);
3882 a = temp;
3883 temp = NULL;
3884 }
3885 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003887 /* At this point a, b, and c are guaranteed non-negative UNLESS
3888 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 z = (PyLongObject *)PyLong_FromLong(1L);
3891 if (z == NULL)
3892 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003894 /* Perform a modular reduction, X = X % c, but leave X alone if c
3895 * is NULL.
3896 */
3897#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003898 do { \
3899 if (c != NULL) { \
3900 if (l_divmod(X, c, NULL, &temp) < 0) \
3901 goto Error; \
3902 Py_XDECREF(X); \
3903 X = temp; \
3904 temp = NULL; \
3905 } \
3906 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 /* Multiply two values, then reduce the result:
3909 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003910#define MULT(X, Y, result) \
3911 do { \
3912 temp = (PyLongObject *)long_mul(X, Y); \
3913 if (temp == NULL) \
3914 goto Error; \
3915 Py_XDECREF(result); \
3916 result = temp; \
3917 temp = NULL; \
3918 REDUCE(result); \
3919 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003921 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3922 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3923 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3924 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3925 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003928 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003930 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 }
3932 }
3933 }
3934 else {
3935 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3936 Py_INCREF(z); /* still holds 1L */
3937 table[0] = z;
3938 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003939 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3942 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3945 const int index = (bi >> j) & 0x1f;
3946 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003947 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003949 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 }
3951 }
3952 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 if (negativeOutput && (Py_SIZE(z) != 0)) {
3955 temp = (PyLongObject *)long_sub(z, c);
3956 if (temp == NULL)
3957 goto Error;
3958 Py_DECREF(z);
3959 z = temp;
3960 temp = NULL;
3961 }
3962 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003963
Mark Dickinson22b20182010-05-10 21:27:53 +00003964 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 if (z != NULL) {
3966 Py_DECREF(z);
3967 z = NULL;
3968 }
3969 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003970 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3972 for (i = 0; i < 32; ++i)
3973 Py_XDECREF(table[i]);
3974 }
3975 Py_DECREF(a);
3976 Py_DECREF(b);
3977 Py_XDECREF(c);
3978 Py_XDECREF(temp);
3979 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003980}
3981
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003982static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003983long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 /* Implement ~x as -(x+1) */
3986 PyLongObject *x;
3987 PyLongObject *w;
3988 if (ABS(Py_SIZE(v)) <=1)
3989 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3990 w = (PyLongObject *)PyLong_FromLong(1L);
3991 if (w == NULL)
3992 return NULL;
3993 x = (PyLongObject *) long_add(v, w);
3994 Py_DECREF(w);
3995 if (x == NULL)
3996 return NULL;
3997 Py_SIZE(x) = -(Py_SIZE(x));
3998 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003999}
4000
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004001static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004002long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004004 PyLongObject *z;
4005 if (ABS(Py_SIZE(v)) <= 1)
4006 return PyLong_FromLong(-MEDIUM_VALUE(v));
4007 z = (PyLongObject *)_PyLong_Copy(v);
4008 if (z != NULL)
4009 Py_SIZE(z) = -(Py_SIZE(v));
4010 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004011}
4012
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004013static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004014long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004016 if (Py_SIZE(v) < 0)
4017 return long_neg(v);
4018 else
4019 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004020}
4021
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004022static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004023long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004026}
4027
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004028static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004029long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004031 PyLongObject *z = NULL;
4032 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4033 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004035 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004037 if (Py_SIZE(a) < 0) {
4038 /* Right shifting negative numbers is harder */
4039 PyLongObject *a1, *a2;
4040 a1 = (PyLongObject *) long_invert(a);
4041 if (a1 == NULL)
4042 goto rshift_error;
4043 a2 = (PyLongObject *) long_rshift(a1, b);
4044 Py_DECREF(a1);
4045 if (a2 == NULL)
4046 goto rshift_error;
4047 z = (PyLongObject *) long_invert(a2);
4048 Py_DECREF(a2);
4049 }
4050 else {
4051 shiftby = PyLong_AsSsize_t((PyObject *)b);
4052 if (shiftby == -1L && PyErr_Occurred())
4053 goto rshift_error;
4054 if (shiftby < 0) {
4055 PyErr_SetString(PyExc_ValueError,
4056 "negative shift count");
4057 goto rshift_error;
4058 }
4059 wordshift = shiftby / PyLong_SHIFT;
4060 newsize = ABS(Py_SIZE(a)) - wordshift;
4061 if (newsize <= 0)
4062 return PyLong_FromLong(0);
4063 loshift = shiftby % PyLong_SHIFT;
4064 hishift = PyLong_SHIFT - loshift;
4065 lomask = ((digit)1 << hishift) - 1;
4066 himask = PyLong_MASK ^ lomask;
4067 z = _PyLong_New(newsize);
4068 if (z == NULL)
4069 goto rshift_error;
4070 if (Py_SIZE(a) < 0)
4071 Py_SIZE(z) = -(Py_SIZE(z));
4072 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4073 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4074 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004075 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 }
4077 z = long_normalize(z);
4078 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004079 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004080 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004081
Guido van Rossumc6913e71991-11-19 20:26:46 +00004082}
4083
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004084static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004085long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004087 /* This version due to Tim Peters */
4088 PyLongObject *a = (PyLongObject*)v;
4089 PyLongObject *b = (PyLongObject*)w;
4090 PyLongObject *z = NULL;
4091 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4092 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 shiftby = PyLong_AsSsize_t((PyObject *)b);
4097 if (shiftby == -1L && PyErr_Occurred())
4098 goto lshift_error;
4099 if (shiftby < 0) {
4100 PyErr_SetString(PyExc_ValueError, "negative shift count");
4101 goto lshift_error;
4102 }
4103 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4104 wordshift = shiftby / PyLong_SHIFT;
4105 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004107 oldsize = ABS(Py_SIZE(a));
4108 newsize = oldsize + wordshift;
4109 if (remshift)
4110 ++newsize;
4111 z = _PyLong_New(newsize);
4112 if (z == NULL)
4113 goto lshift_error;
4114 if (Py_SIZE(a) < 0)
4115 NEGATE(z);
4116 for (i = 0; i < wordshift; i++)
4117 z->ob_digit[i] = 0;
4118 accum = 0;
4119 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4120 accum |= (twodigits)a->ob_digit[j] << remshift;
4121 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4122 accum >>= PyLong_SHIFT;
4123 }
4124 if (remshift)
4125 z->ob_digit[newsize-1] = (digit)accum;
4126 else
4127 assert(!accum);
4128 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004129 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004130 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004131}
4132
Mark Dickinson27a87a22009-10-25 20:43:34 +00004133/* Compute two's complement of digit vector a[0:m], writing result to
4134 z[0:m]. The digit vector a need not be normalized, but should not
4135 be entirely zero. a and z may point to the same digit vector. */
4136
4137static void
4138v_complement(digit *z, digit *a, Py_ssize_t m)
4139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004140 Py_ssize_t i;
4141 digit carry = 1;
4142 for (i = 0; i < m; ++i) {
4143 carry += a[i] ^ PyLong_MASK;
4144 z[i] = carry & PyLong_MASK;
4145 carry >>= PyLong_SHIFT;
4146 }
4147 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004148}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004149
4150/* Bitwise and/xor/or operations */
4151
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004152static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004153long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004154 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004155 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 int nega, negb, negz;
4158 Py_ssize_t size_a, size_b, size_z, i;
4159 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004161 /* Bitwise operations for negative numbers operate as though
4162 on a two's complement representation. So convert arguments
4163 from sign-magnitude to two's complement, and convert the
4164 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 /* If a is negative, replace it by its two's complement. */
4167 size_a = ABS(Py_SIZE(a));
4168 nega = Py_SIZE(a) < 0;
4169 if (nega) {
4170 z = _PyLong_New(size_a);
4171 if (z == NULL)
4172 return NULL;
4173 v_complement(z->ob_digit, a->ob_digit, size_a);
4174 a = z;
4175 }
4176 else
4177 /* Keep reference count consistent. */
4178 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 /* Same for b. */
4181 size_b = ABS(Py_SIZE(b));
4182 negb = Py_SIZE(b) < 0;
4183 if (negb) {
4184 z = _PyLong_New(size_b);
4185 if (z == NULL) {
4186 Py_DECREF(a);
4187 return NULL;
4188 }
4189 v_complement(z->ob_digit, b->ob_digit, size_b);
4190 b = z;
4191 }
4192 else
4193 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004195 /* Swap a and b if necessary to ensure size_a >= size_b. */
4196 if (size_a < size_b) {
4197 z = a; a = b; b = z;
4198 size_z = size_a; size_a = size_b; size_b = size_z;
4199 negz = nega; nega = negb; negb = negz;
4200 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004202 /* JRH: The original logic here was to allocate the result value (z)
4203 as the longer of the two operands. However, there are some cases
4204 where the result is guaranteed to be shorter than that: AND of two
4205 positives, OR of two negatives: use the shorter number. AND with
4206 mixed signs: use the positive number. OR with mixed signs: use the
4207 negative number.
4208 */
4209 switch (op) {
4210 case '^':
4211 negz = nega ^ negb;
4212 size_z = size_a;
4213 break;
4214 case '&':
4215 negz = nega & negb;
4216 size_z = negb ? size_a : size_b;
4217 break;
4218 case '|':
4219 negz = nega | negb;
4220 size_z = negb ? size_b : size_a;
4221 break;
4222 default:
4223 PyErr_BadArgument();
4224 return NULL;
4225 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004227 /* We allow an extra digit if z is negative, to make sure that
4228 the final two's complement of z doesn't overflow. */
4229 z = _PyLong_New(size_z + negz);
4230 if (z == NULL) {
4231 Py_DECREF(a);
4232 Py_DECREF(b);
4233 return NULL;
4234 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 /* Compute digits for overlap of a and b. */
4237 switch(op) {
4238 case '&':
4239 for (i = 0; i < size_b; ++i)
4240 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4241 break;
4242 case '|':
4243 for (i = 0; i < size_b; ++i)
4244 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4245 break;
4246 case '^':
4247 for (i = 0; i < size_b; ++i)
4248 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4249 break;
4250 default:
4251 PyErr_BadArgument();
4252 return NULL;
4253 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 /* Copy any remaining digits of a, inverting if necessary. */
4256 if (op == '^' && negb)
4257 for (; i < size_z; ++i)
4258 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4259 else if (i < size_z)
4260 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4261 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004263 /* Complement result if negative. */
4264 if (negz) {
4265 Py_SIZE(z) = -(Py_SIZE(z));
4266 z->ob_digit[size_z] = PyLong_MASK;
4267 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4268 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004270 Py_DECREF(a);
4271 Py_DECREF(b);
4272 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004273}
4274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004275static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004276long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004278 PyObject *c;
4279 CHECK_BINOP(a, b);
4280 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4281 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004282}
4283
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004284static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004285long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 PyObject *c;
4288 CHECK_BINOP(a, b);
4289 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4290 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004291}
4292
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004293static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004294long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 PyObject *c;
4297 CHECK_BINOP(a, b);
4298 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4299 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004300}
4301
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004302static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004303long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 if (PyLong_CheckExact(v))
4306 Py_INCREF(v);
4307 else
4308 v = _PyLong_Copy((PyLongObject *)v);
4309 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004310}
4311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004312static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004313long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 double result;
4316 result = PyLong_AsDouble(v);
4317 if (result == -1.0 && PyErr_Occurred())
4318 return NULL;
4319 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004320}
4321
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004322static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004323long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004324
Tim Peters6d6c1a32001-08-02 04:15:00 +00004325static PyObject *
4326long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4327{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004328 PyObject *obase = NULL, *x = NULL;
4329 long base;
4330 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004331 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 if (type != &PyLong_Type)
4334 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004335 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4336 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004338 if (x == NULL) {
4339 if (obase != NULL) {
4340 PyErr_SetString(PyExc_TypeError,
4341 "int() missing string argument");
4342 return NULL;
4343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004345 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004346 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004348
4349 base = PyLong_AsLongAndOverflow(obase, &overflow);
4350 if (base == -1 && PyErr_Occurred())
4351 return NULL;
4352 if (overflow || (base != 0 && base < 2) || base > 36) {
4353 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004354 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004355 return NULL;
4356 }
4357
4358 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004359 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 if (PyByteArray_Check(x))
4363 string = PyByteArray_AS_STRING(x);
4364 else
4365 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004366 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 }
4368 else {
4369 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004370 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 return NULL;
4372 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004373}
4374
Serhiy Storchaka95949422013-08-27 19:40:23 +03004375/* Wimpy, slow approach to tp_new calls for subtypes of int:
4376 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004377 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004378 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004379*/
4380static PyObject *
4381long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 PyLongObject *tmp, *newobj;
4384 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 assert(PyType_IsSubtype(type, &PyLong_Type));
4387 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4388 if (tmp == NULL)
4389 return NULL;
4390 assert(PyLong_CheckExact(tmp));
4391 n = Py_SIZE(tmp);
4392 if (n < 0)
4393 n = -n;
4394 newobj = (PyLongObject *)type->tp_alloc(type, n);
4395 if (newobj == NULL) {
4396 Py_DECREF(tmp);
4397 return NULL;
4398 }
4399 assert(PyLong_Check(newobj));
4400 Py_SIZE(newobj) = Py_SIZE(tmp);
4401 for (i = 0; i < n; i++)
4402 newobj->ob_digit[i] = tmp->ob_digit[i];
4403 Py_DECREF(tmp);
4404 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004405}
4406
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004407static PyObject *
4408long_getnewargs(PyLongObject *v)
4409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004411}
4412
Guido van Rossumb43daf72007-08-01 18:08:08 +00004413static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004414long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004416}
4417
4418static PyObject *
4419long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004421}
4422
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004423static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004424long__format__(PyObject *self, PyObject *args)
4425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004427 _PyUnicodeWriter writer;
4428 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004430 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4431 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004432
4433 _PyUnicodeWriter_Init(&writer, 0);
4434 ret = _PyLong_FormatAdvancedWriter(
4435 &writer,
4436 self,
4437 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4438 if (ret == -1) {
4439 _PyUnicodeWriter_Dealloc(&writer);
4440 return NULL;
4441 }
4442 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004443}
4444
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004445/* Return a pair (q, r) such that a = b * q + r, and
4446 abs(r) <= abs(b)/2, with equality possible only if q is even.
4447 In other words, q == a / b, rounded to the nearest integer using
4448 round-half-to-even. */
4449
4450PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004451_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004452{
4453 PyLongObject *quo = NULL, *rem = NULL;
4454 PyObject *one = NULL, *twice_rem, *result, *temp;
4455 int cmp, quo_is_odd, quo_is_neg;
4456
4457 /* Equivalent Python code:
4458
4459 def divmod_near(a, b):
4460 q, r = divmod(a, b)
4461 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4462 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4463 # positive, 2 * r < b if b negative.
4464 greater_than_half = 2*r > b if b > 0 else 2*r < b
4465 exactly_half = 2*r == b
4466 if greater_than_half or exactly_half and q % 2 == 1:
4467 q += 1
4468 r -= b
4469 return q, r
4470
4471 */
4472 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4473 PyErr_SetString(PyExc_TypeError,
4474 "non-integer arguments in division");
4475 return NULL;
4476 }
4477
4478 /* Do a and b have different signs? If so, quotient is negative. */
4479 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4480
4481 one = PyLong_FromLong(1L);
4482 if (one == NULL)
4483 return NULL;
4484
4485 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4486 goto error;
4487
4488 /* compare twice the remainder with the divisor, to see
4489 if we need to adjust the quotient and remainder */
4490 twice_rem = long_lshift((PyObject *)rem, one);
4491 if (twice_rem == NULL)
4492 goto error;
4493 if (quo_is_neg) {
4494 temp = long_neg((PyLongObject*)twice_rem);
4495 Py_DECREF(twice_rem);
4496 twice_rem = temp;
4497 if (twice_rem == NULL)
4498 goto error;
4499 }
4500 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4501 Py_DECREF(twice_rem);
4502
4503 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4504 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4505 /* fix up quotient */
4506 if (quo_is_neg)
4507 temp = long_sub(quo, (PyLongObject *)one);
4508 else
4509 temp = long_add(quo, (PyLongObject *)one);
4510 Py_DECREF(quo);
4511 quo = (PyLongObject *)temp;
4512 if (quo == NULL)
4513 goto error;
4514 /* and remainder */
4515 if (quo_is_neg)
4516 temp = long_add(rem, (PyLongObject *)b);
4517 else
4518 temp = long_sub(rem, (PyLongObject *)b);
4519 Py_DECREF(rem);
4520 rem = (PyLongObject *)temp;
4521 if (rem == NULL)
4522 goto error;
4523 }
4524
4525 result = PyTuple_New(2);
4526 if (result == NULL)
4527 goto error;
4528
4529 /* PyTuple_SET_ITEM steals references */
4530 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4531 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4532 Py_DECREF(one);
4533 return result;
4534
4535 error:
4536 Py_XDECREF(quo);
4537 Py_XDECREF(rem);
4538 Py_XDECREF(one);
4539 return NULL;
4540}
4541
Eric Smith8c663262007-08-25 02:26:07 +00004542static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004543long_round(PyObject *self, PyObject *args)
4544{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004545 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004546
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004547 /* To round an integer m to the nearest 10**n (n positive), we make use of
4548 * the divmod_near operation, defined by:
4549 *
4550 * divmod_near(a, b) = (q, r)
4551 *
4552 * where q is the nearest integer to the quotient a / b (the
4553 * nearest even integer in the case of a tie) and r == a - q * b.
4554 * Hence q * b = a - r is the nearest multiple of b to a,
4555 * preferring even multiples in the case of a tie.
4556 *
4557 * So the nearest multiple of 10**n to m is:
4558 *
4559 * m - divmod_near(m, 10**n)[1].
4560 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004561 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4562 return NULL;
4563 if (o_ndigits == NULL)
4564 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004565
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004566 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004567 if (ndigits == NULL)
4568 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004569
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004570 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 if (Py_SIZE(ndigits) >= 0) {
4572 Py_DECREF(ndigits);
4573 return long_long(self);
4574 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004575
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004576 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4577 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004579 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004581 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004582
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004583 result = PyLong_FromLong(10L);
4584 if (result == NULL) {
4585 Py_DECREF(ndigits);
4586 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004588
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004589 temp = long_pow(result, ndigits, Py_None);
4590 Py_DECREF(ndigits);
4591 Py_DECREF(result);
4592 result = temp;
4593 if (result == NULL)
4594 return NULL;
4595
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004596 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004597 Py_DECREF(result);
4598 result = temp;
4599 if (result == NULL)
4600 return NULL;
4601
4602 temp = long_sub((PyLongObject *)self,
4603 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4604 Py_DECREF(result);
4605 result = temp;
4606
4607 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004608}
4609
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004610static PyObject *
4611long_sizeof(PyLongObject *v)
4612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004613 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004615 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4616 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004617}
4618
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004619static PyObject *
4620long_bit_length(PyLongObject *v)
4621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 PyLongObject *result, *x, *y;
4623 Py_ssize_t ndigits, msd_bits = 0;
4624 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004626 assert(v != NULL);
4627 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 ndigits = ABS(Py_SIZE(v));
4630 if (ndigits == 0)
4631 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 msd = v->ob_digit[ndigits-1];
4634 while (msd >= 32) {
4635 msd_bits += 6;
4636 msd >>= 6;
4637 }
4638 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4641 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 /* expression above may overflow; use Python integers instead */
4644 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4645 if (result == NULL)
4646 return NULL;
4647 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4648 if (x == NULL)
4649 goto error;
4650 y = (PyLongObject *)long_mul(result, x);
4651 Py_DECREF(x);
4652 if (y == NULL)
4653 goto error;
4654 Py_DECREF(result);
4655 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4658 if (x == NULL)
4659 goto error;
4660 y = (PyLongObject *)long_add(result, x);
4661 Py_DECREF(x);
4662 if (y == NULL)
4663 goto error;
4664 Py_DECREF(result);
4665 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004667 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004668
Mark Dickinson22b20182010-05-10 21:27:53 +00004669 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 Py_DECREF(result);
4671 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004672}
4673
4674PyDoc_STRVAR(long_bit_length_doc,
4675"int.bit_length() -> int\n\
4676\n\
4677Number of bits necessary to represent self in binary.\n\
4678>>> bin(37)\n\
4679'0b100101'\n\
4680>>> (37).bit_length()\n\
46816");
4682
Christian Heimes53876d92008-04-19 00:31:39 +00004683#if 0
4684static PyObject *
4685long_is_finite(PyObject *v)
4686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004688}
4689#endif
4690
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004691
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004692static PyObject *
4693long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004695 PyObject *byteorder_str;
4696 PyObject *is_signed_obj = NULL;
4697 Py_ssize_t length;
4698 int little_endian;
4699 int is_signed;
4700 PyObject *bytes;
4701 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4704 &length, &byteorder_str,
4705 &is_signed_obj))
4706 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 if (args != NULL && Py_SIZE(args) > 2) {
4709 PyErr_SetString(PyExc_TypeError,
4710 "'signed' is a keyword-only argument");
4711 return NULL;
4712 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4715 little_endian = 1;
4716 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4717 little_endian = 0;
4718 else {
4719 PyErr_SetString(PyExc_ValueError,
4720 "byteorder must be either 'little' or 'big'");
4721 return NULL;
4722 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 if (is_signed_obj != NULL) {
4725 int cmp = PyObject_IsTrue(is_signed_obj);
4726 if (cmp < 0)
4727 return NULL;
4728 is_signed = cmp ? 1 : 0;
4729 }
4730 else {
4731 /* If the signed argument was omitted, use False as the
4732 default. */
4733 is_signed = 0;
4734 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 if (length < 0) {
4737 PyErr_SetString(PyExc_ValueError,
4738 "length argument must be non-negative");
4739 return NULL;
4740 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 bytes = PyBytes_FromStringAndSize(NULL, length);
4743 if (bytes == NULL)
4744 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4747 length, little_endian, is_signed) < 0) {
4748 Py_DECREF(bytes);
4749 return NULL;
4750 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004753}
4754
Mark Dickinson078c2532010-01-30 18:06:17 +00004755PyDoc_STRVAR(long_to_bytes_doc,
4756"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004757\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004758Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004759\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004761raised if the integer is not representable with the given number of\n\
4762bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004763\n\
4764The byteorder argument determines the byte order used to represent the\n\
4765integer. If byteorder is 'big', the most significant byte is at the\n\
4766beginning of the byte array. If byteorder is 'little', the most\n\
4767significant byte is at the end of the byte array. To request the native\n\
4768byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4769\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004770The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004772is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004773
4774static PyObject *
4775long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 PyObject *byteorder_str;
4778 PyObject *is_signed_obj = NULL;
4779 int little_endian;
4780 int is_signed;
4781 PyObject *obj;
4782 PyObject *bytes;
4783 PyObject *long_obj;
4784 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4787 &obj, &byteorder_str,
4788 &is_signed_obj))
4789 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004791 if (args != NULL && Py_SIZE(args) > 2) {
4792 PyErr_SetString(PyExc_TypeError,
4793 "'signed' is a keyword-only argument");
4794 return NULL;
4795 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004797 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4798 little_endian = 1;
4799 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4800 little_endian = 0;
4801 else {
4802 PyErr_SetString(PyExc_ValueError,
4803 "byteorder must be either 'little' or 'big'");
4804 return NULL;
4805 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 if (is_signed_obj != NULL) {
4808 int cmp = PyObject_IsTrue(is_signed_obj);
4809 if (cmp < 0)
4810 return NULL;
4811 is_signed = cmp ? 1 : 0;
4812 }
4813 else {
4814 /* If the signed argument was omitted, use False as the
4815 default. */
4816 is_signed = 0;
4817 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004819 bytes = PyObject_Bytes(obj);
4820 if (bytes == NULL)
4821 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 long_obj = _PyLong_FromByteArray(
4824 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4825 little_endian, is_signed);
4826 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004829 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 */
4831 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4832 PyLongObject *newobj;
4833 int i;
4834 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 newobj = (PyLongObject *)type->tp_alloc(type, n);
4837 if (newobj == NULL) {
4838 Py_DECREF(long_obj);
4839 return NULL;
4840 }
4841 assert(PyLong_Check(newobj));
4842 Py_SIZE(newobj) = Py_SIZE(long_obj);
4843 for (i = 0; i < n; i++) {
4844 newobj->ob_digit[i] =
4845 ((PyLongObject *)long_obj)->ob_digit[i];
4846 }
4847 Py_DECREF(long_obj);
4848 return (PyObject *)newobj;
4849 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004852}
4853
Mark Dickinson078c2532010-01-30 18:06:17 +00004854PyDoc_STRVAR(long_from_bytes_doc,
4855"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4856\n\
4857Return the integer represented by the given array of bytes.\n\
4858\n\
4859The bytes argument must either support the buffer protocol or be an\n\
4860iterable object producing bytes. Bytes and bytearray are examples of\n\
4861built-in objects that support the buffer protocol.\n\
4862\n\
4863The byteorder argument determines the byte order used to represent the\n\
4864integer. If byteorder is 'big', the most significant byte is at the\n\
4865beginning of the byte array. If byteorder is 'little', the most\n\
4866significant byte is at the end of the byte array. To request the native\n\
4867byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4868\n\
4869The signed keyword-only argument indicates whether two's complement is\n\
4870used to represent the integer.");
4871
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004872static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4874 "Returns self, the complex conjugate of any int."},
4875 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4876 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004877#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4879 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004880#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004881 {"to_bytes", (PyCFunction)long_to_bytes,
4882 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4883 {"from_bytes", (PyCFunction)long_from_bytes,
4884 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4885 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4886 "Truncating an Integral returns itself."},
4887 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4888 "Flooring an Integral returns itself."},
4889 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4890 "Ceiling of an Integral returns itself."},
4891 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4892 "Rounding an Integral returns itself.\n"
4893 "Rounding with an ndigits argument also returns an integer."},
4894 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4895 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4896 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4897 "Returns size in memory, in bytes"},
4898 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004899};
4900
Guido van Rossumb43daf72007-08-01 18:08:08 +00004901static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004902 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004903 (getter)long_long, (setter)NULL,
4904 "the real part of a complex number",
4905 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004906 {"imag",
4907 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004908 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004909 NULL},
4910 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004911 (getter)long_long, (setter)NULL,
4912 "the numerator of a rational number in lowest terms",
4913 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004914 {"denominator",
4915 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004916 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004917 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004918 {NULL} /* Sentinel */
4919};
4920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004921PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004922"int(x=0) -> integer\n\
4923int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004924\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004925Convert a number or string to an integer, or return 0 if no arguments\n\
4926are given. If x is a number, return x.__int__(). For floating point\n\
4927numbers, this truncates towards zero.\n\
4928\n\
4929If x is not a number or if base is given, then x must be a string,\n\
4930bytes, or bytearray instance representing an integer literal in the\n\
4931given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4932by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4933Base 0 means to interpret the base from the string as an integer literal.\n\
4934>>> int('0b100', base=0)\n\
49354");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004936
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004937static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004938 (binaryfunc)long_add, /*nb_add*/
4939 (binaryfunc)long_sub, /*nb_subtract*/
4940 (binaryfunc)long_mul, /*nb_multiply*/
4941 long_mod, /*nb_remainder*/
4942 long_divmod, /*nb_divmod*/
4943 long_pow, /*nb_power*/
4944 (unaryfunc)long_neg, /*nb_negative*/
4945 (unaryfunc)long_long, /*tp_positive*/
4946 (unaryfunc)long_abs, /*tp_absolute*/
4947 (inquiry)long_bool, /*tp_bool*/
4948 (unaryfunc)long_invert, /*nb_invert*/
4949 long_lshift, /*nb_lshift*/
4950 (binaryfunc)long_rshift, /*nb_rshift*/
4951 long_and, /*nb_and*/
4952 long_xor, /*nb_xor*/
4953 long_or, /*nb_or*/
4954 long_long, /*nb_int*/
4955 0, /*nb_reserved*/
4956 long_float, /*nb_float*/
4957 0, /* nb_inplace_add */
4958 0, /* nb_inplace_subtract */
4959 0, /* nb_inplace_multiply */
4960 0, /* nb_inplace_remainder */
4961 0, /* nb_inplace_power */
4962 0, /* nb_inplace_lshift */
4963 0, /* nb_inplace_rshift */
4964 0, /* nb_inplace_and */
4965 0, /* nb_inplace_xor */
4966 0, /* nb_inplace_or */
4967 long_div, /* nb_floor_divide */
4968 long_true_divide, /* nb_true_divide */
4969 0, /* nb_inplace_floor_divide */
4970 0, /* nb_inplace_true_divide */
4971 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004972};
4973
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004974PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4976 "int", /* tp_name */
4977 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4978 sizeof(digit), /* tp_itemsize */
4979 long_dealloc, /* tp_dealloc */
4980 0, /* tp_print */
4981 0, /* tp_getattr */
4982 0, /* tp_setattr */
4983 0, /* tp_reserved */
4984 long_to_decimal_string, /* tp_repr */
4985 &long_as_number, /* tp_as_number */
4986 0, /* tp_as_sequence */
4987 0, /* tp_as_mapping */
4988 (hashfunc)long_hash, /* tp_hash */
4989 0, /* tp_call */
4990 long_to_decimal_string, /* tp_str */
4991 PyObject_GenericGetAttr, /* tp_getattro */
4992 0, /* tp_setattro */
4993 0, /* tp_as_buffer */
4994 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
4995 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
4996 long_doc, /* tp_doc */
4997 0, /* tp_traverse */
4998 0, /* tp_clear */
4999 long_richcompare, /* tp_richcompare */
5000 0, /* tp_weaklistoffset */
5001 0, /* tp_iter */
5002 0, /* tp_iternext */
5003 long_methods, /* tp_methods */
5004 0, /* tp_members */
5005 long_getset, /* tp_getset */
5006 0, /* tp_base */
5007 0, /* tp_dict */
5008 0, /* tp_descr_get */
5009 0, /* tp_descr_set */
5010 0, /* tp_dictoffset */
5011 0, /* tp_init */
5012 0, /* tp_alloc */
5013 long_new, /* tp_new */
5014 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005015};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005016
Mark Dickinsonbd792642009-03-18 20:06:12 +00005017static PyTypeObject Int_InfoType;
5018
5019PyDoc_STRVAR(int_info__doc__,
5020"sys.int_info\n\
5021\n\
5022A struct sequence that holds information about Python's\n\
5023internal representation of integers. The attributes are read only.");
5024
5025static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005027 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005029};
5030
5031static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 "sys.int_info", /* name */
5033 int_info__doc__, /* doc */
5034 int_info_fields, /* fields */
5035 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005036};
5037
5038PyObject *
5039PyLong_GetInfo(void)
5040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 PyObject* int_info;
5042 int field = 0;
5043 int_info = PyStructSequence_New(&Int_InfoType);
5044 if (int_info == NULL)
5045 return NULL;
5046 PyStructSequence_SET_ITEM(int_info, field++,
5047 PyLong_FromLong(PyLong_SHIFT));
5048 PyStructSequence_SET_ITEM(int_info, field++,
5049 PyLong_FromLong(sizeof(digit)));
5050 if (PyErr_Occurred()) {
5051 Py_CLEAR(int_info);
5052 return NULL;
5053 }
5054 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005055}
5056
Guido van Rossumddefaf32007-01-14 03:31:43 +00005057int
5058_PyLong_Init(void)
5059{
5060#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 int ival, size;
5062 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5065 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5066 if (Py_TYPE(v) == &PyLong_Type) {
5067 /* The element is already initialized, most likely
5068 * the Python interpreter was initialized before.
5069 */
5070 Py_ssize_t refcnt;
5071 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5074 _Py_NewReference(op);
5075 /* _Py_NewReference sets the ref count to 1 but
5076 * the ref count might be larger. Set the refcnt
5077 * to the original refcnt + 1 */
5078 Py_REFCNT(op) = refcnt + 1;
5079 assert(Py_SIZE(op) == size);
5080 assert(v->ob_digit[0] == abs(ival));
5081 }
5082 else {
5083 PyObject_INIT(v, &PyLong_Type);
5084 }
5085 Py_SIZE(v) = size;
5086 v->ob_digit[0] = abs(ival);
5087 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005088#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 /* initialize int_info */
5090 if (Int_InfoType.tp_name == 0)
5091 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005094}
5095
5096void
5097PyLong_Fini(void)
5098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 /* Integers are currently statically allocated. Py_DECREF is not
5100 needed, but Python must forget about the reference or multiple
5101 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005102#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 int i;
5104 PyLongObject *v = small_ints;
5105 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5106 _Py_DEC_REFTOTAL;
5107 _Py_ForgetReference((PyObject*)v);
5108 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005109#endif
5110}