blob: 29040e60a9f467215d92ba42d343d620aadb6042 [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 }
156 /* Issue #17576: warn if 'result' not of exact type int. */
157 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
158 "__int__ returned non-int (type %.200s). "
159 "The ability to return an instance of a strict subclass of int "
160 "is deprecated, and may be removed in a future version of Python.",
161 result->ob_type->tp_name)) {
162 Py_DECREF(result);
163 return NULL;
164 }
165 return (PyLongObject *)result;
166}
167
168
Serhiy Storchaka95949422013-08-27 19:40:23 +0300169/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000170 Return NULL and set exception if we run out of memory. */
171
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000172#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000174
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000176_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 PyLongObject *result;
179 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
180 sizeof(digit)*size. Previous incarnations of this code used
181 sizeof(PyVarObject) instead of the offsetof, but this risks being
182 incorrect in the presence of padding between the PyVarObject header
183 and the digits. */
184 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
185 PyErr_SetString(PyExc_OverflowError,
186 "too many digits in integer");
187 return NULL;
188 }
189 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
190 size*sizeof(digit));
191 if (!result) {
192 PyErr_NoMemory();
193 return NULL;
194 }
195 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000196}
197
Tim Peters64b5ce32001-09-10 20:52:51 +0000198PyObject *
199_PyLong_Copy(PyLongObject *src)
200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 PyLongObject *result;
202 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 assert(src != NULL);
205 i = Py_SIZE(src);
206 if (i < 0)
207 i = -(i);
208 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100209 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 CHECK_SMALL_INT(ival);
211 }
212 result = _PyLong_New(i);
213 if (result != NULL) {
214 Py_SIZE(result) = Py_SIZE(src);
215 while (--i >= 0)
216 result->ob_digit[i] = src->ob_digit[i];
217 }
218 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000219}
220
Serhiy Storchaka95949422013-08-27 19:40:23 +0300221/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000222
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000223PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000224PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 PyLongObject *v;
227 unsigned long abs_ival;
228 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
229 int ndigits = 0;
230 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (ival < 0) {
235 /* negate: can't write this as abs_ival = -ival since that
236 invokes undefined behaviour when ival is LONG_MIN */
237 abs_ival = 0U-(unsigned long)ival;
238 sign = -1;
239 }
240 else {
241 abs_ival = (unsigned long)ival;
242 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 /* Fast path for single-digit ints */
245 if (!(abs_ival >> PyLong_SHIFT)) {
246 v = _PyLong_New(1);
247 if (v) {
248 Py_SIZE(v) = sign;
249 v->ob_digit[0] = Py_SAFE_DOWNCAST(
250 abs_ival, unsigned long, digit);
251 }
252 return (PyObject*)v;
253 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000254
Mark Dickinson249b8982009-04-27 19:41:00 +0000255#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 /* 2 digits */
257 if (!(abs_ival >> 2*PyLong_SHIFT)) {
258 v = _PyLong_New(2);
259 if (v) {
260 Py_SIZE(v) = 2*sign;
261 v->ob_digit[0] = Py_SAFE_DOWNCAST(
262 abs_ival & PyLong_MASK, unsigned long, digit);
263 v->ob_digit[1] = Py_SAFE_DOWNCAST(
264 abs_ival >> PyLong_SHIFT, unsigned long, digit);
265 }
266 return (PyObject*)v;
267 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000268#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* Larger numbers: loop to determine number of digits */
271 t = abs_ival;
272 while (t) {
273 ++ndigits;
274 t >>= PyLong_SHIFT;
275 }
276 v = _PyLong_New(ndigits);
277 if (v != NULL) {
278 digit *p = v->ob_digit;
279 Py_SIZE(v) = ndigits*sign;
280 t = abs_ival;
281 while (t) {
282 *p++ = Py_SAFE_DOWNCAST(
283 t & PyLong_MASK, unsigned long, digit);
284 t >>= PyLong_SHIFT;
285 }
286 }
287 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000288}
289
Serhiy Storchaka95949422013-08-27 19:40:23 +0300290/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000291
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000292PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000293PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 PyLongObject *v;
296 unsigned long t;
297 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (ival < PyLong_BASE)
300 return PyLong_FromLong(ival);
301 /* Count the number of Python digits. */
302 t = (unsigned long)ival;
303 while (t) {
304 ++ndigits;
305 t >>= PyLong_SHIFT;
306 }
307 v = _PyLong_New(ndigits);
308 if (v != NULL) {
309 digit *p = v->ob_digit;
310 Py_SIZE(v) = ndigits;
311 while (ival) {
312 *p++ = (digit)(ival & PyLong_MASK);
313 ival >>= PyLong_SHIFT;
314 }
315 }
316 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000317}
318
Serhiy Storchaka95949422013-08-27 19:40:23 +0300319/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000320
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyLongObject *v;
325 double frac;
326 int i, ndig, expo, neg;
327 neg = 0;
328 if (Py_IS_INFINITY(dval)) {
329 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000330 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return NULL;
332 }
333 if (Py_IS_NAN(dval)) {
334 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000335 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 return NULL;
337 }
338 if (dval < 0.0) {
339 neg = 1;
340 dval = -dval;
341 }
342 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
343 if (expo <= 0)
344 return PyLong_FromLong(0L);
345 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
346 v = _PyLong_New(ndig);
347 if (v == NULL)
348 return NULL;
349 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
350 for (i = ndig; --i >= 0; ) {
351 digit bits = (digit)frac;
352 v->ob_digit[i] = bits;
353 frac = frac - (double)bits;
354 frac = ldexp(frac, PyLong_SHIFT);
355 }
356 if (neg)
357 Py_SIZE(v) = -(Py_SIZE(v));
358 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000359}
360
Thomas Wouters89f507f2006-12-13 04:49:30 +0000361/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
362 * anything about what happens when a signed integer operation overflows,
363 * and some compilers think they're doing you a favor by being "clever"
364 * then. The bit pattern for the largest postive signed long is
365 * (unsigned long)LONG_MAX, and for the smallest negative signed long
366 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
367 * However, some other compilers warn about applying unary minus to an
368 * unsigned operand. Hence the weird "0-".
369 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
371#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000372
Serhiy Storchaka95949422013-08-27 19:40:23 +0300373/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100374 method.
375
376 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
377 the result. Otherwise *overflow is 0.
378
379 For other errors (e.g., TypeError), return -1 and set an error condition.
380 In this case *overflow will be 0.
381*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000382
383long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000384PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* This version by Tim Peters */
387 register PyLongObject *v;
388 unsigned long x, prev;
389 long res;
390 Py_ssize_t i;
391 int sign;
392 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 *overflow = 0;
395 if (vv == NULL) {
396 PyErr_BadInternalCall();
397 return -1;
398 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000399
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200400 if (PyLong_Check(vv)) {
401 v = (PyLongObject *)vv;
402 }
403 else {
404 v = _PyLong_FromNbInt(vv);
405 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 return -1;
407 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 switch (i) {
414 case -1:
415 res = -(sdigit)v->ob_digit[0];
416 break;
417 case 0:
418 res = 0;
419 break;
420 case 1:
421 res = v->ob_digit[0];
422 break;
423 default:
424 sign = 1;
425 x = 0;
426 if (i < 0) {
427 sign = -1;
428 i = -(i);
429 }
430 while (--i >= 0) {
431 prev = x;
432 x = (x << PyLong_SHIFT) | v->ob_digit[i];
433 if ((x >> PyLong_SHIFT) != prev) {
434 *overflow = sign;
435 goto exit;
436 }
437 }
438 /* Haven't lost any bits, but casting to long requires extra
439 * care (see comment above).
440 */
441 if (x <= (unsigned long)LONG_MAX) {
442 res = (long)x * sign;
443 }
444 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
445 res = LONG_MIN;
446 }
447 else {
448 *overflow = sign;
449 /* res is already set to -1 */
450 }
451 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000452 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200454 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 }
456 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000457}
458
Serhiy Storchaka95949422013-08-27 19:40:23 +0300459/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100460 method. Return -1 and set an error if overflow occurs. */
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000463PyLong_AsLong(PyObject *obj)
464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 int overflow;
466 long result = PyLong_AsLongAndOverflow(obj, &overflow);
467 if (overflow) {
468 /* XXX: could be cute and give a different
469 message for overflow == -1 */
470 PyErr_SetString(PyExc_OverflowError,
471 "Python int too large to convert to C long");
472 }
473 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000474}
475
Serhiy Storchaka95949422013-08-27 19:40:23 +0300476/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka441d30f2013-01-19 12:26:26 +0200477 method. Return -1 and set an error if overflow occurs. */
478
479int
480_PyLong_AsInt(PyObject *obj)
481{
482 int overflow;
483 long result = PyLong_AsLongAndOverflow(obj, &overflow);
484 if (overflow || result > INT_MAX || result < INT_MIN) {
485 /* XXX: could be cute and give a different
486 message for overflow == -1 */
487 PyErr_SetString(PyExc_OverflowError,
488 "Python int too large to convert to C int");
489 return -1;
490 }
491 return (int)result;
492}
493
Serhiy Storchaka95949422013-08-27 19:40:23 +0300494/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000495 Returns -1 and sets an error condition if overflow occurs. */
496
497Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000498PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 register PyLongObject *v;
500 size_t x, prev;
501 Py_ssize_t i;
502 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (vv == NULL) {
505 PyErr_BadInternalCall();
506 return -1;
507 }
508 if (!PyLong_Check(vv)) {
509 PyErr_SetString(PyExc_TypeError, "an integer is required");
510 return -1;
511 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 v = (PyLongObject *)vv;
514 i = Py_SIZE(v);
515 switch (i) {
516 case -1: return -(sdigit)v->ob_digit[0];
517 case 0: return 0;
518 case 1: return v->ob_digit[0];
519 }
520 sign = 1;
521 x = 0;
522 if (i < 0) {
523 sign = -1;
524 i = -(i);
525 }
526 while (--i >= 0) {
527 prev = x;
528 x = (x << PyLong_SHIFT) | v->ob_digit[i];
529 if ((x >> PyLong_SHIFT) != prev)
530 goto overflow;
531 }
532 /* Haven't lost any bits, but casting to a signed type requires
533 * extra care (see comment above).
534 */
535 if (x <= (size_t)PY_SSIZE_T_MAX) {
536 return (Py_ssize_t)x * sign;
537 }
538 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
539 return PY_SSIZE_T_MIN;
540 }
541 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000542
Mark Dickinson22b20182010-05-10 21:27:53 +0000543 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 PyErr_SetString(PyExc_OverflowError,
545 "Python int too large to convert to C ssize_t");
546 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000547}
548
Serhiy Storchaka95949422013-08-27 19:40:23 +0300549/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000550 Returns -1 and sets an error condition if overflow occurs. */
551
552unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000553PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 register PyLongObject *v;
556 unsigned long x, prev;
557 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (vv == NULL) {
560 PyErr_BadInternalCall();
561 return (unsigned long)-1;
562 }
563 if (!PyLong_Check(vv)) {
564 PyErr_SetString(PyExc_TypeError, "an integer is required");
565 return (unsigned long)-1;
566 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 v = (PyLongObject *)vv;
569 i = Py_SIZE(v);
570 x = 0;
571 if (i < 0) {
572 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000573 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 return (unsigned long) -1;
575 }
576 switch (i) {
577 case 0: return 0;
578 case 1: return v->ob_digit[0];
579 }
580 while (--i >= 0) {
581 prev = x;
582 x = (x << PyLong_SHIFT) | v->ob_digit[i];
583 if ((x >> PyLong_SHIFT) != prev) {
584 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000585 "python int too large to convert "
586 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return (unsigned long) -1;
588 }
589 }
590 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000591}
592
Serhiy Storchaka95949422013-08-27 19:40:23 +0300593/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200594 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000595
596size_t
597PyLong_AsSize_t(PyObject *vv)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 register PyLongObject *v;
600 size_t x, prev;
601 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (vv == NULL) {
604 PyErr_BadInternalCall();
605 return (size_t) -1;
606 }
607 if (!PyLong_Check(vv)) {
608 PyErr_SetString(PyExc_TypeError, "an integer is required");
609 return (size_t)-1;
610 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 v = (PyLongObject *)vv;
613 i = Py_SIZE(v);
614 x = 0;
615 if (i < 0) {
616 PyErr_SetString(PyExc_OverflowError,
617 "can't convert negative value to size_t");
618 return (size_t) -1;
619 }
620 switch (i) {
621 case 0: return 0;
622 case 1: return v->ob_digit[0];
623 }
624 while (--i >= 0) {
625 prev = x;
626 x = (x << PyLong_SHIFT) | v->ob_digit[i];
627 if ((x >> PyLong_SHIFT) != prev) {
628 PyErr_SetString(PyExc_OverflowError,
629 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200630 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 }
632 }
633 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000634}
635
Serhiy Storchaka95949422013-08-27 19:40:23 +0300636/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000637 Returns -1 and sets an error condition if an error occurs. */
638
Guido van Rossumddefaf32007-01-14 03:31:43 +0000639static unsigned long
640_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 register PyLongObject *v;
643 unsigned long x;
644 Py_ssize_t i;
645 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (vv == NULL || !PyLong_Check(vv)) {
648 PyErr_BadInternalCall();
649 return (unsigned long) -1;
650 }
651 v = (PyLongObject *)vv;
652 i = Py_SIZE(v);
653 switch (i) {
654 case 0: return 0;
655 case 1: return v->ob_digit[0];
656 }
657 sign = 1;
658 x = 0;
659 if (i < 0) {
660 sign = -1;
661 i = -i;
662 }
663 while (--i >= 0) {
664 x = (x << PyLong_SHIFT) | v->ob_digit[i];
665 }
666 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000667}
668
Guido van Rossumddefaf32007-01-14 03:31:43 +0000669unsigned long
670PyLong_AsUnsignedLongMask(register PyObject *op)
671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyLongObject *lo;
673 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000674
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200675 if (op == NULL) {
676 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return (unsigned long)-1;
678 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000679
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200680 if (PyLong_Check(op)) {
681 return _PyLong_AsUnsignedLongMask(op);
682 }
683
684 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (lo == NULL)
686 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200687
688 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
689 Py_DECREF(lo);
690 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000691}
692
Tim Peters5b8132f2003-01-31 15:52:05 +0000693int
694_PyLong_Sign(PyObject *vv)
695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 assert(v != NULL);
699 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000702}
703
Tim Petersbaefd9e2003-01-28 20:37:45 +0000704size_t
705_PyLong_NumBits(PyObject *vv)
706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyLongObject *v = (PyLongObject *)vv;
708 size_t result = 0;
709 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 assert(v != NULL);
712 assert(PyLong_Check(v));
713 ndigits = ABS(Py_SIZE(v));
714 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
715 if (ndigits > 0) {
716 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100717 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100719 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 do {
721 ++result;
722 if (result == 0)
723 goto Overflow;
724 msd >>= 1;
725 } while (msd);
726 }
727 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000728
Mark Dickinson22b20182010-05-10 21:27:53 +0000729 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
731 "to express in a platform size_t");
732 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000733}
734
Tim Peters2a9b3672001-06-11 21:23:58 +0000735PyObject *
736_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000738{
Mark Dickinson22b20182010-05-10 21:27:53 +0000739 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 int incr; /* direction to move pstartbyte */
741 const unsigned char* pendbyte; /* MSB of bytes */
742 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300743 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyLongObject* v; /* result */
745 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (n == 0)
748 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (little_endian) {
751 pstartbyte = bytes;
752 pendbyte = bytes + n - 1;
753 incr = 1;
754 }
755 else {
756 pstartbyte = bytes + n - 1;
757 pendbyte = bytes;
758 incr = -1;
759 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 if (is_signed)
762 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200765 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 is positive, and leading 0xff bytes if negative. */
767 {
768 size_t i;
769 const unsigned char* p = pendbyte;
770 const int pincr = -incr; /* search MSB to LSB */
771 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 for (i = 0; i < n; ++i, p += pincr) {
774 if (*p != insignficant)
775 break;
776 }
777 numsignificantbytes = n - i;
778 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
779 actually has 2 significant bytes. OTOH, 0xff0001 ==
780 -0x00ffff, so we wouldn't *need* to bump it there; but we
781 do for 0xffff = -0x0001. To be safe without bothering to
782 check every case, bump it regardless. */
783 if (is_signed && numsignificantbytes < n)
784 ++numsignificantbytes;
785 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000786
Serhiy Storchaka95949422013-08-27 19:40:23 +0300787 /* How many Python int digits do we need? We have
788 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
790 /* catch overflow before it happens */
791 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
792 PyErr_SetString(PyExc_OverflowError,
793 "byte array too long to convert to int");
794 return NULL;
795 }
796 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
797 v = _PyLong_New(ndigits);
798 if (v == NULL)
799 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 /* Copy the bits over. The tricky parts are computing 2's-comp on
802 the fly for signed numbers, and dealing with the mismatch between
803 8-bit bytes and (probably) 15-bit Python digits.*/
804 {
805 size_t i;
806 twodigits carry = 1; /* for 2's-comp calculation */
807 twodigits accum = 0; /* sliding register */
808 unsigned int accumbits = 0; /* number of bits in accum */
809 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
812 twodigits thisbyte = *p;
813 /* Compute correction for 2's comp, if needed. */
814 if (is_signed) {
815 thisbyte = (0xff ^ thisbyte) + carry;
816 carry = thisbyte >> 8;
817 thisbyte &= 0xff;
818 }
819 /* Because we're going LSB to MSB, thisbyte is
820 more significant than what's already in accum,
821 so needs to be prepended to accum. */
822 accum |= (twodigits)thisbyte << accumbits;
823 accumbits += 8;
824 if (accumbits >= PyLong_SHIFT) {
825 /* There's enough to fill a Python digit. */
826 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000827 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 ++idigit;
829 accum >>= PyLong_SHIFT;
830 accumbits -= PyLong_SHIFT;
831 assert(accumbits < PyLong_SHIFT);
832 }
833 }
834 assert(accumbits < PyLong_SHIFT);
835 if (accumbits) {
836 assert(idigit < ndigits);
837 v->ob_digit[idigit] = (digit)accum;
838 ++idigit;
839 }
840 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 Py_SIZE(v) = is_signed ? -idigit : idigit;
843 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000844}
845
846int
847_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 unsigned char* bytes, size_t n,
849 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000852 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000854 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
856 digit carry; /* for computing 2's-comp */
857 size_t j; /* # bytes filled */
858 unsigned char* p; /* pointer to next byte in bytes */
859 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (Py_SIZE(v) < 0) {
864 ndigits = -(Py_SIZE(v));
865 if (!is_signed) {
866 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000867 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return -1;
869 }
870 do_twos_comp = 1;
871 }
872 else {
873 ndigits = Py_SIZE(v);
874 do_twos_comp = 0;
875 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (little_endian) {
878 p = bytes;
879 pincr = 1;
880 }
881 else {
882 p = bytes + n - 1;
883 pincr = -1;
884 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* Copy over all the Python digits.
887 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300888 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 normalized. */
890 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
891 j = 0;
892 accum = 0;
893 accumbits = 0;
894 carry = do_twos_comp ? 1 : 0;
895 for (i = 0; i < ndigits; ++i) {
896 digit thisdigit = v->ob_digit[i];
897 if (do_twos_comp) {
898 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
899 carry = thisdigit >> PyLong_SHIFT;
900 thisdigit &= PyLong_MASK;
901 }
902 /* Because we're going LSB to MSB, thisdigit is more
903 significant than what's already in accum, so needs to be
904 prepended to accum. */
905 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* The most-significant digit may be (probably is) at least
908 partly empty. */
909 if (i == ndigits - 1) {
910 /* Count # of sign bits -- they needn't be stored,
911 * although for signed conversion we need later to
912 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000913 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 while (s != 0) {
915 s >>= 1;
916 accumbits++;
917 }
918 }
919 else
920 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Store as many bytes as possible. */
923 while (accumbits >= 8) {
924 if (j >= n)
925 goto Overflow;
926 ++j;
927 *p = (unsigned char)(accum & 0xff);
928 p += pincr;
929 accumbits -= 8;
930 accum >>= 8;
931 }
932 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* Store the straggler (if any). */
935 assert(accumbits < 8);
936 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
937 if (accumbits > 0) {
938 if (j >= n)
939 goto Overflow;
940 ++j;
941 if (do_twos_comp) {
942 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300943 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 infinite supply of sign bits). */
945 accum |= (~(twodigits)0) << accumbits;
946 }
947 *p = (unsigned char)(accum & 0xff);
948 p += pincr;
949 }
950 else if (j == n && n > 0 && is_signed) {
951 /* The main loop filled the byte array exactly, so the code
952 just above didn't get to ensure there's a sign bit, and the
953 loop below wouldn't add one either. Make sure a sign bit
954 exists. */
955 unsigned char msb = *(p - pincr);
956 int sign_bit_set = msb >= 0x80;
957 assert(accumbits == 0);
958 if (sign_bit_set == do_twos_comp)
959 return 0;
960 else
961 goto Overflow;
962 }
Tim Peters05607ad2001-06-13 21:01:27 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 /* Fill remaining bytes with copies of the sign bit. */
965 {
966 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
967 for ( ; j < n; ++j, p += pincr)
968 *p = signbyte;
969 }
Tim Peters05607ad2001-06-13 21:01:27 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000972
Mark Dickinson22b20182010-05-10 21:27:53 +0000973 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
975 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000976
Tim Peters2a9b3672001-06-11 21:23:58 +0000977}
978
Serhiy Storchaka95949422013-08-27 19:40:23 +0300979/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000980
981PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000982PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000983{
Mark Dickinson91044792012-10-18 19:21:43 +0100984#if SIZEOF_VOID_P <= SIZEOF_LONG
985 /* special-case null pointer */
986 if (!p)
987 return PyLong_FromLong(0);
988 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
989#else
990
Tim Peters70128a12001-06-16 08:48:40 +0000991#ifndef HAVE_LONG_LONG
992# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
993#endif
994#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000995# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000996#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* special-case null pointer */
998 if (!p)
999 return PyLong_FromLong(0);
1000 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001001#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001002
Guido van Rossum78694d91998-09-18 14:14:13 +00001003}
1004
Serhiy Storchaka95949422013-08-27 19:40:23 +03001005/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001006
1007void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001008PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001009{
Tim Peters70128a12001-06-16 08:48:40 +00001010#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1014 x = PyLong_AsLong(vv);
1015 else
1016 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001017#else
Tim Peters70128a12001-06-16 08:48:40 +00001018
1019#ifndef HAVE_LONG_LONG
1020# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1021#endif
1022#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001024#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1028 x = PyLong_AsLongLong(vv);
1029 else
1030 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001031
1032#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (x == -1 && PyErr_Occurred())
1035 return NULL;
1036 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001037}
1038
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001040
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001042 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043 */
1044
Tim Peterscf37dfc2001-06-14 18:42:50 +00001045#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
Mark Dickinson22b20182010-05-10 21:27:53 +00001046#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001047
Serhiy Storchaka95949422013-08-27 19:40:23 +03001048/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001049
1050PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001051PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyLongObject *v;
1054 unsigned PY_LONG_LONG abs_ival;
1055 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1056 int ndigits = 0;
1057 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 CHECK_SMALL_INT(ival);
1060 if (ival < 0) {
1061 /* avoid signed overflow on negation; see comments
1062 in PyLong_FromLong above. */
1063 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1064 negative = 1;
1065 }
1066 else {
1067 abs_ival = (unsigned PY_LONG_LONG)ival;
1068 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Count the number of Python digits.
1071 We used to pick 5 ("big enough for anything"), but that's a
1072 waste of time and space given that 5*15 = 75 bits are rarely
1073 needed. */
1074 t = abs_ival;
1075 while (t) {
1076 ++ndigits;
1077 t >>= PyLong_SHIFT;
1078 }
1079 v = _PyLong_New(ndigits);
1080 if (v != NULL) {
1081 digit *p = v->ob_digit;
1082 Py_SIZE(v) = negative ? -ndigits : ndigits;
1083 t = abs_ival;
1084 while (t) {
1085 *p++ = (digit)(t & PyLong_MASK);
1086 t >>= PyLong_SHIFT;
1087 }
1088 }
1089 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001090}
1091
Serhiy Storchaka95949422013-08-27 19:40:23 +03001092/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001093
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001094PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001095PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyLongObject *v;
1098 unsigned PY_LONG_LONG t;
1099 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (ival < PyLong_BASE)
1102 return PyLong_FromLong((long)ival);
1103 /* Count the number of Python digits. */
1104 t = (unsigned PY_LONG_LONG)ival;
1105 while (t) {
1106 ++ndigits;
1107 t >>= PyLong_SHIFT;
1108 }
1109 v = _PyLong_New(ndigits);
1110 if (v != NULL) {
1111 digit *p = v->ob_digit;
1112 Py_SIZE(v) = ndigits;
1113 while (ival) {
1114 *p++ = (digit)(ival & PyLong_MASK);
1115 ival >>= PyLong_SHIFT;
1116 }
1117 }
1118 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001119}
1120
Serhiy Storchaka95949422013-08-27 19:40:23 +03001121/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001122
1123PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001124PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyLongObject *v;
1127 size_t abs_ival;
1128 size_t t; /* unsigned so >> doesn't propagate sign bit */
1129 int ndigits = 0;
1130 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 CHECK_SMALL_INT(ival);
1133 if (ival < 0) {
1134 /* avoid signed overflow when ival = SIZE_T_MIN */
1135 abs_ival = (size_t)(-1-ival)+1;
1136 negative = 1;
1137 }
1138 else {
1139 abs_ival = (size_t)ival;
1140 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Count the number of Python digits. */
1143 t = abs_ival;
1144 while (t) {
1145 ++ndigits;
1146 t >>= PyLong_SHIFT;
1147 }
1148 v = _PyLong_New(ndigits);
1149 if (v != NULL) {
1150 digit *p = v->ob_digit;
1151 Py_SIZE(v) = negative ? -ndigits : ndigits;
1152 t = abs_ival;
1153 while (t) {
1154 *p++ = (digit)(t & PyLong_MASK);
1155 t >>= PyLong_SHIFT;
1156 }
1157 }
1158 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159}
1160
Serhiy Storchaka95949422013-08-27 19:40:23 +03001161/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162
1163PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001164PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyLongObject *v;
1167 size_t t;
1168 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (ival < PyLong_BASE)
1171 return PyLong_FromLong((long)ival);
1172 /* Count the number of Python digits. */
1173 t = ival;
1174 while (t) {
1175 ++ndigits;
1176 t >>= PyLong_SHIFT;
1177 }
1178 v = _PyLong_New(ndigits);
1179 if (v != NULL) {
1180 digit *p = v->ob_digit;
1181 Py_SIZE(v) = ndigits;
1182 while (ival) {
1183 *p++ = (digit)(ival & PyLong_MASK);
1184 ival >>= PyLong_SHIFT;
1185 }
1186 }
1187 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188}
1189
Serhiy Storchaka95949422013-08-27 19:40:23 +03001190/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001191 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001192
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001193PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001194PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyLongObject *v;
1197 PY_LONG_LONG bytes;
1198 int one = 1;
1199 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001200 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (vv == NULL) {
1203 PyErr_BadInternalCall();
1204 return -1;
1205 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001206
1207 if (PyLong_Check(vv)) {
1208 v = (PyLongObject *)vv;
1209 }
1210 else {
1211 v = _PyLong_FromNbInt(vv);
1212 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001214 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001216
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001217 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001219 case -1:
1220 bytes = -(sdigit)v->ob_digit[0];
1221 break;
1222 case 0:
1223 bytes = 0;
1224 break;
1225 case 1:
1226 bytes = v->ob_digit[0];
1227 break;
1228 default:
1229 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
1230 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001232 if (do_decref) {
1233 Py_DECREF(v);
1234 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1237 if (res < 0)
1238 return (PY_LONG_LONG)-1;
1239 else
1240 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001241}
1242
Serhiy Storchaka95949422013-08-27 19:40:23 +03001243/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001244 Return -1 and set an error if overflow occurs. */
1245
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001246unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001247PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 PyLongObject *v;
1250 unsigned PY_LONG_LONG bytes;
1251 int one = 1;
1252 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001253
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001254 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 PyErr_BadInternalCall();
1256 return (unsigned PY_LONG_LONG)-1;
1257 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001258 if (!PyLong_Check(vv)) {
1259 PyErr_SetString(PyExc_TypeError, "an integer is required");
1260 return (unsigned PY_LONG_LONG)-1;
1261 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 v = (PyLongObject*)vv;
1264 switch(Py_SIZE(v)) {
1265 case 0: return 0;
1266 case 1: return v->ob_digit[0];
1267 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001268
Mark Dickinson22b20182010-05-10 21:27:53 +00001269 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
1270 SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1273 if (res < 0)
1274 return (unsigned PY_LONG_LONG)res;
1275 else
1276 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001277}
Tim Petersd1a7da62001-06-13 00:35:57 +00001278
Serhiy Storchaka95949422013-08-27 19:40:23 +03001279/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001280 Returns -1 and sets an error condition if an error occurs. */
1281
Guido van Rossumddefaf32007-01-14 03:31:43 +00001282static unsigned PY_LONG_LONG
1283_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 register PyLongObject *v;
1286 unsigned PY_LONG_LONG x;
1287 Py_ssize_t i;
1288 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (vv == NULL || !PyLong_Check(vv)) {
1291 PyErr_BadInternalCall();
1292 return (unsigned long) -1;
1293 }
1294 v = (PyLongObject *)vv;
1295 switch(Py_SIZE(v)) {
1296 case 0: return 0;
1297 case 1: return v->ob_digit[0];
1298 }
1299 i = Py_SIZE(v);
1300 sign = 1;
1301 x = 0;
1302 if (i < 0) {
1303 sign = -1;
1304 i = -i;
1305 }
1306 while (--i >= 0) {
1307 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1308 }
1309 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001310}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001311
1312unsigned PY_LONG_LONG
1313PyLong_AsUnsignedLongLongMask(register PyObject *op)
1314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyLongObject *lo;
1316 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001317
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001318 if (op == NULL) {
1319 PyErr_BadInternalCall();
1320 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001322
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001323 if (PyLong_Check(op)) {
1324 return _PyLong_AsUnsignedLongLongMask(op);
1325 }
1326
1327 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (lo == NULL)
1329 return (unsigned PY_LONG_LONG)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001330
1331 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1332 Py_DECREF(lo);
1333 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001334}
Tim Petersd1a7da62001-06-13 00:35:57 +00001335#undef IS_LITTLE_ENDIAN
1336
Serhiy Storchaka95949422013-08-27 19:40:23 +03001337/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001338 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001339
Mark Dickinson8d48b432011-10-23 20:47:14 +01001340 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1341 the result. Otherwise *overflow is 0.
1342
1343 For other errors (e.g., TypeError), return -1 and set an error condition.
1344 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001345*/
1346
1347PY_LONG_LONG
1348PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* This version by Tim Peters */
1351 register PyLongObject *v;
1352 unsigned PY_LONG_LONG x, prev;
1353 PY_LONG_LONG res;
1354 Py_ssize_t i;
1355 int sign;
1356 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 *overflow = 0;
1359 if (vv == NULL) {
1360 PyErr_BadInternalCall();
1361 return -1;
1362 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001363
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001364 if (PyLong_Check(vv)) {
1365 v = (PyLongObject *)vv;
1366 }
1367 else {
1368 v = _PyLong_FromNbInt(vv);
1369 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 return -1;
1371 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 switch (i) {
1378 case -1:
1379 res = -(sdigit)v->ob_digit[0];
1380 break;
1381 case 0:
1382 res = 0;
1383 break;
1384 case 1:
1385 res = v->ob_digit[0];
1386 break;
1387 default:
1388 sign = 1;
1389 x = 0;
1390 if (i < 0) {
1391 sign = -1;
1392 i = -(i);
1393 }
1394 while (--i >= 0) {
1395 prev = x;
1396 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1397 if ((x >> PyLong_SHIFT) != prev) {
1398 *overflow = sign;
1399 goto exit;
1400 }
1401 }
1402 /* Haven't lost any bits, but casting to long requires extra
1403 * care (see comment above).
1404 */
1405 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1406 res = (PY_LONG_LONG)x * sign;
1407 }
1408 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1409 res = PY_LLONG_MIN;
1410 }
1411 else {
1412 *overflow = sign;
1413 /* res is already set to -1 */
1414 }
1415 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001416 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001418 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 }
1420 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001421}
1422
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001423#endif /* HAVE_LONG_LONG */
1424
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001425#define CHECK_BINOP(v,w) \
1426 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001427 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1428 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001429 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001430
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001431/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1432 2**k if d is nonzero, else 0. */
1433
1434static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1436 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001437};
1438
1439static int
1440bits_in_digit(digit d)
1441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 int d_bits = 0;
1443 while (d >= 32) {
1444 d_bits += 6;
1445 d >>= 6;
1446 }
1447 d_bits += (int)BitLengthTable[d];
1448 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001449}
1450
Tim Peters877a2122002-08-12 05:09:36 +00001451/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1452 * is modified in place, by adding y to it. Carries are propagated as far as
1453 * x[m-1], and the remaining carry (0 or 1) is returned.
1454 */
1455static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001456v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 Py_ssize_t i;
1459 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 assert(m >= n);
1462 for (i = 0; i < n; ++i) {
1463 carry += x[i] + y[i];
1464 x[i] = carry & PyLong_MASK;
1465 carry >>= PyLong_SHIFT;
1466 assert((carry & 1) == carry);
1467 }
1468 for (; carry && i < m; ++i) {
1469 carry += x[i];
1470 x[i] = carry & PyLong_MASK;
1471 carry >>= PyLong_SHIFT;
1472 assert((carry & 1) == carry);
1473 }
1474 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001475}
1476
1477/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1478 * is modified in place, by subtracting y from it. Borrows are propagated as
1479 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1480 */
1481static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001482v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 Py_ssize_t i;
1485 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 assert(m >= n);
1488 for (i = 0; i < n; ++i) {
1489 borrow = x[i] - y[i] - borrow;
1490 x[i] = borrow & PyLong_MASK;
1491 borrow >>= PyLong_SHIFT;
1492 borrow &= 1; /* keep only 1 sign bit */
1493 }
1494 for (; borrow && i < m; ++i) {
1495 borrow = x[i] - borrow;
1496 x[i] = borrow & PyLong_MASK;
1497 borrow >>= PyLong_SHIFT;
1498 borrow &= 1;
1499 }
1500 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001501}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001502
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001503/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1504 * result in z[0:m], and return the d bits shifted out of the top.
1505 */
1506static digit
1507v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 Py_ssize_t i;
1510 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 assert(0 <= d && d < PyLong_SHIFT);
1513 for (i=0; i < m; i++) {
1514 twodigits acc = (twodigits)a[i] << d | carry;
1515 z[i] = (digit)acc & PyLong_MASK;
1516 carry = (digit)(acc >> PyLong_SHIFT);
1517 }
1518 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001519}
1520
1521/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1522 * result in z[0:m], and return the d bits shifted out of the bottom.
1523 */
1524static digit
1525v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 Py_ssize_t i;
1528 digit carry = 0;
1529 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 assert(0 <= d && d < PyLong_SHIFT);
1532 for (i=m; i-- > 0;) {
1533 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1534 carry = (digit)acc & mask;
1535 z[i] = (digit)(acc >> d);
1536 }
1537 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001538}
1539
Tim Peters212e6142001-07-14 12:23:19 +00001540/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1541 in pout, and returning the remainder. pin and pout point at the LSD.
1542 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001543 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001544 immutable. */
1545
1546static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001547inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 assert(n > 0 && n <= PyLong_MASK);
1552 pin += size;
1553 pout += size;
1554 while (--size >= 0) {
1555 digit hi;
1556 rem = (rem << PyLong_SHIFT) | *--pin;
1557 *--pout = hi = (digit)(rem / n);
1558 rem -= (twodigits)hi * n;
1559 }
1560 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001561}
1562
Serhiy Storchaka95949422013-08-27 19:40:23 +03001563/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001564 (as function result) and the remainder (through *prem).
1565 The sign of a is ignored; n should not be zero. */
1566
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001567static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001568divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 const Py_ssize_t size = ABS(Py_SIZE(a));
1571 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 assert(n > 0 && n <= PyLong_MASK);
1574 z = _PyLong_New(size);
1575 if (z == NULL)
1576 return NULL;
1577 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1578 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001579}
1580
Serhiy Storchaka95949422013-08-27 19:40:23 +03001581/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001582 string. (Return value is non-shared so that callers can modify the
1583 returned value if necessary.) */
1584
Victor Stinnerd3f08822012-05-29 12:57:52 +02001585static int
1586long_to_decimal_string_internal(PyObject *aa,
1587 PyObject **p_output,
1588 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 PyLongObject *scratch, *a;
1591 PyObject *str;
1592 Py_ssize_t size, strlen, size_a, i, j;
1593 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001595 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 a = (PyLongObject *)aa;
1598 if (a == NULL || !PyLong_Check(a)) {
1599 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001600 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
1602 size_a = ABS(Py_SIZE(a));
1603 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 /* quick and dirty upper bound for the number of digits
1606 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 But log2(a) < size_a * PyLong_SHIFT, and
1611 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1612 > 3 * _PyLong_DECIMAL_SHIFT
1613 */
1614 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1615 PyErr_SetString(PyExc_OverflowError,
1616 "long is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001617 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 }
1619 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1620 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1621 scratch = _PyLong_New(size);
1622 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001623 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 /* convert array of base _PyLong_BASE digits in pin to an array of
1626 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1627 Volume 2 (3rd edn), section 4.4, Method 1b). */
1628 pin = a->ob_digit;
1629 pout = scratch->ob_digit;
1630 size = 0;
1631 for (i = size_a; --i >= 0; ) {
1632 digit hi = pin[i];
1633 for (j = 0; j < size; j++) {
1634 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1635 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1636 pout[j] = (digit)(z - (twodigits)hi *
1637 _PyLong_DECIMAL_BASE);
1638 }
1639 while (hi) {
1640 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1641 hi /= _PyLong_DECIMAL_BASE;
1642 }
1643 /* check for keyboard interrupt */
1644 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001645 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001646 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001647 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 }
1649 /* pout should have at least one digit, so that the case when a = 0
1650 works correctly */
1651 if (size == 0)
1652 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* calculate exact length of output string, and allocate */
1655 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1656 tenpow = 10;
1657 rem = pout[size-1];
1658 while (rem >= tenpow) {
1659 tenpow *= 10;
1660 strlen++;
1661 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001662 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001663 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1664 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001665 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001666 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001667 kind = writer->kind;
1668 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001670 else {
1671 str = PyUnicode_New(strlen, '9');
1672 if (str == NULL) {
1673 Py_DECREF(scratch);
1674 return -1;
1675 }
1676 kind = PyUnicode_KIND(str);
1677 }
1678
1679#define WRITE_DIGITS(TYPE) \
1680 do { \
1681 if (writer) \
1682 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1683 else \
1684 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1685 \
1686 *p = '\0'; \
1687 /* pout[0] through pout[size-2] contribute exactly \
1688 _PyLong_DECIMAL_SHIFT digits each */ \
1689 for (i=0; i < size - 1; i++) { \
1690 rem = pout[i]; \
1691 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1692 *--p = '0' + rem % 10; \
1693 rem /= 10; \
1694 } \
1695 } \
1696 /* pout[size-1]: always produce at least one decimal digit */ \
1697 rem = pout[i]; \
1698 do { \
1699 *--p = '0' + rem % 10; \
1700 rem /= 10; \
1701 } while (rem != 0); \
1702 \
1703 /* and sign */ \
1704 if (negative) \
1705 *--p = '-'; \
1706 \
1707 /* check we've counted correctly */ \
1708 if (writer) \
1709 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1710 else \
1711 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1712 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001715 if (kind == PyUnicode_1BYTE_KIND) {
1716 Py_UCS1 *p;
1717 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 else if (kind == PyUnicode_2BYTE_KIND) {
1720 Py_UCS2 *p;
1721 WRITE_DIGITS(Py_UCS2);
1722 }
1723 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001724 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001725 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 WRITE_DIGITS(Py_UCS4);
1727 }
1728#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001731 if (writer) {
1732 writer->pos += strlen;
1733 }
1734 else {
1735 assert(_PyUnicode_CheckConsistency(str, 1));
1736 *p_output = (PyObject *)str;
1737 }
1738 return 0;
1739}
1740
1741static PyObject *
1742long_to_decimal_string(PyObject *aa)
1743{
1744 PyObject *v;
1745 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1746 return NULL;
1747 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001748}
1749
Serhiy Storchaka95949422013-08-27 19:40:23 +03001750/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001751 which should be one of 2, 8 or 16. Return a string object.
1752 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1753 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755static int
1756long_format_binary(PyObject *aa, int base, int alternate,
1757 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 register PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001761 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001764 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001766
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (a == NULL || !PyLong_Check(a)) {
1769 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001770 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 }
1772 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001773 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 /* Compute a rough upper bound for the length of the string */
1776 switch (base) {
1777 case 16:
1778 bits = 4;
1779 break;
1780 case 8:
1781 bits = 3;
1782 break;
1783 case 2:
1784 bits = 1;
1785 break;
1786 default:
1787 assert(0); /* shouldn't ever get here */
1788 bits = 0; /* to silence gcc warning */
1789 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001790
Mark Dickinsone2846542012-04-20 21:21:24 +01001791 /* Compute exact length 'sz' of output string. */
1792 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001793 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001794 }
1795 else {
1796 Py_ssize_t size_a_in_bits;
1797 /* Ensure overflow doesn't occur during computation of sz. */
1798 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1799 PyErr_SetString(PyExc_OverflowError,
1800 "int is too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001802 }
1803 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1804 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001805 /* Allow 1 character for a '-' sign. */
1806 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1807 }
1808 if (alternate) {
1809 /* 2 characters for prefix */
1810 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001811 }
1812
Victor Stinnerd3f08822012-05-29 12:57:52 +02001813 if (writer) {
1814 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1815 return -1;
1816 kind = writer->kind;
1817 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 }
1819 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001820 v = PyUnicode_New(sz, 'x');
1821 if (v == NULL)
1822 return -1;
1823 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001825
Victor Stinnerd3f08822012-05-29 12:57:52 +02001826#define WRITE_DIGITS(TYPE) \
1827 do { \
1828 if (writer) \
1829 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1830 else \
1831 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1832 \
1833 if (size_a == 0) { \
1834 *--p = '0'; \
1835 } \
1836 else { \
1837 /* JRH: special case for power-of-2 bases */ \
1838 twodigits accum = 0; \
1839 int accumbits = 0; /* # of bits in accum */ \
1840 Py_ssize_t i; \
1841 for (i = 0; i < size_a; ++i) { \
1842 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1843 accumbits += PyLong_SHIFT; \
1844 assert(accumbits >= bits); \
1845 do { \
1846 char cdigit; \
1847 cdigit = (char)(accum & (base - 1)); \
1848 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1849 *--p = cdigit; \
1850 accumbits -= bits; \
1851 accum >>= bits; \
1852 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1853 } \
1854 } \
1855 \
1856 if (alternate) { \
1857 if (base == 16) \
1858 *--p = 'x'; \
1859 else if (base == 8) \
1860 *--p = 'o'; \
1861 else /* (base == 2) */ \
1862 *--p = 'b'; \
1863 *--p = '0'; \
1864 } \
1865 if (negative) \
1866 *--p = '-'; \
1867 if (writer) \
1868 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1869 else \
1870 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1871 } while (0)
1872
1873 if (kind == PyUnicode_1BYTE_KIND) {
1874 Py_UCS1 *p;
1875 WRITE_DIGITS(Py_UCS1);
1876 }
1877 else if (kind == PyUnicode_2BYTE_KIND) {
1878 Py_UCS2 *p;
1879 WRITE_DIGITS(Py_UCS2);
1880 }
1881 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001882 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001883 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001884 WRITE_DIGITS(Py_UCS4);
1885 }
1886#undef WRITE_DIGITS
1887
1888 if (writer) {
1889 writer->pos += sz;
1890 }
1891 else {
1892 assert(_PyUnicode_CheckConsistency(v, 1));
1893 *p_output = v;
1894 }
1895 return 0;
1896}
1897
1898PyObject *
1899_PyLong_Format(PyObject *obj, int base)
1900{
1901 PyObject *str;
1902 int err;
1903 if (base == 10)
1904 err = long_to_decimal_string_internal(obj, &str, NULL);
1905 else
1906 err = long_format_binary(obj, base, 1, &str, NULL);
1907 if (err == -1)
1908 return NULL;
1909 return str;
1910}
1911
1912int
1913_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1914 PyObject *obj,
1915 int base, int alternate)
1916{
1917 if (base == 10)
1918 return long_to_decimal_string_internal(obj, NULL, writer);
1919 else
1920 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001921}
1922
Thomas Wouters477c8d52006-05-27 19:21:47 +00001923/* Table of digit values for 8-bit string -> integer conversion.
1924 * '0' maps to 0, ..., '9' maps to 9.
1925 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1926 * All other indices map to 37.
1927 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001928 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001930unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1935 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1936 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1937 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1938 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1939 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1940 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1941 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1942 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1943 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1944 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1945 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1946 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001947};
1948
1949/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001950 * 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 +03001951 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001952 * The point to this routine is that it takes time linear in the number of
1953 * string characters.
1954 */
1955static PyLongObject *
1956long_from_binary_base(char **str, int base)
1957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 char *p = *str;
1959 char *start = p;
1960 int bits_per_char;
1961 Py_ssize_t n;
1962 PyLongObject *z;
1963 twodigits accum;
1964 int bits_in_accum;
1965 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1968 n = base;
1969 for (bits_per_char = -1; n; ++bits_per_char)
1970 n >>= 1;
1971 /* n <- total # of bits needed, while setting p to end-of-string */
1972 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1973 ++p;
1974 *str = p;
1975 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1976 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1977 if (n / bits_per_char < p - start) {
1978 PyErr_SetString(PyExc_ValueError,
1979 "int string too large to convert");
1980 return NULL;
1981 }
1982 n = n / PyLong_SHIFT;
1983 z = _PyLong_New(n);
1984 if (z == NULL)
1985 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001986 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 * from least to most significant in both.
1988 */
1989 accum = 0;
1990 bits_in_accum = 0;
1991 pdigit = z->ob_digit;
1992 while (--p >= start) {
1993 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1994 assert(k >= 0 && k < base);
1995 accum |= (twodigits)k << bits_in_accum;
1996 bits_in_accum += bits_per_char;
1997 if (bits_in_accum >= PyLong_SHIFT) {
1998 *pdigit++ = (digit)(accum & PyLong_MASK);
1999 assert(pdigit - z->ob_digit <= n);
2000 accum >>= PyLong_SHIFT;
2001 bits_in_accum -= PyLong_SHIFT;
2002 assert(bits_in_accum < PyLong_SHIFT);
2003 }
2004 }
2005 if (bits_in_accum) {
2006 assert(bits_in_accum <= PyLong_SHIFT);
2007 *pdigit++ = (digit)accum;
2008 assert(pdigit - z->ob_digit <= n);
2009 }
2010 while (pdigit - z->ob_digit < n)
2011 *pdigit++ = 0;
2012 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002013}
2014
Serhiy Storchaka95949422013-08-27 19:40:23 +03002015/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002016 * ignored.
2017 *
2018 * If successful, a PyLong object will be returned and 'pend' will be pointing
2019 * to the first unused byte unless it's NULL.
2020 *
2021 * If unsuccessful, NULL will be returned.
2022 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002023PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002024PyLong_FromString(char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 int sign = 1, error_if_nonzero = 0;
2027 char *start, *orig_str = str;
2028 PyLongObject *z = NULL;
2029 PyObject *strobj;
2030 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if ((base != 0 && base < 2) || base > 36) {
2033 PyErr_SetString(PyExc_ValueError,
2034 "int() arg 2 must be >= 2 and <= 36");
2035 return NULL;
2036 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002037 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 str++;
2039 if (*str == '+')
2040 ++str;
2041 else if (*str == '-') {
2042 ++str;
2043 sign = -1;
2044 }
2045 if (base == 0) {
2046 if (str[0] != '0')
2047 base = 10;
2048 else if (str[1] == 'x' || str[1] == 'X')
2049 base = 16;
2050 else if (str[1] == 'o' || str[1] == 'O')
2051 base = 8;
2052 else if (str[1] == 'b' || str[1] == 'B')
2053 base = 2;
2054 else {
2055 /* "old" (C-style) octal literal, now invalid.
2056 it might still be zero though */
2057 error_if_nonzero = 1;
2058 base = 10;
2059 }
2060 }
2061 if (str[0] == '0' &&
2062 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2063 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2064 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2065 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 start = str;
2068 if ((base & (base - 1)) == 0)
2069 z = long_from_binary_base(&str, base);
2070 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071/***
2072Binary bases can be converted in time linear in the number of digits, because
2073Python's representation base is binary. Other bases (including decimal!) use
2074the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002075
Thomas Wouters477c8d52006-05-27 19:21:47 +00002076First some math: the largest integer that can be expressed in N base-B digits
2077is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2078case number of Python digits needed to hold it is the smallest integer n s.t.
2079
2080 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2081 BASE**n >= B**N [taking logs to base BASE]
2082 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2083
2084The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002085this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002086and the result is computed into it.
2087
2088The input string is actually treated as being in base base**i (i.e., i digits
2089are processed at a time), where two more static arrays hold:
2090
2091 convwidth_base[base] = the largest integer i such that base**i <= BASE
2092 convmultmax_base[base] = base ** convwidth_base[base]
2093
2094The first of these is the largest i such that i consecutive input digits
2095must fit in a single Python digit. The second is effectively the input
2096base we're really using.
2097
2098Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2099convmultmax_base[base], the result is "simply"
2100
2101 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2102
2103where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002104
2105Error analysis: as above, the number of Python digits `n` needed is worst-
2106case
2107
2108 n >= N * log(B)/log(BASE)
2109
2110where `N` is the number of input digits in base `B`. This is computed via
2111
2112 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2113
2114below. Two numeric concerns are how much space this can waste, and whether
2115the computed result can be too small. To be concrete, assume BASE = 2**15,
2116which is the default (and it's unlikely anyone changes that).
2117
2118Waste isn't a problem: provided the first input digit isn't 0, the difference
2119between the worst-case input with N digits and the smallest input with N
2120digits is about a factor of B, but B is small compared to BASE so at most
2121one allocated Python digit can remain unused on that count. If
2122N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2123and adding 1 returns a result 1 larger than necessary. However, that can't
2124happen: whenever B is a power of 2, long_from_binary_base() is called
2125instead, and it's impossible for B**i to be an integer power of 2**15 when
2126B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2127an exact integer when B is not a power of 2, since B**i has a prime factor
2128other than 2 in that case, but (2**15)**j's only prime factor is 2).
2129
2130The computed result can be too small if the true value of N*log(B)/log(BASE)
2131is a little bit larger than an exact integer, but due to roundoff errors (in
2132computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2133yields a numeric result a little less than that integer. Unfortunately, "how
2134close can a transcendental function get to an integer over some range?"
2135questions are generally theoretically intractable. Computer analysis via
2136continued fractions is practical: expand log(B)/log(BASE) via continued
2137fractions, giving a sequence i/j of "the best" rational approximations. Then
2138j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2139we can get very close to being in trouble, but very rarely. For example,
214076573 is a denominator in one of the continued-fraction approximations to
2141log(10)/log(2**15), and indeed:
2142
2143 >>> log(10)/log(2**15)*76573
2144 16958.000000654003
2145
2146is very close to an integer. If we were working with IEEE single-precision,
2147rounding errors could kill us. Finding worst cases in IEEE double-precision
2148requires better-than-double-precision log() functions, and Tim didn't bother.
2149Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002150new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002151This should happen extremely rarely, and in fact I don't have a test case
2152that triggers it(!). Instead the code was tested by artificially allocating
2153just 1 digit at the start, so that the copying code was exercised for every
2154digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002155***/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 register twodigits c; /* current input character */
2157 Py_ssize_t size_z;
2158 int i;
2159 int convwidth;
2160 twodigits convmultmax, convmult;
2161 digit *pz, *pzstop;
2162 char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 static double log_base_BASE[37] = {0.0e0,};
2165 static int convwidth_base[37] = {0,};
2166 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (log_base_BASE[base] == 0.0) {
2169 twodigits convmax = base;
2170 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002171
Mark Dickinson22b20182010-05-10 21:27:53 +00002172 log_base_BASE[base] = (log((double)base) /
2173 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 for (;;) {
2175 twodigits next = convmax * base;
2176 if (next > PyLong_BASE)
2177 break;
2178 convmax = next;
2179 ++i;
2180 }
2181 convmultmax_base[base] = convmax;
2182 assert(i > 0);
2183 convwidth_base[base] = i;
2184 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 /* Find length of the string of numeric characters. */
2187 scan = str;
2188 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2189 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002190
Serhiy Storchaka95949422013-08-27 19:40:23 +03002191 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 * integer with this base and length. Note that there's no
2193 * need to initialize z->ob_digit -- no slot is read up before
2194 * being stored into.
2195 */
2196 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2197 /* Uncomment next line to test exceedingly rare copy code */
2198 /* size_z = 1; */
2199 assert(size_z > 0);
2200 z = _PyLong_New(size_z);
2201 if (z == NULL)
2202 return NULL;
2203 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 /* `convwidth` consecutive input digits are treated as a single
2206 * digit in base `convmultmax`.
2207 */
2208 convwidth = convwidth_base[base];
2209 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 /* Work ;-) */
2212 while (str < scan) {
2213 /* grab up to convwidth digits from the input string */
2214 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2215 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2216 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002217 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 assert(c < PyLong_BASE);
2219 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 convmult = convmultmax;
2222 /* Calculate the shift only if we couldn't get
2223 * convwidth digits.
2224 */
2225 if (i != convwidth) {
2226 convmult = base;
2227 for ( ; i > 1; --i)
2228 convmult *= base;
2229 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 /* Multiply z by convmult, and add c. */
2232 pz = z->ob_digit;
2233 pzstop = pz + Py_SIZE(z);
2234 for (; pz < pzstop; ++pz) {
2235 c += (twodigits)*pz * convmult;
2236 *pz = (digit)(c & PyLong_MASK);
2237 c >>= PyLong_SHIFT;
2238 }
2239 /* carry off the current end? */
2240 if (c) {
2241 assert(c < PyLong_BASE);
2242 if (Py_SIZE(z) < size_z) {
2243 *pz = (digit)c;
2244 ++Py_SIZE(z);
2245 }
2246 else {
2247 PyLongObject *tmp;
2248 /* Extremely rare. Get more space. */
2249 assert(Py_SIZE(z) == size_z);
2250 tmp = _PyLong_New(size_z + 1);
2251 if (tmp == NULL) {
2252 Py_DECREF(z);
2253 return NULL;
2254 }
2255 memcpy(tmp->ob_digit,
2256 z->ob_digit,
2257 sizeof(digit) * size_z);
2258 Py_DECREF(z);
2259 z = tmp;
2260 z->ob_digit[size_z] = (digit)c;
2261 ++size_z;
2262 }
2263 }
2264 }
2265 }
2266 if (z == NULL)
2267 return NULL;
2268 if (error_if_nonzero) {
2269 /* reset the base to 0, else the exception message
2270 doesn't make too much sense */
2271 base = 0;
2272 if (Py_SIZE(z) != 0)
2273 goto onError;
2274 /* there might still be other problems, therefore base
2275 remains zero here for the same reason */
2276 }
2277 if (str == start)
2278 goto onError;
2279 if (sign < 0)
2280 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002281 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 str++;
2283 if (*str != '\0')
2284 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002286 z = maybe_small_long(z);
2287 if (z == NULL)
2288 return NULL;
2289 if (pend != NULL)
2290 *pend = str;
2291 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002292
Mark Dickinson22b20182010-05-10 21:27:53 +00002293 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002294 if (pend != NULL)
2295 *pend = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 Py_XDECREF(z);
2297 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2298 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2299 if (strobj == NULL)
2300 return NULL;
2301 PyErr_Format(PyExc_ValueError,
2302 "invalid literal for int() with base %d: %R",
2303 base, strobj);
2304 Py_DECREF(strobj);
2305 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002306}
2307
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002308/* Since PyLong_FromString doesn't have a length parameter,
2309 * check here for possible NULs in the string.
2310 *
2311 * Reports an invalid literal as a bytes object.
2312 */
2313PyObject *
2314_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2315{
2316 PyObject *result, *strobj;
2317 char *end = NULL;
2318
2319 result = PyLong_FromString((char*)s, &end, base);
2320 if (end == NULL || (result != NULL && end == s + len))
2321 return result;
2322 Py_XDECREF(result);
2323 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2324 if (strobj != NULL) {
2325 PyErr_Format(PyExc_ValueError,
2326 "invalid literal for int() with base %d: %R",
2327 base, strobj);
2328 Py_DECREF(strobj);
2329 }
2330 return NULL;
2331}
2332
Guido van Rossum9e896b32000-04-05 20:11:21 +00002333PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002334PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002335{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002336 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2337 if (unicode == NULL)
2338 return NULL;
2339 v = PyLong_FromUnicodeObject(unicode, base);
2340 Py_DECREF(unicode);
2341 return v;
2342}
2343
2344PyObject *
2345PyLong_FromUnicodeObject(PyObject *u, int base)
2346{
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002347 PyObject *result, *asciidig, *strobj;
2348 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002349 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002351 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002352 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002354 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002355 if (buffer == NULL) {
2356 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002357 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2358 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002360 else {
2361 result = PyLong_FromString(buffer, &end, base);
2362 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2363 Py_DECREF(asciidig);
2364 return result;
2365 }
2366 Py_DECREF(asciidig);
2367 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002368 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002369 strobj = PySequence_GetSlice(u, 0, 200);
2370 if (strobj != NULL) {
2371 PyErr_Format(PyExc_ValueError,
2372 "invalid literal for int() with base %d: %R",
2373 base, strobj);
2374 Py_DECREF(strobj);
2375 }
2376 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377}
2378
Tim Peters9f688bf2000-07-07 15:53:28 +00002379/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002380static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002382static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002383
Serhiy Storchaka95949422013-08-27 19:40:23 +03002384/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002385
Guido van Rossume32e0141992-01-19 16:31:05 +00002386static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002387long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2391 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 if (size_b == 0) {
2394 PyErr_SetString(PyExc_ZeroDivisionError,
2395 "integer division or modulo by zero");
2396 return -1;
2397 }
2398 if (size_a < size_b ||
2399 (size_a == size_b &&
2400 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2401 /* |a| < |b|. */
2402 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2403 if (*pdiv == NULL)
2404 return -1;
2405 Py_INCREF(a);
2406 *prem = (PyLongObject *) a;
2407 return 0;
2408 }
2409 if (size_b == 1) {
2410 digit rem = 0;
2411 z = divrem1(a, b->ob_digit[0], &rem);
2412 if (z == NULL)
2413 return -1;
2414 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2415 if (*prem == NULL) {
2416 Py_DECREF(z);
2417 return -1;
2418 }
2419 }
2420 else {
2421 z = x_divrem(a, b, prem);
2422 if (z == NULL)
2423 return -1;
2424 }
2425 /* Set the signs.
2426 The quotient z has the sign of a*b;
2427 the remainder r has the sign of a,
2428 so a = b*z + r. */
2429 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0))
2430 NEGATE(z);
2431 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0)
2432 NEGATE(*prem);
2433 *pdiv = maybe_small_long(z);
2434 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002435}
2436
Serhiy Storchaka95949422013-08-27 19:40:23 +03002437/* Unsigned int division with remainder -- the algorithm. The arguments v1
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002438 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002439
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002440static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002441x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 PyLongObject *v, *w, *a;
2444 Py_ssize_t i, k, size_v, size_w;
2445 int d;
2446 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2447 twodigits vv;
2448 sdigit zhi;
2449 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2452 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2453 handle the special case when the initial estimate q for a quotient
2454 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2455 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 /* allocate space; w will also be used to hold the final remainder */
2458 size_v = ABS(Py_SIZE(v1));
2459 size_w = ABS(Py_SIZE(w1));
2460 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2461 v = _PyLong_New(size_v+1);
2462 if (v == NULL) {
2463 *prem = NULL;
2464 return NULL;
2465 }
2466 w = _PyLong_New(size_w);
2467 if (w == NULL) {
2468 Py_DECREF(v);
2469 *prem = NULL;
2470 return NULL;
2471 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2474 shift v1 left by the same amount. Results go into w and v. */
2475 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2476 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2477 assert(carry == 0);
2478 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2479 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2480 v->ob_digit[size_v] = carry;
2481 size_v++;
2482 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2485 at most (and usually exactly) k = size_v - size_w digits. */
2486 k = size_v - size_w;
2487 assert(k >= 0);
2488 a = _PyLong_New(k);
2489 if (a == NULL) {
2490 Py_DECREF(w);
2491 Py_DECREF(v);
2492 *prem = NULL;
2493 return NULL;
2494 }
2495 v0 = v->ob_digit;
2496 w0 = w->ob_digit;
2497 wm1 = w0[size_w-1];
2498 wm2 = w0[size_w-2];
2499 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2500 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2501 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002504 Py_DECREF(a);
2505 Py_DECREF(w);
2506 Py_DECREF(v);
2507 *prem = NULL;
2508 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002509 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 /* estimate quotient digit q; may overestimate by 1 (rare) */
2512 vtop = vk[size_w];
2513 assert(vtop <= wm1);
2514 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2515 q = (digit)(vv / wm1);
2516 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2517 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2518 | vk[size_w-2])) {
2519 --q;
2520 r += wm1;
2521 if (r >= PyLong_BASE)
2522 break;
2523 }
2524 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2527 zhi = 0;
2528 for (i = 0; i < size_w; ++i) {
2529 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2530 -PyLong_BASE * q <= z < PyLong_BASE */
2531 z = (sdigit)vk[i] + zhi -
2532 (stwodigits)q * (stwodigits)w0[i];
2533 vk[i] = (digit)z & PyLong_MASK;
2534 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002535 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 /* add w back if q was too large (this branch taken rarely) */
2539 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2540 if ((sdigit)vtop + zhi < 0) {
2541 carry = 0;
2542 for (i = 0; i < size_w; ++i) {
2543 carry += vk[i] + w0[i];
2544 vk[i] = carry & PyLong_MASK;
2545 carry >>= PyLong_SHIFT;
2546 }
2547 --q;
2548 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 /* store quotient digit */
2551 assert(q < PyLong_BASE);
2552 *--ak = q;
2553 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 /* unshift remainder; we reuse w to store the result */
2556 carry = v_rshift(w0, v0, size_w, d);
2557 assert(carry==0);
2558 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 *prem = long_normalize(w);
2561 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002562}
2563
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002564/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2565 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2566 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2567 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2568 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2569 -1.0. */
2570
2571/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2572#if DBL_MANT_DIG == 53
2573#define EXP2_DBL_MANT_DIG 9007199254740992.0
2574#else
2575#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2576#endif
2577
2578double
2579_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2582 /* See below for why x_digits is always large enough. */
2583 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2584 double dx;
2585 /* Correction term for round-half-to-even rounding. For a digit x,
2586 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2587 multiple of 4, rounding ties to a multiple of 8. */
2588 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 a_size = ABS(Py_SIZE(a));
2591 if (a_size == 0) {
2592 /* Special case for 0: significand 0.0, exponent 0. */
2593 *e = 0;
2594 return 0.0;
2595 }
2596 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2597 /* The following is an overflow-free version of the check
2598 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2599 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2600 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2601 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002602 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2606 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 Number of digits needed for result: write // for floor division.
2609 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2618 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2621 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2622 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 in both cases.
2629 */
2630 if (a_bits <= DBL_MANT_DIG + 2) {
2631 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2632 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2633 x_size = 0;
2634 while (x_size < shift_digits)
2635 x_digits[x_size++] = 0;
2636 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2637 (int)shift_bits);
2638 x_size += a_size;
2639 x_digits[x_size++] = rem;
2640 }
2641 else {
2642 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2643 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2644 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2645 a_size - shift_digits, (int)shift_bits);
2646 x_size = a_size - shift_digits;
2647 /* For correct rounding below, we need the least significant
2648 bit of x to be 'sticky' for this shift: if any of the bits
2649 shifted out was nonzero, we set the least significant bit
2650 of x. */
2651 if (rem)
2652 x_digits[0] |= 1;
2653 else
2654 while (shift_digits > 0)
2655 if (a->ob_digit[--shift_digits]) {
2656 x_digits[0] |= 1;
2657 break;
2658 }
2659 }
Victor Stinner63941882011-09-29 00:42:28 +02002660 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 /* Round, and convert to double. */
2663 x_digits[0] += half_even_correction[x_digits[0] & 7];
2664 dx = x_digits[--x_size];
2665 while (x_size > 0)
2666 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* Rescale; make correction if result is 1.0. */
2669 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2670 if (dx == 1.0) {
2671 if (a_bits == PY_SSIZE_T_MAX)
2672 goto overflow;
2673 dx = 0.5;
2674 a_bits += 1;
2675 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 *e = a_bits;
2678 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002679
2680 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 /* exponent > PY_SSIZE_T_MAX */
2682 PyErr_SetString(PyExc_OverflowError,
2683 "huge integer: number of bits overflows a Py_ssize_t");
2684 *e = 0;
2685 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002686}
2687
Serhiy Storchaka95949422013-08-27 19:40:23 +03002688/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002689 using the round-half-to-even rule in the case of a tie. */
2690
2691double
2692PyLong_AsDouble(PyObject *v)
2693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 Py_ssize_t exponent;
2695 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002696
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002697 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 PyErr_BadInternalCall();
2699 return -1.0;
2700 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002701 if (!PyLong_Check(v)) {
2702 PyErr_SetString(PyExc_TypeError, "an integer is required");
2703 return -1.0;
2704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2706 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2707 PyErr_SetString(PyExc_OverflowError,
2708 "long int too large to convert to float");
2709 return -1.0;
2710 }
2711 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002712}
2713
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002714/* Methods */
2715
2716static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002717long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720}
2721
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002722static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002723long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 if (Py_SIZE(a) != Py_SIZE(b)) {
2728 sign = Py_SIZE(a) - Py_SIZE(b);
2729 }
2730 else {
2731 Py_ssize_t i = ABS(Py_SIZE(a));
2732 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2733 ;
2734 if (i < 0)
2735 sign = 0;
2736 else {
2737 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2738 if (Py_SIZE(a) < 0)
2739 sign = -sign;
2740 }
2741 }
2742 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002743}
2744
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002745#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002747
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002748static PyObject *
2749long_richcompare(PyObject *self, PyObject *other, int op)
2750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 int result;
2752 PyObject *v;
2753 CHECK_BINOP(self, other);
2754 if (self == other)
2755 result = 0;
2756 else
2757 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2758 /* Convert the return value to a Boolean */
2759 switch (op) {
2760 case Py_EQ:
2761 v = TEST_COND(result == 0);
2762 break;
2763 case Py_NE:
2764 v = TEST_COND(result != 0);
2765 break;
2766 case Py_LE:
2767 v = TEST_COND(result <= 0);
2768 break;
2769 case Py_GE:
2770 v = TEST_COND(result >= 0);
2771 break;
2772 case Py_LT:
2773 v = TEST_COND(result == -1);
2774 break;
2775 case Py_GT:
2776 v = TEST_COND(result == 1);
2777 break;
2778 default:
2779 PyErr_BadArgument();
2780 return NULL;
2781 }
2782 Py_INCREF(v);
2783 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002784}
2785
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002786static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002787long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002788{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002789 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 Py_ssize_t i;
2791 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 i = Py_SIZE(v);
2794 switch(i) {
2795 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2796 case 0: return 0;
2797 case 1: return v->ob_digit[0];
2798 }
2799 sign = 1;
2800 x = 0;
2801 if (i < 0) {
2802 sign = -1;
2803 i = -(i);
2804 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002806 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2807 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2808 _PyHASH_MODULUS.
2809
2810 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2811 amounts to a rotation of the bits of x. To see this, write
2812
2813 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2814
2815 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2816 PyLong_SHIFT bits of x (those that are shifted out of the
2817 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2818 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2819 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2820 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2821 congruent to y modulo _PyHASH_MODULUS. So
2822
2823 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2824
2825 The right-hand side is just the result of rotating the
2826 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2827 not all _PyHASH_BITS bits of x are 1s, the same is true
2828 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2829 the reduction of x*2**PyLong_SHIFT modulo
2830 _PyHASH_MODULUS. */
2831 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2832 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002834 if (x >= _PyHASH_MODULUS)
2835 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 }
2837 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002838 if (x == (Py_uhash_t)-1)
2839 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002840 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002841}
2842
2843
Serhiy Storchaka95949422013-08-27 19:40:23 +03002844/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002845
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002846static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002847x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2850 PyLongObject *z;
2851 Py_ssize_t i;
2852 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 /* Ensure a is the larger of the two: */
2855 if (size_a < size_b) {
2856 { PyLongObject *temp = a; a = b; b = temp; }
2857 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002858 size_a = size_b;
2859 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 }
2861 z = _PyLong_New(size_a+1);
2862 if (z == NULL)
2863 return NULL;
2864 for (i = 0; i < size_b; ++i) {
2865 carry += a->ob_digit[i] + b->ob_digit[i];
2866 z->ob_digit[i] = carry & PyLong_MASK;
2867 carry >>= PyLong_SHIFT;
2868 }
2869 for (; i < size_a; ++i) {
2870 carry += a->ob_digit[i];
2871 z->ob_digit[i] = carry & PyLong_MASK;
2872 carry >>= PyLong_SHIFT;
2873 }
2874 z->ob_digit[i] = carry;
2875 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002876}
2877
2878/* Subtract the absolute values of two integers. */
2879
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002880static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002881x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2884 PyLongObject *z;
2885 Py_ssize_t i;
2886 int sign = 1;
2887 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 /* Ensure a is the larger of the two: */
2890 if (size_a < size_b) {
2891 sign = -1;
2892 { PyLongObject *temp = a; a = b; b = temp; }
2893 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002894 size_a = size_b;
2895 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 }
2897 else if (size_a == size_b) {
2898 /* Find highest digit where a and b differ: */
2899 i = size_a;
2900 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2901 ;
2902 if (i < 0)
2903 return (PyLongObject *)PyLong_FromLong(0);
2904 if (a->ob_digit[i] < b->ob_digit[i]) {
2905 sign = -1;
2906 { PyLongObject *temp = a; a = b; b = temp; }
2907 }
2908 size_a = size_b = i+1;
2909 }
2910 z = _PyLong_New(size_a);
2911 if (z == NULL)
2912 return NULL;
2913 for (i = 0; i < size_b; ++i) {
2914 /* The following assumes unsigned arithmetic
2915 works module 2**N for some N>PyLong_SHIFT. */
2916 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2917 z->ob_digit[i] = borrow & PyLong_MASK;
2918 borrow >>= PyLong_SHIFT;
2919 borrow &= 1; /* Keep only one sign bit */
2920 }
2921 for (; i < size_a; ++i) {
2922 borrow = a->ob_digit[i] - borrow;
2923 z->ob_digit[i] = borrow & PyLong_MASK;
2924 borrow >>= PyLong_SHIFT;
2925 borrow &= 1; /* Keep only one sign bit */
2926 }
2927 assert(borrow == 0);
2928 if (sign < 0)
2929 NEGATE(z);
2930 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002931}
2932
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002933static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002934long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2941 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2942 MEDIUM_VALUE(b));
2943 return result;
2944 }
2945 if (Py_SIZE(a) < 0) {
2946 if (Py_SIZE(b) < 0) {
2947 z = x_add(a, b);
2948 if (z != NULL && Py_SIZE(z) != 0)
2949 Py_SIZE(z) = -(Py_SIZE(z));
2950 }
2951 else
2952 z = x_sub(b, a);
2953 }
2954 else {
2955 if (Py_SIZE(b) < 0)
2956 z = x_sub(a, b);
2957 else
2958 z = x_add(a, b);
2959 }
2960 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002961}
2962
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002963static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002964long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2971 PyObject* r;
2972 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2973 return r;
2974 }
2975 if (Py_SIZE(a) < 0) {
2976 if (Py_SIZE(b) < 0)
2977 z = x_sub(a, b);
2978 else
2979 z = x_add(a, b);
2980 if (z != NULL && Py_SIZE(z) != 0)
2981 Py_SIZE(z) = -(Py_SIZE(z));
2982 }
2983 else {
2984 if (Py_SIZE(b) < 0)
2985 z = x_add(a, b);
2986 else
2987 z = x_sub(a, b);
2988 }
2989 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002990}
2991
Tim Peters5af4e6c2002-08-12 02:31:19 +00002992/* Grade school multiplication, ignoring the signs.
2993 * Returns the absolute value of the product, or NULL if error.
2994 */
2995static PyLongObject *
2996x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00002997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 PyLongObject *z;
2999 Py_ssize_t size_a = ABS(Py_SIZE(a));
3000 Py_ssize_t size_b = ABS(Py_SIZE(b));
3001 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 z = _PyLong_New(size_a + size_b);
3004 if (z == NULL)
3005 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3008 if (a == b) {
3009 /* Efficient squaring per HAC, Algorithm 14.16:
3010 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3011 * Gives slightly less than a 2x speedup when a == b,
3012 * via exploiting that each entry in the multiplication
3013 * pyramid appears twice (except for the size_a squares).
3014 */
3015 for (i = 0; i < size_a; ++i) {
3016 twodigits carry;
3017 twodigits f = a->ob_digit[i];
3018 digit *pz = z->ob_digit + (i << 1);
3019 digit *pa = a->ob_digit + i + 1;
3020 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003023 Py_DECREF(z);
3024 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003025 });
Tim Peters0973b992004-08-29 22:16:50 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 carry = *pz + f * f;
3028 *pz++ = (digit)(carry & PyLong_MASK);
3029 carry >>= PyLong_SHIFT;
3030 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 /* Now f is added in twice in each column of the
3033 * pyramid it appears. Same as adding f<<1 once.
3034 */
3035 f <<= 1;
3036 while (pa < paend) {
3037 carry += *pz + *pa++ * f;
3038 *pz++ = (digit)(carry & PyLong_MASK);
3039 carry >>= PyLong_SHIFT;
3040 assert(carry <= (PyLong_MASK << 1));
3041 }
3042 if (carry) {
3043 carry += *pz;
3044 *pz++ = (digit)(carry & PyLong_MASK);
3045 carry >>= PyLong_SHIFT;
3046 }
3047 if (carry)
3048 *pz += (digit)(carry & PyLong_MASK);
3049 assert((carry >> PyLong_SHIFT) == 0);
3050 }
3051 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003052 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 for (i = 0; i < size_a; ++i) {
3054 twodigits carry = 0;
3055 twodigits f = a->ob_digit[i];
3056 digit *pz = z->ob_digit + i;
3057 digit *pb = b->ob_digit;
3058 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003061 Py_DECREF(z);
3062 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003063 });
Tim Peters0973b992004-08-29 22:16:50 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 while (pb < pbend) {
3066 carry += *pz + *pb++ * f;
3067 *pz++ = (digit)(carry & PyLong_MASK);
3068 carry >>= PyLong_SHIFT;
3069 assert(carry <= PyLong_MASK);
3070 }
3071 if (carry)
3072 *pz += (digit)(carry & PyLong_MASK);
3073 assert((carry >> PyLong_SHIFT) == 0);
3074 }
3075 }
3076 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003077}
3078
3079/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003080 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003081 split, and sets low and high such that abs(n) == (high << size) + low,
3082 viewing the shift as being by digits. The sign bit is ignored, and
3083 the return values are >= 0.
3084 Returns 0 on success, -1 on failure.
3085*/
3086static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003087kmul_split(PyLongObject *n,
3088 Py_ssize_t size,
3089 PyLongObject **high,
3090 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 PyLongObject *hi, *lo;
3093 Py_ssize_t size_lo, size_hi;
3094 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 size_lo = MIN(size_n, size);
3097 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if ((hi = _PyLong_New(size_hi)) == NULL)
3100 return -1;
3101 if ((lo = _PyLong_New(size_lo)) == NULL) {
3102 Py_DECREF(hi);
3103 return -1;
3104 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3107 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 *high = long_normalize(hi);
3110 *low = long_normalize(lo);
3111 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003112}
3113
Tim Peters60004642002-08-12 22:01:34 +00003114static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3115
Tim Peters5af4e6c2002-08-12 02:31:19 +00003116/* Karatsuba multiplication. Ignores the input signs, and returns the
3117 * absolute value of the product (or NULL if error).
3118 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3119 */
3120static PyLongObject *
3121k_mul(PyLongObject *a, PyLongObject *b)
3122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 Py_ssize_t asize = ABS(Py_SIZE(a));
3124 Py_ssize_t bsize = ABS(Py_SIZE(b));
3125 PyLongObject *ah = NULL;
3126 PyLongObject *al = NULL;
3127 PyLongObject *bh = NULL;
3128 PyLongObject *bl = NULL;
3129 PyLongObject *ret = NULL;
3130 PyLongObject *t1, *t2, *t3;
3131 Py_ssize_t shift; /* the number of digits we split off */
3132 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3135 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3136 * Then the original product is
3137 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3138 * By picking X to be a power of 2, "*X" is just shifting, and it's
3139 * been reduced to 3 multiplies on numbers half the size.
3140 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 /* We want to split based on the larger number; fiddle so that b
3143 * is largest.
3144 */
3145 if (asize > bsize) {
3146 t1 = a;
3147 a = b;
3148 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 i = asize;
3151 asize = bsize;
3152 bsize = i;
3153 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 /* Use gradeschool math when either number is too small. */
3156 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3157 if (asize <= i) {
3158 if (asize == 0)
3159 return (PyLongObject *)PyLong_FromLong(0);
3160 else
3161 return x_mul(a, b);
3162 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* If a is small compared to b, splitting on b gives a degenerate
3165 * case with ah==0, and Karatsuba may be (even much) less efficient
3166 * than "grade school" then. However, we can still win, by viewing
3167 * b as a string of "big digits", each of width a->ob_size. That
3168 * leads to a sequence of balanced calls to k_mul.
3169 */
3170 if (2 * asize <= bsize)
3171 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 /* Split a & b into hi & lo pieces. */
3174 shift = bsize >> 1;
3175 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3176 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 if (a == b) {
3179 bh = ah;
3180 bl = al;
3181 Py_INCREF(bh);
3182 Py_INCREF(bl);
3183 }
3184 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 /* The plan:
3187 * 1. Allocate result space (asize + bsize digits: that's always
3188 * enough).
3189 * 2. Compute ah*bh, and copy into result at 2*shift.
3190 * 3. Compute al*bl, and copy into result at 0. Note that this
3191 * can't overlap with #2.
3192 * 4. Subtract al*bl from the result, starting at shift. This may
3193 * underflow (borrow out of the high digit), but we don't care:
3194 * we're effectively doing unsigned arithmetic mod
3195 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3196 * borrows and carries out of the high digit can be ignored.
3197 * 5. Subtract ah*bh from the result, starting at shift.
3198 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3199 * at shift.
3200 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 /* 1. Allocate result space. */
3203 ret = _PyLong_New(asize + bsize);
3204 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003205#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 /* Fill with trash, to catch reference to uninitialized digits. */
3207 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003208#endif
Tim Peters44121a62002-08-12 06:17:58 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3211 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3212 assert(Py_SIZE(t1) >= 0);
3213 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3214 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3215 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 /* Zero-out the digits higher than the ah*bh copy. */
3218 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3219 if (i)
3220 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3221 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 /* 3. t2 <- al*bl, and copy into the low digits. */
3224 if ((t2 = k_mul(al, bl)) == NULL) {
3225 Py_DECREF(t1);
3226 goto fail;
3227 }
3228 assert(Py_SIZE(t2) >= 0);
3229 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3230 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 /* Zero out remaining digits. */
3233 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3234 if (i)
3235 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3238 * because it's fresher in cache.
3239 */
3240 i = Py_SIZE(ret) - shift; /* # digits after shift */
3241 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3242 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3245 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3248 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3249 Py_DECREF(ah);
3250 Py_DECREF(al);
3251 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (a == b) {
3254 t2 = t1;
3255 Py_INCREF(t2);
3256 }
3257 else if ((t2 = x_add(bh, bl)) == NULL) {
3258 Py_DECREF(t1);
3259 goto fail;
3260 }
3261 Py_DECREF(bh);
3262 Py_DECREF(bl);
3263 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 t3 = k_mul(t1, t2);
3266 Py_DECREF(t1);
3267 Py_DECREF(t2);
3268 if (t3 == NULL) goto fail;
3269 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 /* Add t3. It's not obvious why we can't run out of room here.
3272 * See the (*) comment after this function.
3273 */
3274 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3275 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003278
Mark Dickinson22b20182010-05-10 21:27:53 +00003279 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 Py_XDECREF(ret);
3281 Py_XDECREF(ah);
3282 Py_XDECREF(al);
3283 Py_XDECREF(bh);
3284 Py_XDECREF(bl);
3285 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003286}
3287
Tim Petersd6974a52002-08-13 20:37:51 +00003288/* (*) Why adding t3 can't "run out of room" above.
3289
Tim Petersab86c2b2002-08-15 20:06:00 +00003290Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3291to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003292
Tim Petersab86c2b2002-08-15 20:06:00 +000032931. For any integer i, i = c(i/2) + f(i/2). In particular,
3294 bsize = c(bsize/2) + f(bsize/2).
32952. shift = f(bsize/2)
32963. asize <= bsize
32974. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3298 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003299
Tim Petersab86c2b2002-08-15 20:06:00 +00003300We allocated asize + bsize result digits, and add t3 into them at an offset
3301of shift. This leaves asize+bsize-shift allocated digit positions for t3
3302to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3303asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003304
Tim Petersab86c2b2002-08-15 20:06:00 +00003305bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3306at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003307
Tim Petersab86c2b2002-08-15 20:06:00 +00003308If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3309digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3310most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003311
Tim Petersab86c2b2002-08-15 20:06:00 +00003312The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003313
Tim Petersab86c2b2002-08-15 20:06:00 +00003314 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003315
Tim Petersab86c2b2002-08-15 20:06:00 +00003316and we have asize + c(bsize/2) available digit positions. We need to show
3317this is always enough. An instance of c(bsize/2) cancels out in both, so
3318the question reduces to whether asize digits is enough to hold
3319(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3320then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3321asize 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 +00003322digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003323asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003324c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3325is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3326bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003327
Tim Peters48d52c02002-08-14 17:07:32 +00003328Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3329clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3330ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003331*/
3332
Tim Peters60004642002-08-12 22:01:34 +00003333/* b has at least twice the digits of a, and a is big enough that Karatsuba
3334 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3335 * of slices, each with a->ob_size digits, and multiply the slices by a,
3336 * one at a time. This gives k_mul balanced inputs to work with, and is
3337 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003338 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003339 * single-width slice overlap between successive partial sums).
3340 */
3341static PyLongObject *
3342k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 const Py_ssize_t asize = ABS(Py_SIZE(a));
3345 Py_ssize_t bsize = ABS(Py_SIZE(b));
3346 Py_ssize_t nbdone; /* # of b digits already multiplied */
3347 PyLongObject *ret;
3348 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 assert(asize > KARATSUBA_CUTOFF);
3351 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003353 /* Allocate result space, and zero it out. */
3354 ret = _PyLong_New(asize + bsize);
3355 if (ret == NULL)
3356 return NULL;
3357 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 /* Successive slices of b are copied into bslice. */
3360 bslice = _PyLong_New(asize);
3361 if (bslice == NULL)
3362 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 nbdone = 0;
3365 while (bsize > 0) {
3366 PyLongObject *product;
3367 const Py_ssize_t nbtouse = MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 /* Multiply the next slice of b by a. */
3370 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3371 nbtouse * sizeof(digit));
3372 Py_SIZE(bslice) = nbtouse;
3373 product = k_mul(a, bslice);
3374 if (product == NULL)
3375 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003377 /* Add into result. */
3378 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3379 product->ob_digit, Py_SIZE(product));
3380 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 bsize -= nbtouse;
3383 nbdone += nbtouse;
3384 }
Tim Peters60004642002-08-12 22:01:34 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 Py_DECREF(bslice);
3387 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003388
Mark Dickinson22b20182010-05-10 21:27:53 +00003389 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 Py_DECREF(ret);
3391 Py_XDECREF(bslice);
3392 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003393}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003394
3395static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003396long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 /* fast path for single-digit multiplication */
3403 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3404 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003405#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003407#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 /* if we don't have long long then we're almost certainly
3409 using 15-bit digits, so v will fit in a long. In the
3410 unlikely event that we're using 30-bit digits on a platform
3411 without long long, a large v will just cause us to fall
3412 through to the general multiplication code below. */
3413 if (v >= LONG_MIN && v <= LONG_MAX)
3414 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003415#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003416 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 z = k_mul(a, b);
3419 /* Negate if exactly one of the inputs is negative. */
3420 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z)
3421 NEGATE(z);
3422 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003423}
3424
Guido van Rossume32e0141992-01-19 16:31:05 +00003425/* The / and % operators are now defined in terms of divmod().
3426 The expression a mod b has the value a - b*floor(a/b).
3427 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003428 |a| by |b|, with the sign of a. This is also expressed
3429 as a - b*trunc(a/b), if trunc truncates towards zero.
3430 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 a b a rem b a mod b
3432 13 10 3 3
3433 -13 10 -3 7
3434 13 -10 3 -7
3435 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003436 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003437 have different signs. We then subtract one from the 'div'
3438 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003439
Tim Peters47e52ee2004-08-30 02:44:38 +00003440/* Compute
3441 * *pdiv, *pmod = divmod(v, w)
3442 * NULL can be passed for pdiv or pmod, in which case that part of
3443 * the result is simply thrown away. The caller owns a reference to
3444 * each of these it requests (does not pass NULL for).
3445 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003446static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003447l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 if (long_divrem(v, w, &div, &mod) < 0)
3453 return -1;
3454 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3455 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3456 PyLongObject *temp;
3457 PyLongObject *one;
3458 temp = (PyLongObject *) long_add(mod, w);
3459 Py_DECREF(mod);
3460 mod = temp;
3461 if (mod == NULL) {
3462 Py_DECREF(div);
3463 return -1;
3464 }
3465 one = (PyLongObject *) PyLong_FromLong(1L);
3466 if (one == NULL ||
3467 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3468 Py_DECREF(mod);
3469 Py_DECREF(div);
3470 Py_XDECREF(one);
3471 return -1;
3472 }
3473 Py_DECREF(one);
3474 Py_DECREF(div);
3475 div = temp;
3476 }
3477 if (pdiv != NULL)
3478 *pdiv = div;
3479 else
3480 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 if (pmod != NULL)
3483 *pmod = mod;
3484 else
3485 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003487 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003488}
3489
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003490static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003491long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003493 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 CHECK_BINOP(a, b);
3496 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3497 div = NULL;
3498 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003499}
3500
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003501/* PyLong/PyLong -> float, with correctly rounded result. */
3502
3503#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3504#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3505
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003506static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003507long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 PyLongObject *a, *b, *x;
3510 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3511 digit mask, low;
3512 int inexact, negate, a_is_small, b_is_small;
3513 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003515 CHECK_BINOP(v, w);
3516 a = (PyLongObject *)v;
3517 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 /*
3520 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3523 1. choose a suitable integer 'shift'
3524 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3525 3. adjust x for correct rounding
3526 4. convert x to a double dx with the same value
3527 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3532 returns either 0.0 or -0.0, depending on the sign of b. For a and
3533 b both nonzero, ignore signs of a and b, and add the sign back in
3534 at the end. Now write a_bits and b_bits for the bit lengths of a
3535 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3536 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3541 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3542 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3543 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 1. The integer 'shift' is chosen so that x has the right number of
3548 bits for a double, plus two or three extra bits that will be used
3549 in the rounding decisions. Writing a_bits and b_bits for the
3550 number of significant bits in a and b respectively, a
3551 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 This is fine in the usual case, but if a/b is smaller than the
3556 smallest normal float then it can lead to double rounding on an
3557 IEEE 754 platform, giving incorrectly rounded results. So we
3558 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 2. The quantity x is computed by first shifting a (left -shift bits
3563 if shift <= 0, right shift bits if shift > 0) and then dividing by
3564 b. For both the shift and the division, we keep track of whether
3565 the result is inexact, in a flag 'inexact'; this information is
3566 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 With the choice of shift above, together with our assumption that
3569 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3570 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3573 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 For float representability, we need x/2**extra_bits <
3578 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3579 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 To round, we just modify the bottom digit of x in-place; this can
3584 end up giving a digit with value > PyLONG_MASK, but that's not a
3585 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 With the original choices for shift above, extra_bits will always
3588 be 2 or 3. Then rounding under the round-half-to-even rule, we
3589 round up iff the most significant of the extra bits is 1, and
3590 either: (a) the computation of x in step 2 had an inexact result,
3591 or (b) at least one other of the extra bits is 1, or (c) the least
3592 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 4. Conversion to a double is straightforward; all floating-point
3595 operations involved in the conversion are exact, so there's no
3596 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3599 The result will always be exactly representable as a double, except
3600 in the case that it overflows. To avoid dependence on the exact
3601 behaviour of ldexp on overflow, we check for overflow before
3602 applying ldexp. The result of ldexp is adjusted for sign before
3603 returning.
3604 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 /* Reduce to case where a and b are both positive. */
3607 a_size = ABS(Py_SIZE(a));
3608 b_size = ABS(Py_SIZE(b));
3609 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3610 if (b_size == 0) {
3611 PyErr_SetString(PyExc_ZeroDivisionError,
3612 "division by zero");
3613 goto error;
3614 }
3615 if (a_size == 0)
3616 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 /* Fast path for a and b small (exactly representable in a double).
3619 Relies on floating-point division being correctly rounded; results
3620 may be subject to double rounding on x86 machines that operate with
3621 the x87 FPU set to 64-bit precision. */
3622 a_is_small = a_size <= MANT_DIG_DIGITS ||
3623 (a_size == MANT_DIG_DIGITS+1 &&
3624 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3625 b_is_small = b_size <= MANT_DIG_DIGITS ||
3626 (b_size == MANT_DIG_DIGITS+1 &&
3627 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3628 if (a_is_small && b_is_small) {
3629 double da, db;
3630 da = a->ob_digit[--a_size];
3631 while (a_size > 0)
3632 da = da * PyLong_BASE + a->ob_digit[--a_size];
3633 db = b->ob_digit[--b_size];
3634 while (b_size > 0)
3635 db = db * PyLong_BASE + b->ob_digit[--b_size];
3636 result = da / db;
3637 goto success;
3638 }
Tim Peterse2a60002001-09-04 06:17:36 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 /* Catch obvious cases of underflow and overflow */
3641 diff = a_size - b_size;
3642 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3643 /* Extreme overflow */
3644 goto overflow;
3645 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3646 /* Extreme underflow */
3647 goto underflow_or_zero;
3648 /* Next line is now safe from overflowing a Py_ssize_t */
3649 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3650 bits_in_digit(b->ob_digit[b_size - 1]);
3651 /* Now diff = a_bits - b_bits. */
3652 if (diff > DBL_MAX_EXP)
3653 goto overflow;
3654 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3655 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 /* Choose value for shift; see comments for step 1 above. */
3658 shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 /* x = abs(a * 2**-shift) */
3663 if (shift <= 0) {
3664 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3665 digit rem;
3666 /* x = a << -shift */
3667 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3668 /* In practice, it's probably impossible to end up
3669 here. Both a and b would have to be enormous,
3670 using close to SIZE_T_MAX bytes of memory each. */
3671 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003672 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 goto error;
3674 }
3675 x = _PyLong_New(a_size + shift_digits + 1);
3676 if (x == NULL)
3677 goto error;
3678 for (i = 0; i < shift_digits; i++)
3679 x->ob_digit[i] = 0;
3680 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3681 a_size, -shift % PyLong_SHIFT);
3682 x->ob_digit[a_size + shift_digits] = rem;
3683 }
3684 else {
3685 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3686 digit rem;
3687 /* x = a >> shift */
3688 assert(a_size >= shift_digits);
3689 x = _PyLong_New(a_size - shift_digits);
3690 if (x == NULL)
3691 goto error;
3692 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3693 a_size - shift_digits, shift % PyLong_SHIFT);
3694 /* set inexact if any of the bits shifted out is nonzero */
3695 if (rem)
3696 inexact = 1;
3697 while (!inexact && shift_digits > 0)
3698 if (a->ob_digit[--shift_digits])
3699 inexact = 1;
3700 }
3701 long_normalize(x);
3702 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003704 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3705 reference to x, so it's safe to modify it in-place. */
3706 if (b_size == 1) {
3707 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3708 b->ob_digit[0]);
3709 long_normalize(x);
3710 if (rem)
3711 inexact = 1;
3712 }
3713 else {
3714 PyLongObject *div, *rem;
3715 div = x_divrem(x, b, &rem);
3716 Py_DECREF(x);
3717 x = div;
3718 if (x == NULL)
3719 goto error;
3720 if (Py_SIZE(rem))
3721 inexact = 1;
3722 Py_DECREF(rem);
3723 }
3724 x_size = ABS(Py_SIZE(x));
3725 assert(x_size > 0); /* result of division is never zero */
3726 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003728 /* The number of extra bits that have to be rounded away. */
3729 extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
3730 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 /* Round by directly modifying the low digit of x. */
3733 mask = (digit)1 << (extra_bits - 1);
3734 low = x->ob_digit[0] | inexact;
3735 if (low & mask && low & (3*mask-1))
3736 low += mask;
3737 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 /* Convert x to a double dx; the conversion is exact. */
3740 dx = x->ob_digit[--x_size];
3741 while (x_size > 0)
3742 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3743 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003745 /* Check whether ldexp result will overflow a double. */
3746 if (shift + x_bits >= DBL_MAX_EXP &&
3747 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3748 goto overflow;
3749 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003750
3751 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003752 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003753
3754 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003756
3757 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 PyErr_SetString(PyExc_OverflowError,
3759 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003760 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003762}
3763
3764static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003765long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 CHECK_BINOP(a, b);
3770
3771 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3772 mod = NULL;
3773 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003774}
3775
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003776static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003777long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 PyLongObject *div, *mod;
3780 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3785 return NULL;
3786 }
3787 z = PyTuple_New(2);
3788 if (z != NULL) {
3789 PyTuple_SetItem(z, 0, (PyObject *) div);
3790 PyTuple_SetItem(z, 1, (PyObject *) mod);
3791 }
3792 else {
3793 Py_DECREF(div);
3794 Py_DECREF(mod);
3795 }
3796 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003797}
3798
Tim Peters47e52ee2004-08-30 02:44:38 +00003799/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003800static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003801long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3804 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 PyLongObject *z = NULL; /* accumulated result */
3807 Py_ssize_t i, j, k; /* counters */
3808 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 /* 5-ary values. If the exponent is large enough, table is
3811 * precomputed so that table[i] == a**i % c for i in range(32).
3812 */
3813 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3814 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 /* a, b, c = v, w, x */
3817 CHECK_BINOP(v, w);
3818 a = (PyLongObject*)v; Py_INCREF(a);
3819 b = (PyLongObject*)w; Py_INCREF(b);
3820 if (PyLong_Check(x)) {
3821 c = (PyLongObject *)x;
3822 Py_INCREF(x);
3823 }
3824 else if (x == Py_None)
3825 c = NULL;
3826 else {
3827 Py_DECREF(a);
3828 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003829 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003830 }
Tim Peters4c483c42001-09-05 06:24:58 +00003831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3833 if (c) {
3834 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003835 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 goto Error;
3837 }
3838 else {
3839 /* else return a float. This works because we know
3840 that this calls float_pow() which converts its
3841 arguments to double. */
3842 Py_DECREF(a);
3843 Py_DECREF(b);
3844 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3845 }
3846 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 if (c) {
3849 /* if modulus == 0:
3850 raise ValueError() */
3851 if (Py_SIZE(c) == 0) {
3852 PyErr_SetString(PyExc_ValueError,
3853 "pow() 3rd argument cannot be 0");
3854 goto Error;
3855 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 /* if modulus < 0:
3858 negativeOutput = True
3859 modulus = -modulus */
3860 if (Py_SIZE(c) < 0) {
3861 negativeOutput = 1;
3862 temp = (PyLongObject *)_PyLong_Copy(c);
3863 if (temp == NULL)
3864 goto Error;
3865 Py_DECREF(c);
3866 c = temp;
3867 temp = NULL;
3868 NEGATE(c);
3869 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003871 /* if modulus == 1:
3872 return 0 */
3873 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3874 z = (PyLongObject *)PyLong_FromLong(0L);
3875 goto Done;
3876 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003877
Tim Peters81a93152013-10-05 16:53:52 -05003878 /* Reduce base by modulus in some cases:
3879 1. If base < 0. Forcing the base non-negative makes things easier.
3880 2. If base is obviously larger than the modulus. The "small
3881 exponent" case later can multiply directly by base repeatedly,
3882 while the "large exponent" case multiplies directly by base 31
3883 times. It can be unboundedly faster to multiply by
3884 base % modulus instead.
3885 We could _always_ do this reduction, but l_divmod() isn't cheap,
3886 so we only do it when it buys something. */
3887 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003888 if (l_divmod(a, c, NULL, &temp) < 0)
3889 goto Error;
3890 Py_DECREF(a);
3891 a = temp;
3892 temp = NULL;
3893 }
3894 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003896 /* At this point a, b, and c are guaranteed non-negative UNLESS
3897 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 z = (PyLongObject *)PyLong_FromLong(1L);
3900 if (z == NULL)
3901 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003903 /* Perform a modular reduction, X = X % c, but leave X alone if c
3904 * is NULL.
3905 */
3906#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003907 do { \
3908 if (c != NULL) { \
3909 if (l_divmod(X, c, NULL, &temp) < 0) \
3910 goto Error; \
3911 Py_XDECREF(X); \
3912 X = temp; \
3913 temp = NULL; \
3914 } \
3915 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 /* Multiply two values, then reduce the result:
3918 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003919#define MULT(X, Y, result) \
3920 do { \
3921 temp = (PyLongObject *)long_mul(X, Y); \
3922 if (temp == NULL) \
3923 goto Error; \
3924 Py_XDECREF(result); \
3925 result = temp; \
3926 temp = NULL; \
3927 REDUCE(result); \
3928 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3931 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3932 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3933 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3934 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003937 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003938 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003939 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 }
3941 }
3942 }
3943 else {
3944 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3945 Py_INCREF(z); /* still holds 1L */
3946 table[0] = z;
3947 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003948 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3951 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003953 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3954 const int index = (bi >> j) & 0x1f;
3955 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003956 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003958 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 }
3960 }
3961 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 if (negativeOutput && (Py_SIZE(z) != 0)) {
3964 temp = (PyLongObject *)long_sub(z, c);
3965 if (temp == NULL)
3966 goto Error;
3967 Py_DECREF(z);
3968 z = temp;
3969 temp = NULL;
3970 }
3971 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003972
Mark Dickinson22b20182010-05-10 21:27:53 +00003973 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 if (z != NULL) {
3975 Py_DECREF(z);
3976 z = NULL;
3977 }
3978 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003979 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3981 for (i = 0; i < 32; ++i)
3982 Py_XDECREF(table[i]);
3983 }
3984 Py_DECREF(a);
3985 Py_DECREF(b);
3986 Py_XDECREF(c);
3987 Py_XDECREF(temp);
3988 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003989}
3990
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003991static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003992long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 /* Implement ~x as -(x+1) */
3995 PyLongObject *x;
3996 PyLongObject *w;
3997 if (ABS(Py_SIZE(v)) <=1)
3998 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
3999 w = (PyLongObject *)PyLong_FromLong(1L);
4000 if (w == NULL)
4001 return NULL;
4002 x = (PyLongObject *) long_add(v, w);
4003 Py_DECREF(w);
4004 if (x == NULL)
4005 return NULL;
4006 Py_SIZE(x) = -(Py_SIZE(x));
4007 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004008}
4009
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004010static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004011long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004013 PyLongObject *z;
4014 if (ABS(Py_SIZE(v)) <= 1)
4015 return PyLong_FromLong(-MEDIUM_VALUE(v));
4016 z = (PyLongObject *)_PyLong_Copy(v);
4017 if (z != NULL)
4018 Py_SIZE(z) = -(Py_SIZE(v));
4019 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004020}
4021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004022static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004023long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 if (Py_SIZE(v) < 0)
4026 return long_neg(v);
4027 else
4028 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004029}
4030
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004031static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004032long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004035}
4036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004037static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004038long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004040 PyLongObject *z = NULL;
4041 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4042 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004044 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004046 if (Py_SIZE(a) < 0) {
4047 /* Right shifting negative numbers is harder */
4048 PyLongObject *a1, *a2;
4049 a1 = (PyLongObject *) long_invert(a);
4050 if (a1 == NULL)
4051 goto rshift_error;
4052 a2 = (PyLongObject *) long_rshift(a1, b);
4053 Py_DECREF(a1);
4054 if (a2 == NULL)
4055 goto rshift_error;
4056 z = (PyLongObject *) long_invert(a2);
4057 Py_DECREF(a2);
4058 }
4059 else {
4060 shiftby = PyLong_AsSsize_t((PyObject *)b);
4061 if (shiftby == -1L && PyErr_Occurred())
4062 goto rshift_error;
4063 if (shiftby < 0) {
4064 PyErr_SetString(PyExc_ValueError,
4065 "negative shift count");
4066 goto rshift_error;
4067 }
4068 wordshift = shiftby / PyLong_SHIFT;
4069 newsize = ABS(Py_SIZE(a)) - wordshift;
4070 if (newsize <= 0)
4071 return PyLong_FromLong(0);
4072 loshift = shiftby % PyLong_SHIFT;
4073 hishift = PyLong_SHIFT - loshift;
4074 lomask = ((digit)1 << hishift) - 1;
4075 himask = PyLong_MASK ^ lomask;
4076 z = _PyLong_New(newsize);
4077 if (z == NULL)
4078 goto rshift_error;
4079 if (Py_SIZE(a) < 0)
4080 Py_SIZE(z) = -(Py_SIZE(z));
4081 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4082 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4083 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004084 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004085 }
4086 z = long_normalize(z);
4087 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004088 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004089 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004090
Guido van Rossumc6913e71991-11-19 20:26:46 +00004091}
4092
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004093static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004094long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 /* This version due to Tim Peters */
4097 PyLongObject *a = (PyLongObject*)v;
4098 PyLongObject *b = (PyLongObject*)w;
4099 PyLongObject *z = NULL;
4100 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4101 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 shiftby = PyLong_AsSsize_t((PyObject *)b);
4106 if (shiftby == -1L && PyErr_Occurred())
4107 goto lshift_error;
4108 if (shiftby < 0) {
4109 PyErr_SetString(PyExc_ValueError, "negative shift count");
4110 goto lshift_error;
4111 }
4112 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4113 wordshift = shiftby / PyLong_SHIFT;
4114 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 oldsize = ABS(Py_SIZE(a));
4117 newsize = oldsize + wordshift;
4118 if (remshift)
4119 ++newsize;
4120 z = _PyLong_New(newsize);
4121 if (z == NULL)
4122 goto lshift_error;
4123 if (Py_SIZE(a) < 0)
4124 NEGATE(z);
4125 for (i = 0; i < wordshift; i++)
4126 z->ob_digit[i] = 0;
4127 accum = 0;
4128 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4129 accum |= (twodigits)a->ob_digit[j] << remshift;
4130 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4131 accum >>= PyLong_SHIFT;
4132 }
4133 if (remshift)
4134 z->ob_digit[newsize-1] = (digit)accum;
4135 else
4136 assert(!accum);
4137 z = long_normalize(z);
Mark Dickinson22b20182010-05-10 21:27:53 +00004138 lshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004139 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004140}
4141
Mark Dickinson27a87a22009-10-25 20:43:34 +00004142/* Compute two's complement of digit vector a[0:m], writing result to
4143 z[0:m]. The digit vector a need not be normalized, but should not
4144 be entirely zero. a and z may point to the same digit vector. */
4145
4146static void
4147v_complement(digit *z, digit *a, Py_ssize_t m)
4148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 Py_ssize_t i;
4150 digit carry = 1;
4151 for (i = 0; i < m; ++i) {
4152 carry += a[i] ^ PyLong_MASK;
4153 z[i] = carry & PyLong_MASK;
4154 carry >>= PyLong_SHIFT;
4155 }
4156 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004157}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004158
4159/* Bitwise and/xor/or operations */
4160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004161static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004162long_bitwise(PyLongObject *a,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004163 int op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004164 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004166 int nega, negb, negz;
4167 Py_ssize_t size_a, size_b, size_z, i;
4168 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004170 /* Bitwise operations for negative numbers operate as though
4171 on a two's complement representation. So convert arguments
4172 from sign-magnitude to two's complement, and convert the
4173 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 /* If a is negative, replace it by its two's complement. */
4176 size_a = ABS(Py_SIZE(a));
4177 nega = Py_SIZE(a) < 0;
4178 if (nega) {
4179 z = _PyLong_New(size_a);
4180 if (z == NULL)
4181 return NULL;
4182 v_complement(z->ob_digit, a->ob_digit, size_a);
4183 a = z;
4184 }
4185 else
4186 /* Keep reference count consistent. */
4187 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004189 /* Same for b. */
4190 size_b = ABS(Py_SIZE(b));
4191 negb = Py_SIZE(b) < 0;
4192 if (negb) {
4193 z = _PyLong_New(size_b);
4194 if (z == NULL) {
4195 Py_DECREF(a);
4196 return NULL;
4197 }
4198 v_complement(z->ob_digit, b->ob_digit, size_b);
4199 b = z;
4200 }
4201 else
4202 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004204 /* Swap a and b if necessary to ensure size_a >= size_b. */
4205 if (size_a < size_b) {
4206 z = a; a = b; b = z;
4207 size_z = size_a; size_a = size_b; size_b = size_z;
4208 negz = nega; nega = negb; negb = negz;
4209 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 /* JRH: The original logic here was to allocate the result value (z)
4212 as the longer of the two operands. However, there are some cases
4213 where the result is guaranteed to be shorter than that: AND of two
4214 positives, OR of two negatives: use the shorter number. AND with
4215 mixed signs: use the positive number. OR with mixed signs: use the
4216 negative number.
4217 */
4218 switch (op) {
4219 case '^':
4220 negz = nega ^ negb;
4221 size_z = size_a;
4222 break;
4223 case '&':
4224 negz = nega & negb;
4225 size_z = negb ? size_a : size_b;
4226 break;
4227 case '|':
4228 negz = nega | negb;
4229 size_z = negb ? size_b : size_a;
4230 break;
4231 default:
4232 PyErr_BadArgument();
4233 return NULL;
4234 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004236 /* We allow an extra digit if z is negative, to make sure that
4237 the final two's complement of z doesn't overflow. */
4238 z = _PyLong_New(size_z + negz);
4239 if (z == NULL) {
4240 Py_DECREF(a);
4241 Py_DECREF(b);
4242 return NULL;
4243 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 /* Compute digits for overlap of a and b. */
4246 switch(op) {
4247 case '&':
4248 for (i = 0; i < size_b; ++i)
4249 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4250 break;
4251 case '|':
4252 for (i = 0; i < size_b; ++i)
4253 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4254 break;
4255 case '^':
4256 for (i = 0; i < size_b; ++i)
4257 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4258 break;
4259 default:
4260 PyErr_BadArgument();
4261 return NULL;
4262 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004264 /* Copy any remaining digits of a, inverting if necessary. */
4265 if (op == '^' && negb)
4266 for (; i < size_z; ++i)
4267 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4268 else if (i < size_z)
4269 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4270 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 /* Complement result if negative. */
4273 if (negz) {
4274 Py_SIZE(z) = -(Py_SIZE(z));
4275 z->ob_digit[size_z] = PyLong_MASK;
4276 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4277 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004279 Py_DECREF(a);
4280 Py_DECREF(b);
4281 return (PyObject *)maybe_small_long(long_normalize(z));
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_and(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_xor(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 Rossumc6913e71991-11-19 20:26:46 +00004300}
4301
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004302static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004303long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 PyObject *c;
4306 CHECK_BINOP(a, b);
4307 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4308 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004309}
4310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004311static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004312long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 if (PyLong_CheckExact(v))
4315 Py_INCREF(v);
4316 else
4317 v = _PyLong_Copy((PyLongObject *)v);
4318 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004319}
4320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004321static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004322long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 double result;
4325 result = PyLong_AsDouble(v);
4326 if (result == -1.0 && PyErr_Occurred())
4327 return NULL;
4328 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004329}
4330
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004331static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004332long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004333
Tim Peters6d6c1a32001-08-02 04:15:00 +00004334static PyObject *
4335long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4336{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004337 PyObject *obase = NULL, *x = NULL;
4338 long base;
4339 int overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 if (type != &PyLong_Type)
4343 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004344 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4345 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004347 if (x == NULL) {
4348 if (obase != NULL) {
4349 PyErr_SetString(PyExc_TypeError,
4350 "int() missing string argument");
4351 return NULL;
4352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004354 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004355 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004357
4358 base = PyLong_AsLongAndOverflow(obase, &overflow);
4359 if (base == -1 && PyErr_Occurred())
4360 return NULL;
4361 if (overflow || (base != 0 && base < 2) || base > 36) {
4362 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004363 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004364 return NULL;
4365 }
4366
4367 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004368 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004369 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 if (PyByteArray_Check(x))
4372 string = PyByteArray_AS_STRING(x);
4373 else
4374 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004375 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 }
4377 else {
4378 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004379 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 return NULL;
4381 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004382}
4383
Serhiy Storchaka95949422013-08-27 19:40:23 +03004384/* Wimpy, slow approach to tp_new calls for subtypes of int:
4385 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004386 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004387 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004388*/
4389static PyObject *
4390long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 PyLongObject *tmp, *newobj;
4393 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 assert(PyType_IsSubtype(type, &PyLong_Type));
4396 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4397 if (tmp == NULL)
4398 return NULL;
4399 assert(PyLong_CheckExact(tmp));
4400 n = Py_SIZE(tmp);
4401 if (n < 0)
4402 n = -n;
4403 newobj = (PyLongObject *)type->tp_alloc(type, n);
4404 if (newobj == NULL) {
4405 Py_DECREF(tmp);
4406 return NULL;
4407 }
4408 assert(PyLong_Check(newobj));
4409 Py_SIZE(newobj) = Py_SIZE(tmp);
4410 for (i = 0; i < n; i++)
4411 newobj->ob_digit[i] = tmp->ob_digit[i];
4412 Py_DECREF(tmp);
4413 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004414}
4415
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004416static PyObject *
4417long_getnewargs(PyLongObject *v)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004420}
4421
Guido van Rossumb43daf72007-08-01 18:08:08 +00004422static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004423long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004425}
4426
4427static PyObject *
4428long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004430}
4431
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004432static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004433long__format__(PyObject *self, PyObject *args)
4434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004436 _PyUnicodeWriter writer;
4437 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4440 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004441
4442 _PyUnicodeWriter_Init(&writer, 0);
4443 ret = _PyLong_FormatAdvancedWriter(
4444 &writer,
4445 self,
4446 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4447 if (ret == -1) {
4448 _PyUnicodeWriter_Dealloc(&writer);
4449 return NULL;
4450 }
4451 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004452}
4453
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004454/* Return a pair (q, r) such that a = b * q + r, and
4455 abs(r) <= abs(b)/2, with equality possible only if q is even.
4456 In other words, q == a / b, rounded to the nearest integer using
4457 round-half-to-even. */
4458
4459PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004460_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004461{
4462 PyLongObject *quo = NULL, *rem = NULL;
4463 PyObject *one = NULL, *twice_rem, *result, *temp;
4464 int cmp, quo_is_odd, quo_is_neg;
4465
4466 /* Equivalent Python code:
4467
4468 def divmod_near(a, b):
4469 q, r = divmod(a, b)
4470 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4471 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4472 # positive, 2 * r < b if b negative.
4473 greater_than_half = 2*r > b if b > 0 else 2*r < b
4474 exactly_half = 2*r == b
4475 if greater_than_half or exactly_half and q % 2 == 1:
4476 q += 1
4477 r -= b
4478 return q, r
4479
4480 */
4481 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4482 PyErr_SetString(PyExc_TypeError,
4483 "non-integer arguments in division");
4484 return NULL;
4485 }
4486
4487 /* Do a and b have different signs? If so, quotient is negative. */
4488 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4489
4490 one = PyLong_FromLong(1L);
4491 if (one == NULL)
4492 return NULL;
4493
4494 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4495 goto error;
4496
4497 /* compare twice the remainder with the divisor, to see
4498 if we need to adjust the quotient and remainder */
4499 twice_rem = long_lshift((PyObject *)rem, one);
4500 if (twice_rem == NULL)
4501 goto error;
4502 if (quo_is_neg) {
4503 temp = long_neg((PyLongObject*)twice_rem);
4504 Py_DECREF(twice_rem);
4505 twice_rem = temp;
4506 if (twice_rem == NULL)
4507 goto error;
4508 }
4509 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4510 Py_DECREF(twice_rem);
4511
4512 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4513 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4514 /* fix up quotient */
4515 if (quo_is_neg)
4516 temp = long_sub(quo, (PyLongObject *)one);
4517 else
4518 temp = long_add(quo, (PyLongObject *)one);
4519 Py_DECREF(quo);
4520 quo = (PyLongObject *)temp;
4521 if (quo == NULL)
4522 goto error;
4523 /* and remainder */
4524 if (quo_is_neg)
4525 temp = long_add(rem, (PyLongObject *)b);
4526 else
4527 temp = long_sub(rem, (PyLongObject *)b);
4528 Py_DECREF(rem);
4529 rem = (PyLongObject *)temp;
4530 if (rem == NULL)
4531 goto error;
4532 }
4533
4534 result = PyTuple_New(2);
4535 if (result == NULL)
4536 goto error;
4537
4538 /* PyTuple_SET_ITEM steals references */
4539 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4540 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4541 Py_DECREF(one);
4542 return result;
4543
4544 error:
4545 Py_XDECREF(quo);
4546 Py_XDECREF(rem);
4547 Py_XDECREF(one);
4548 return NULL;
4549}
4550
Eric Smith8c663262007-08-25 02:26:07 +00004551static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004552long_round(PyObject *self, PyObject *args)
4553{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004554 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004555
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004556 /* To round an integer m to the nearest 10**n (n positive), we make use of
4557 * the divmod_near operation, defined by:
4558 *
4559 * divmod_near(a, b) = (q, r)
4560 *
4561 * where q is the nearest integer to the quotient a / b (the
4562 * nearest even integer in the case of a tie) and r == a - q * b.
4563 * Hence q * b = a - r is the nearest multiple of b to a,
4564 * preferring even multiples in the case of a tie.
4565 *
4566 * So the nearest multiple of 10**n to m is:
4567 *
4568 * m - divmod_near(m, 10**n)[1].
4569 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004570 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4571 return NULL;
4572 if (o_ndigits == NULL)
4573 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004574
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004575 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 if (ndigits == NULL)
4577 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004578
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004579 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004580 if (Py_SIZE(ndigits) >= 0) {
4581 Py_DECREF(ndigits);
4582 return long_long(self);
4583 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004584
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004585 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4586 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004588 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004590 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004591
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004592 result = PyLong_FromLong(10L);
4593 if (result == NULL) {
4594 Py_DECREF(ndigits);
4595 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004597
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004598 temp = long_pow(result, ndigits, Py_None);
4599 Py_DECREF(ndigits);
4600 Py_DECREF(result);
4601 result = temp;
4602 if (result == NULL)
4603 return NULL;
4604
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004605 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004606 Py_DECREF(result);
4607 result = temp;
4608 if (result == NULL)
4609 return NULL;
4610
4611 temp = long_sub((PyLongObject *)self,
4612 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4613 Py_DECREF(result);
4614 result = temp;
4615
4616 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004617}
4618
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004619static PyObject *
4620long_sizeof(PyLongObject *v)
4621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004624 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4625 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004626}
4627
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004628static PyObject *
4629long_bit_length(PyLongObject *v)
4630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 PyLongObject *result, *x, *y;
4632 Py_ssize_t ndigits, msd_bits = 0;
4633 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 assert(v != NULL);
4636 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 ndigits = ABS(Py_SIZE(v));
4639 if (ndigits == 0)
4640 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 msd = v->ob_digit[ndigits-1];
4643 while (msd >= 32) {
4644 msd_bits += 6;
4645 msd >>= 6;
4646 }
4647 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4650 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 /* expression above may overflow; use Python integers instead */
4653 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4654 if (result == NULL)
4655 return NULL;
4656 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4657 if (x == NULL)
4658 goto error;
4659 y = (PyLongObject *)long_mul(result, x);
4660 Py_DECREF(x);
4661 if (y == NULL)
4662 goto error;
4663 Py_DECREF(result);
4664 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4667 if (x == NULL)
4668 goto error;
4669 y = (PyLongObject *)long_add(result, x);
4670 Py_DECREF(x);
4671 if (y == NULL)
4672 goto error;
4673 Py_DECREF(result);
4674 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004677
Mark Dickinson22b20182010-05-10 21:27:53 +00004678 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004679 Py_DECREF(result);
4680 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004681}
4682
4683PyDoc_STRVAR(long_bit_length_doc,
4684"int.bit_length() -> int\n\
4685\n\
4686Number of bits necessary to represent self in binary.\n\
4687>>> bin(37)\n\
4688'0b100101'\n\
4689>>> (37).bit_length()\n\
46906");
4691
Christian Heimes53876d92008-04-19 00:31:39 +00004692#if 0
4693static PyObject *
4694long_is_finite(PyObject *v)
4695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004697}
4698#endif
4699
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004700
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004701static PyObject *
4702long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 PyObject *byteorder_str;
4705 PyObject *is_signed_obj = NULL;
4706 Py_ssize_t length;
4707 int little_endian;
4708 int is_signed;
4709 PyObject *bytes;
4710 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4713 &length, &byteorder_str,
4714 &is_signed_obj))
4715 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (args != NULL && Py_SIZE(args) > 2) {
4718 PyErr_SetString(PyExc_TypeError,
4719 "'signed' is a keyword-only argument");
4720 return NULL;
4721 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4724 little_endian = 1;
4725 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4726 little_endian = 0;
4727 else {
4728 PyErr_SetString(PyExc_ValueError,
4729 "byteorder must be either 'little' or 'big'");
4730 return NULL;
4731 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 if (is_signed_obj != NULL) {
4734 int cmp = PyObject_IsTrue(is_signed_obj);
4735 if (cmp < 0)
4736 return NULL;
4737 is_signed = cmp ? 1 : 0;
4738 }
4739 else {
4740 /* If the signed argument was omitted, use False as the
4741 default. */
4742 is_signed = 0;
4743 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004745 if (length < 0) {
4746 PyErr_SetString(PyExc_ValueError,
4747 "length argument must be non-negative");
4748 return NULL;
4749 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 bytes = PyBytes_FromStringAndSize(NULL, length);
4752 if (bytes == NULL)
4753 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004755 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4756 length, little_endian, is_signed) < 0) {
4757 Py_DECREF(bytes);
4758 return NULL;
4759 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004761 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004762}
4763
Mark Dickinson078c2532010-01-30 18:06:17 +00004764PyDoc_STRVAR(long_to_bytes_doc,
4765"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004766\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004767Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004768\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004770raised if the integer is not representable with the given number of\n\
4771bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004772\n\
4773The byteorder argument determines the byte order used to represent the\n\
4774integer. If byteorder is 'big', the most significant byte is at the\n\
4775beginning of the byte array. If byteorder is 'little', the most\n\
4776significant byte is at the end of the byte array. To request the native\n\
4777byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4778\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004779The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004781is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004782
4783static PyObject *
4784long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004786 PyObject *byteorder_str;
4787 PyObject *is_signed_obj = NULL;
4788 int little_endian;
4789 int is_signed;
4790 PyObject *obj;
4791 PyObject *bytes;
4792 PyObject *long_obj;
4793 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4796 &obj, &byteorder_str,
4797 &is_signed_obj))
4798 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 if (args != NULL && Py_SIZE(args) > 2) {
4801 PyErr_SetString(PyExc_TypeError,
4802 "'signed' is a keyword-only argument");
4803 return NULL;
4804 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004806 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4807 little_endian = 1;
4808 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4809 little_endian = 0;
4810 else {
4811 PyErr_SetString(PyExc_ValueError,
4812 "byteorder must be either 'little' or 'big'");
4813 return NULL;
4814 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004816 if (is_signed_obj != NULL) {
4817 int cmp = PyObject_IsTrue(is_signed_obj);
4818 if (cmp < 0)
4819 return NULL;
4820 is_signed = cmp ? 1 : 0;
4821 }
4822 else {
4823 /* If the signed argument was omitted, use False as the
4824 default. */
4825 is_signed = 0;
4826 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004828 bytes = PyObject_Bytes(obj);
4829 if (bytes == NULL)
4830 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004832 long_obj = _PyLong_FromByteArray(
4833 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4834 little_endian, is_signed);
4835 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004838 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 */
4840 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4841 PyLongObject *newobj;
4842 int i;
4843 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 newobj = (PyLongObject *)type->tp_alloc(type, n);
4846 if (newobj == NULL) {
4847 Py_DECREF(long_obj);
4848 return NULL;
4849 }
4850 assert(PyLong_Check(newobj));
4851 Py_SIZE(newobj) = Py_SIZE(long_obj);
4852 for (i = 0; i < n; i++) {
4853 newobj->ob_digit[i] =
4854 ((PyLongObject *)long_obj)->ob_digit[i];
4855 }
4856 Py_DECREF(long_obj);
4857 return (PyObject *)newobj;
4858 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004861}
4862
Mark Dickinson078c2532010-01-30 18:06:17 +00004863PyDoc_STRVAR(long_from_bytes_doc,
4864"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4865\n\
4866Return the integer represented by the given array of bytes.\n\
4867\n\
4868The bytes argument must either support the buffer protocol or be an\n\
4869iterable object producing bytes. Bytes and bytearray are examples of\n\
4870built-in objects that support the buffer protocol.\n\
4871\n\
4872The byteorder argument determines the byte order used to represent the\n\
4873integer. If byteorder is 'big', the most significant byte is at the\n\
4874beginning of the byte array. If byteorder is 'little', the most\n\
4875significant byte is at the end of the byte array. To request the native\n\
4876byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4877\n\
4878The signed keyword-only argument indicates whether two's complement is\n\
4879used to represent the integer.");
4880
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004881static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004882 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4883 "Returns self, the complex conjugate of any int."},
4884 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4885 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004886#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004887 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4888 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004889#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004890 {"to_bytes", (PyCFunction)long_to_bytes,
4891 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4892 {"from_bytes", (PyCFunction)long_from_bytes,
4893 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4894 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4895 "Truncating an Integral returns itself."},
4896 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4897 "Flooring an Integral returns itself."},
4898 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4899 "Ceiling of an Integral returns itself."},
4900 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4901 "Rounding an Integral returns itself.\n"
4902 "Rounding with an ndigits argument also returns an integer."},
4903 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4904 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4905 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4906 "Returns size in memory, in bytes"},
4907 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004908};
4909
Guido van Rossumb43daf72007-08-01 18:08:08 +00004910static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004911 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004912 (getter)long_long, (setter)NULL,
4913 "the real part of a complex number",
4914 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004915 {"imag",
4916 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004917 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004918 NULL},
4919 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004920 (getter)long_long, (setter)NULL,
4921 "the numerator of a rational number in lowest terms",
4922 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004923 {"denominator",
4924 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004925 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004926 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004927 {NULL} /* Sentinel */
4928};
4929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004930PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004931"int(x=0) -> integer\n\
4932int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004933\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004934Convert a number or string to an integer, or return 0 if no arguments\n\
4935are given. If x is a number, return x.__int__(). For floating point\n\
4936numbers, this truncates towards zero.\n\
4937\n\
4938If x is not a number or if base is given, then x must be a string,\n\
4939bytes, or bytearray instance representing an integer literal in the\n\
4940given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4941by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4942Base 0 means to interpret the base from the string as an integer literal.\n\
4943>>> int('0b100', base=0)\n\
49444");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004945
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004946static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004947 (binaryfunc)long_add, /*nb_add*/
4948 (binaryfunc)long_sub, /*nb_subtract*/
4949 (binaryfunc)long_mul, /*nb_multiply*/
4950 long_mod, /*nb_remainder*/
4951 long_divmod, /*nb_divmod*/
4952 long_pow, /*nb_power*/
4953 (unaryfunc)long_neg, /*nb_negative*/
4954 (unaryfunc)long_long, /*tp_positive*/
4955 (unaryfunc)long_abs, /*tp_absolute*/
4956 (inquiry)long_bool, /*tp_bool*/
4957 (unaryfunc)long_invert, /*nb_invert*/
4958 long_lshift, /*nb_lshift*/
4959 (binaryfunc)long_rshift, /*nb_rshift*/
4960 long_and, /*nb_and*/
4961 long_xor, /*nb_xor*/
4962 long_or, /*nb_or*/
4963 long_long, /*nb_int*/
4964 0, /*nb_reserved*/
4965 long_float, /*nb_float*/
4966 0, /* nb_inplace_add */
4967 0, /* nb_inplace_subtract */
4968 0, /* nb_inplace_multiply */
4969 0, /* nb_inplace_remainder */
4970 0, /* nb_inplace_power */
4971 0, /* nb_inplace_lshift */
4972 0, /* nb_inplace_rshift */
4973 0, /* nb_inplace_and */
4974 0, /* nb_inplace_xor */
4975 0, /* nb_inplace_or */
4976 long_div, /* nb_floor_divide */
4977 long_true_divide, /* nb_true_divide */
4978 0, /* nb_inplace_floor_divide */
4979 0, /* nb_inplace_true_divide */
4980 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004981};
4982
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004983PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004984 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4985 "int", /* tp_name */
4986 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4987 sizeof(digit), /* tp_itemsize */
4988 long_dealloc, /* tp_dealloc */
4989 0, /* tp_print */
4990 0, /* tp_getattr */
4991 0, /* tp_setattr */
4992 0, /* tp_reserved */
4993 long_to_decimal_string, /* tp_repr */
4994 &long_as_number, /* tp_as_number */
4995 0, /* tp_as_sequence */
4996 0, /* tp_as_mapping */
4997 (hashfunc)long_hash, /* tp_hash */
4998 0, /* tp_call */
4999 long_to_decimal_string, /* tp_str */
5000 PyObject_GenericGetAttr, /* tp_getattro */
5001 0, /* tp_setattro */
5002 0, /* tp_as_buffer */
5003 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5004 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5005 long_doc, /* tp_doc */
5006 0, /* tp_traverse */
5007 0, /* tp_clear */
5008 long_richcompare, /* tp_richcompare */
5009 0, /* tp_weaklistoffset */
5010 0, /* tp_iter */
5011 0, /* tp_iternext */
5012 long_methods, /* tp_methods */
5013 0, /* tp_members */
5014 long_getset, /* tp_getset */
5015 0, /* tp_base */
5016 0, /* tp_dict */
5017 0, /* tp_descr_get */
5018 0, /* tp_descr_set */
5019 0, /* tp_dictoffset */
5020 0, /* tp_init */
5021 0, /* tp_alloc */
5022 long_new, /* tp_new */
5023 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005024};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005025
Mark Dickinsonbd792642009-03-18 20:06:12 +00005026static PyTypeObject Int_InfoType;
5027
5028PyDoc_STRVAR(int_info__doc__,
5029"sys.int_info\n\
5030\n\
5031A struct sequence that holds information about Python's\n\
5032internal representation of integers. The attributes are read only.");
5033
5034static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005036 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005037 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005038};
5039
5040static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 "sys.int_info", /* name */
5042 int_info__doc__, /* doc */
5043 int_info_fields, /* fields */
5044 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005045};
5046
5047PyObject *
5048PyLong_GetInfo(void)
5049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 PyObject* int_info;
5051 int field = 0;
5052 int_info = PyStructSequence_New(&Int_InfoType);
5053 if (int_info == NULL)
5054 return NULL;
5055 PyStructSequence_SET_ITEM(int_info, field++,
5056 PyLong_FromLong(PyLong_SHIFT));
5057 PyStructSequence_SET_ITEM(int_info, field++,
5058 PyLong_FromLong(sizeof(digit)));
5059 if (PyErr_Occurred()) {
5060 Py_CLEAR(int_info);
5061 return NULL;
5062 }
5063 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005064}
5065
Guido van Rossumddefaf32007-01-14 03:31:43 +00005066int
5067_PyLong_Init(void)
5068{
5069#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 int ival, size;
5071 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5074 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5075 if (Py_TYPE(v) == &PyLong_Type) {
5076 /* The element is already initialized, most likely
5077 * the Python interpreter was initialized before.
5078 */
5079 Py_ssize_t refcnt;
5080 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5083 _Py_NewReference(op);
5084 /* _Py_NewReference sets the ref count to 1 but
5085 * the ref count might be larger. Set the refcnt
5086 * to the original refcnt + 1 */
5087 Py_REFCNT(op) = refcnt + 1;
5088 assert(Py_SIZE(op) == size);
5089 assert(v->ob_digit[0] == abs(ival));
5090 }
5091 else {
5092 PyObject_INIT(v, &PyLong_Type);
5093 }
5094 Py_SIZE(v) = size;
5095 v->ob_digit[0] = abs(ival);
5096 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005097#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 /* initialize int_info */
5099 if (Int_InfoType.tp_name == 0)
5100 PyStructSequence_InitType(&Int_InfoType, &int_info_desc);
Mark Dickinsonbd792642009-03-18 20:06:12 +00005101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005103}
5104
5105void
5106PyLong_Fini(void)
5107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 /* Integers are currently statically allocated. Py_DECREF is not
5109 needed, but Python must forget about the reference or multiple
5110 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005111#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 int i;
5113 PyLongObject *v = small_ints;
5114 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5115 _Py_DEC_REFTOTAL;
5116 _Py_ForgetReference((PyObject*)v);
5117 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005118#endif
5119}