blob: b749fd3d2df722fc51fded506ab4fa37a983dfee [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 */
Victor Stinner08a80b12013-07-17 22:33:42 +020020#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
21 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010034Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000035#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050040 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050041 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050042 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000044#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045 if (ival >= 0)
46 quick_int_allocs++;
47 else
48 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000051}
52#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
54 return get_small_int((sdigit)ival); \
55 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000058maybe_small_long(PyLongObject *v)
59{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 if (v && ABS(Py_SIZE(v)) <= 1) {
61 sdigit ival = MEDIUM_VALUE(v);
62 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
63 Py_DECREF(v);
64 return (PyLongObject *)get_small_int(ival);
65 }
66 }
67 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000068}
Guido van Rossumddefaf32007-01-14 03:31:43 +000069#else
70#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000071#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000072#endif
73
Serhiy Storchaka95949422013-08-27 19:40:23 +030074/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000075 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020076Py_LOCAL_INLINE(void)
77_PyLong_Negate(PyLongObject **x_p)
78{
79 PyLongObject *x;
80
81 x = (PyLongObject *)*x_p;
82 if (Py_REFCNT(x) == 1) {
83 Py_SIZE(x) = -Py_SIZE(x);
84 return;
85 }
86
87 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
88 Py_DECREF(x);
89}
90
Serhiy Storchaka95949422013-08-27 19:40:23 +030091/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000092 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030093 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000094 */
Tim Peters0973b992004-08-29 22:16:50 +000095#define KARATSUBA_CUTOFF 70
96#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000097
Tim Peters47e52ee2004-08-30 02:44:38 +000098/* For exponentiation, use the binary left-to-right algorithm
99 * unless the exponent contains more than FIVEARY_CUTOFF digits.
100 * In that case, do 5 bits at a time. The potential drawback is that
101 * a table of 2**5 intermediate results is computed.
102 */
103#define FIVEARY_CUTOFF 8
104
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000105#define SIGCHECK(PyTryBlock) \
106 do { \
107 if (PyErr_CheckSignals()) PyTryBlock \
108 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000109
Serhiy Storchaka95949422013-08-27 19:40:23 +0300110/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000111 Doesn't attempt to free the storage--in most cases, due to the nature
112 of the algorithms used, this could save at most be one word anyway. */
113
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200115long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Py_ssize_t j = ABS(Py_SIZE(v));
118 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 while (i > 0 && v->ob_digit[i-1] == 0)
121 --i;
122 if (i != j)
123 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
124 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000125}
126
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200127/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
128 using the nb_int slot, if available. Raise TypeError if either the
129 nb_int slot is not available or the result of the call to nb_int
130 returns something not of type int.
131*/
132PyLongObject *
133_PyLong_FromNbInt(PyObject *integral)
134{
135 PyNumberMethods *nb;
136 PyObject *result;
137
138 /* Fast path for the case that we already have an int. */
139 if (PyLong_CheckExact(integral)) {
140 Py_INCREF(integral);
141 return (PyLongObject *)integral;
142 }
143
144 nb = Py_TYPE(integral)->tp_as_number;
145 if (nb == NULL || nb->nb_int == NULL) {
146 PyErr_Format(PyExc_TypeError,
147 "an integer is required (got type %.200s)",
148 Py_TYPE(integral)->tp_name);
149 return NULL;
150 }
151
152 /* Convert using the nb_int slot, which should return something
153 of exact type int. */
154 result = nb->nb_int(integral);
155 if (!result || PyLong_CheckExact(result))
156 return (PyLongObject *)result;
157 if (!PyLong_Check(result)) {
158 PyErr_Format(PyExc_TypeError,
159 "__int__ returned non-int (type %.200s)",
160 result->ob_type->tp_name);
161 Py_DECREF(result);
162 return NULL;
163 }
164 /* Issue #17576: warn if 'result' not of exact type int. */
165 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
166 "__int__ returned non-int (type %.200s). "
167 "The ability to return an instance of a strict subclass of int "
168 "is deprecated, and may be removed in a future version of Python.",
169 result->ob_type->tp_name)) {
170 Py_DECREF(result);
171 return NULL;
172 }
173 return (PyLongObject *)result;
174}
175
176
Serhiy Storchaka95949422013-08-27 19:40:23 +0300177/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000178 Return NULL and set exception if we run out of memory. */
179
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000180#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000182
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000184_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 PyLongObject *result;
187 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
188 sizeof(digit)*size. Previous incarnations of this code used
189 sizeof(PyVarObject) instead of the offsetof, but this risks being
190 incorrect in the presence of padding between the PyVarObject header
191 and the digits. */
192 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
193 PyErr_SetString(PyExc_OverflowError,
194 "too many digits in integer");
195 return NULL;
196 }
197 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
198 size*sizeof(digit));
199 if (!result) {
200 PyErr_NoMemory();
201 return NULL;
202 }
203 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000204}
205
Tim Peters64b5ce32001-09-10 20:52:51 +0000206PyObject *
207_PyLong_Copy(PyLongObject *src)
208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 PyLongObject *result;
210 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 assert(src != NULL);
213 i = Py_SIZE(src);
214 if (i < 0)
215 i = -(i);
216 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100217 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 CHECK_SMALL_INT(ival);
219 }
220 result = _PyLong_New(i);
221 if (result != NULL) {
222 Py_SIZE(result) = Py_SIZE(src);
223 while (--i >= 0)
224 result->ob_digit[i] = src->ob_digit[i];
225 }
226 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000227}
228
Serhiy Storchaka95949422013-08-27 19:40:23 +0300229/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000230
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000231PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000232PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyLongObject *v;
235 unsigned long abs_ival;
236 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
237 int ndigits = 0;
238 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 if (ival < 0) {
243 /* negate: can't write this as abs_ival = -ival since that
244 invokes undefined behaviour when ival is LONG_MIN */
245 abs_ival = 0U-(unsigned long)ival;
246 sign = -1;
247 }
248 else {
249 abs_ival = (unsigned long)ival;
250 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /* Fast path for single-digit ints */
253 if (!(abs_ival >> PyLong_SHIFT)) {
254 v = _PyLong_New(1);
255 if (v) {
256 Py_SIZE(v) = sign;
257 v->ob_digit[0] = Py_SAFE_DOWNCAST(
258 abs_ival, unsigned long, digit);
259 }
260 return (PyObject*)v;
261 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000262
Mark Dickinson249b8982009-04-27 19:41:00 +0000263#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* 2 digits */
265 if (!(abs_ival >> 2*PyLong_SHIFT)) {
266 v = _PyLong_New(2);
267 if (v) {
268 Py_SIZE(v) = 2*sign;
269 v->ob_digit[0] = Py_SAFE_DOWNCAST(
270 abs_ival & PyLong_MASK, unsigned long, digit);
271 v->ob_digit[1] = Py_SAFE_DOWNCAST(
272 abs_ival >> PyLong_SHIFT, unsigned long, digit);
273 }
274 return (PyObject*)v;
275 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000276#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* Larger numbers: loop to determine number of digits */
279 t = abs_ival;
280 while (t) {
281 ++ndigits;
282 t >>= PyLong_SHIFT;
283 }
284 v = _PyLong_New(ndigits);
285 if (v != NULL) {
286 digit *p = v->ob_digit;
287 Py_SIZE(v) = ndigits*sign;
288 t = abs_ival;
289 while (t) {
290 *p++ = Py_SAFE_DOWNCAST(
291 t & PyLong_MASK, unsigned long, digit);
292 t >>= PyLong_SHIFT;
293 }
294 }
295 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000296}
297
Serhiy Storchaka95949422013-08-27 19:40:23 +0300298/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000299
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000300PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000301PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 PyLongObject *v;
304 unsigned long t;
305 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (ival < PyLong_BASE)
308 return PyLong_FromLong(ival);
309 /* Count the number of Python digits. */
310 t = (unsigned long)ival;
311 while (t) {
312 ++ndigits;
313 t >>= PyLong_SHIFT;
314 }
315 v = _PyLong_New(ndigits);
316 if (v != NULL) {
317 digit *p = v->ob_digit;
318 Py_SIZE(v) = ndigits;
319 while (ival) {
320 *p++ = (digit)(ival & PyLong_MASK);
321 ival >>= PyLong_SHIFT;
322 }
323 }
324 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000325}
326
Serhiy Storchaka95949422013-08-27 19:40:23 +0300327/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000328
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 PyLongObject *v;
333 double frac;
334 int i, ndig, expo, neg;
335 neg = 0;
336 if (Py_IS_INFINITY(dval)) {
337 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000338 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return NULL;
340 }
341 if (Py_IS_NAN(dval)) {
342 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000343 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 return NULL;
345 }
346 if (dval < 0.0) {
347 neg = 1;
348 dval = -dval;
349 }
350 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
351 if (expo <= 0)
352 return PyLong_FromLong(0L);
353 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
354 v = _PyLong_New(ndig);
355 if (v == NULL)
356 return NULL;
357 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
358 for (i = ndig; --i >= 0; ) {
359 digit bits = (digit)frac;
360 v->ob_digit[i] = bits;
361 frac = frac - (double)bits;
362 frac = ldexp(frac, PyLong_SHIFT);
363 }
364 if (neg)
365 Py_SIZE(v) = -(Py_SIZE(v));
366 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000367}
368
Thomas Wouters89f507f2006-12-13 04:49:30 +0000369/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
370 * anything about what happens when a signed integer operation overflows,
371 * and some compilers think they're doing you a favor by being "clever"
372 * then. The bit pattern for the largest postive signed long is
373 * (unsigned long)LONG_MAX, and for the smallest negative signed long
374 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
375 * However, some other compilers warn about applying unary minus to an
376 * unsigned operand. Hence the weird "0-".
377 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
379#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380
Serhiy Storchaka95949422013-08-27 19:40:23 +0300381/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100382 method.
383
384 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
385 the result. Otherwise *overflow is 0.
386
387 For other errors (e.g., TypeError), return -1 and set an error condition.
388 In this case *overflow will be 0.
389*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000390
391long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000392PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200395 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 unsigned long x, prev;
397 long res;
398 Py_ssize_t i;
399 int sign;
400 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 *overflow = 0;
403 if (vv == NULL) {
404 PyErr_BadInternalCall();
405 return -1;
406 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000407
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200408 if (PyLong_Check(vv)) {
409 v = (PyLongObject *)vv;
410 }
411 else {
412 v = _PyLong_FromNbInt(vv);
413 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 return -1;
415 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 switch (i) {
422 case -1:
423 res = -(sdigit)v->ob_digit[0];
424 break;
425 case 0:
426 res = 0;
427 break;
428 case 1:
429 res = v->ob_digit[0];
430 break;
431 default:
432 sign = 1;
433 x = 0;
434 if (i < 0) {
435 sign = -1;
436 i = -(i);
437 }
438 while (--i >= 0) {
439 prev = x;
440 x = (x << PyLong_SHIFT) | v->ob_digit[i];
441 if ((x >> PyLong_SHIFT) != prev) {
442 *overflow = sign;
443 goto exit;
444 }
445 }
446 /* Haven't lost any bits, but casting to long requires extra
447 * care (see comment above).
448 */
449 if (x <= (unsigned long)LONG_MAX) {
450 res = (long)x * sign;
451 }
452 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
453 res = LONG_MIN;
454 }
455 else {
456 *overflow = sign;
457 /* res is already set to -1 */
458 }
459 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000460 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200462 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 }
464 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000465}
466
Serhiy Storchaka95949422013-08-27 19:40:23 +0300467/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100468 method. Return -1 and set an error if overflow occurs. */
469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000471PyLong_AsLong(PyObject *obj)
472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 int overflow;
474 long result = PyLong_AsLongAndOverflow(obj, &overflow);
475 if (overflow) {
476 /* XXX: could be cute and give a different
477 message for overflow == -1 */
478 PyErr_SetString(PyExc_OverflowError,
479 "Python int too large to convert to C long");
480 }
481 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000482}
483
Serhiy Storchaka95949422013-08-27 19:40:23 +0300484/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200485 method. Return -1 and set an error if overflow occurs. */
486
487int
488_PyLong_AsInt(PyObject *obj)
489{
490 int overflow;
491 long result = PyLong_AsLongAndOverflow(obj, &overflow);
492 if (overflow || result > INT_MAX || result < INT_MIN) {
493 /* XXX: could be cute and give a different
494 message for overflow == -1 */
495 PyErr_SetString(PyExc_OverflowError,
496 "Python int too large to convert to C int");
497 return -1;
498 }
499 return (int)result;
500}
501
Serhiy Storchaka95949422013-08-27 19:40:23 +0300502/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000503 Returns -1 and sets an error condition if overflow occurs. */
504
505Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000506PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200507 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 size_t x, prev;
509 Py_ssize_t i;
510 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (vv == NULL) {
513 PyErr_BadInternalCall();
514 return -1;
515 }
516 if (!PyLong_Check(vv)) {
517 PyErr_SetString(PyExc_TypeError, "an integer is required");
518 return -1;
519 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 v = (PyLongObject *)vv;
522 i = Py_SIZE(v);
523 switch (i) {
524 case -1: return -(sdigit)v->ob_digit[0];
525 case 0: return 0;
526 case 1: return v->ob_digit[0];
527 }
528 sign = 1;
529 x = 0;
530 if (i < 0) {
531 sign = -1;
532 i = -(i);
533 }
534 while (--i >= 0) {
535 prev = x;
536 x = (x << PyLong_SHIFT) | v->ob_digit[i];
537 if ((x >> PyLong_SHIFT) != prev)
538 goto overflow;
539 }
540 /* Haven't lost any bits, but casting to a signed type requires
541 * extra care (see comment above).
542 */
543 if (x <= (size_t)PY_SSIZE_T_MAX) {
544 return (Py_ssize_t)x * sign;
545 }
546 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
547 return PY_SSIZE_T_MIN;
548 }
549 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000550
Mark Dickinson22b20182010-05-10 21:27:53 +0000551 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyErr_SetString(PyExc_OverflowError,
553 "Python int too large to convert to C ssize_t");
554 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000555}
556
Serhiy Storchaka95949422013-08-27 19:40:23 +0300557/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000558 Returns -1 and sets an error condition if overflow occurs. */
559
560unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000561PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000562{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200563 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 unsigned long x, prev;
565 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (vv == NULL) {
568 PyErr_BadInternalCall();
569 return (unsigned long)-1;
570 }
571 if (!PyLong_Check(vv)) {
572 PyErr_SetString(PyExc_TypeError, "an integer is required");
573 return (unsigned long)-1;
574 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 v = (PyLongObject *)vv;
577 i = Py_SIZE(v);
578 x = 0;
579 if (i < 0) {
580 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000581 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 return (unsigned long) -1;
583 }
584 switch (i) {
585 case 0: return 0;
586 case 1: return v->ob_digit[0];
587 }
588 while (--i >= 0) {
589 prev = x;
590 x = (x << PyLong_SHIFT) | v->ob_digit[i];
591 if ((x >> PyLong_SHIFT) != prev) {
592 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100593 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000594 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return (unsigned long) -1;
596 }
597 }
598 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000599}
600
Serhiy Storchaka95949422013-08-27 19:40:23 +0300601/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200602 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000603
604size_t
605PyLong_AsSize_t(PyObject *vv)
606{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200607 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 size_t x, prev;
609 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (vv == NULL) {
612 PyErr_BadInternalCall();
613 return (size_t) -1;
614 }
615 if (!PyLong_Check(vv)) {
616 PyErr_SetString(PyExc_TypeError, "an integer is required");
617 return (size_t)-1;
618 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 v = (PyLongObject *)vv;
621 i = Py_SIZE(v);
622 x = 0;
623 if (i < 0) {
624 PyErr_SetString(PyExc_OverflowError,
625 "can't convert negative value to size_t");
626 return (size_t) -1;
627 }
628 switch (i) {
629 case 0: return 0;
630 case 1: return v->ob_digit[0];
631 }
632 while (--i >= 0) {
633 prev = x;
634 x = (x << PyLong_SHIFT) | v->ob_digit[i];
635 if ((x >> PyLong_SHIFT) != prev) {
636 PyErr_SetString(PyExc_OverflowError,
637 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200638 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 }
640 }
641 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000642}
643
Serhiy Storchaka95949422013-08-27 19:40:23 +0300644/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000645 Returns -1 and sets an error condition if an error occurs. */
646
Guido van Rossumddefaf32007-01-14 03:31:43 +0000647static unsigned long
648_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000649{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200650 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 unsigned long x;
652 Py_ssize_t i;
653 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (vv == NULL || !PyLong_Check(vv)) {
656 PyErr_BadInternalCall();
657 return (unsigned long) -1;
658 }
659 v = (PyLongObject *)vv;
660 i = Py_SIZE(v);
661 switch (i) {
662 case 0: return 0;
663 case 1: return v->ob_digit[0];
664 }
665 sign = 1;
666 x = 0;
667 if (i < 0) {
668 sign = -1;
669 i = -i;
670 }
671 while (--i >= 0) {
672 x = (x << PyLong_SHIFT) | v->ob_digit[i];
673 }
674 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000675}
676
Guido van Rossumddefaf32007-01-14 03:31:43 +0000677unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200678PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyLongObject *lo;
681 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000682
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200683 if (op == NULL) {
684 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return (unsigned long)-1;
686 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000687
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200688 if (PyLong_Check(op)) {
689 return _PyLong_AsUnsignedLongMask(op);
690 }
691
692 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (lo == NULL)
694 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200695
696 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
697 Py_DECREF(lo);
698 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000699}
700
Tim Peters5b8132f2003-01-31 15:52:05 +0000701int
702_PyLong_Sign(PyObject *vv)
703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 assert(v != NULL);
707 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000710}
711
Tim Petersbaefd9e2003-01-28 20:37:45 +0000712size_t
713_PyLong_NumBits(PyObject *vv)
714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyLongObject *v = (PyLongObject *)vv;
716 size_t result = 0;
717 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 assert(v != NULL);
720 assert(PyLong_Check(v));
721 ndigits = ABS(Py_SIZE(v));
722 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
723 if (ndigits > 0) {
724 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100725 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100727 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 do {
729 ++result;
730 if (result == 0)
731 goto Overflow;
732 msd >>= 1;
733 } while (msd);
734 }
735 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000736
Mark Dickinson22b20182010-05-10 21:27:53 +0000737 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
739 "to express in a platform size_t");
740 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000741}
742
Tim Peters2a9b3672001-06-11 21:23:58 +0000743PyObject *
744_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000746{
Mark Dickinson22b20182010-05-10 21:27:53 +0000747 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 int incr; /* direction to move pstartbyte */
749 const unsigned char* pendbyte; /* MSB of bytes */
750 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300751 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyLongObject* v; /* result */
753 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (n == 0)
756 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 if (little_endian) {
759 pstartbyte = bytes;
760 pendbyte = bytes + n - 1;
761 incr = 1;
762 }
763 else {
764 pstartbyte = bytes + n - 1;
765 pendbyte = bytes;
766 incr = -1;
767 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (is_signed)
770 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200773 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 is positive, and leading 0xff bytes if negative. */
775 {
776 size_t i;
777 const unsigned char* p = pendbyte;
778 const int pincr = -incr; /* search MSB to LSB */
779 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 for (i = 0; i < n; ++i, p += pincr) {
782 if (*p != insignficant)
783 break;
784 }
785 numsignificantbytes = n - i;
786 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
787 actually has 2 significant bytes. OTOH, 0xff0001 ==
788 -0x00ffff, so we wouldn't *need* to bump it there; but we
789 do for 0xffff = -0x0001. To be safe without bothering to
790 check every case, bump it regardless. */
791 if (is_signed && numsignificantbytes < n)
792 ++numsignificantbytes;
793 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000794
Serhiy Storchaka95949422013-08-27 19:40:23 +0300795 /* How many Python int digits do we need? We have
796 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
798 /* catch overflow before it happens */
799 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
800 PyErr_SetString(PyExc_OverflowError,
801 "byte array too long to convert to int");
802 return NULL;
803 }
804 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
805 v = _PyLong_New(ndigits);
806 if (v == NULL)
807 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 /* Copy the bits over. The tricky parts are computing 2's-comp on
810 the fly for signed numbers, and dealing with the mismatch between
811 8-bit bytes and (probably) 15-bit Python digits.*/
812 {
813 size_t i;
814 twodigits carry = 1; /* for 2's-comp calculation */
815 twodigits accum = 0; /* sliding register */
816 unsigned int accumbits = 0; /* number of bits in accum */
817 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
820 twodigits thisbyte = *p;
821 /* Compute correction for 2's comp, if needed. */
822 if (is_signed) {
823 thisbyte = (0xff ^ thisbyte) + carry;
824 carry = thisbyte >> 8;
825 thisbyte &= 0xff;
826 }
827 /* Because we're going LSB to MSB, thisbyte is
828 more significant than what's already in accum,
829 so needs to be prepended to accum. */
830 accum |= (twodigits)thisbyte << accumbits;
831 accumbits += 8;
832 if (accumbits >= PyLong_SHIFT) {
833 /* There's enough to fill a Python digit. */
834 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000835 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 ++idigit;
837 accum >>= PyLong_SHIFT;
838 accumbits -= PyLong_SHIFT;
839 assert(accumbits < PyLong_SHIFT);
840 }
841 }
842 assert(accumbits < PyLong_SHIFT);
843 if (accumbits) {
844 assert(idigit < ndigits);
845 v->ob_digit[idigit] = (digit)accum;
846 ++idigit;
847 }
848 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 Py_SIZE(v) = is_signed ? -idigit : idigit;
851 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000852}
853
854int
855_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 unsigned char* bytes, size_t n,
857 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000862 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
864 digit carry; /* for computing 2's-comp */
865 size_t j; /* # bytes filled */
866 unsigned char* p; /* pointer to next byte in bytes */
867 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (Py_SIZE(v) < 0) {
872 ndigits = -(Py_SIZE(v));
873 if (!is_signed) {
874 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000875 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 return -1;
877 }
878 do_twos_comp = 1;
879 }
880 else {
881 ndigits = Py_SIZE(v);
882 do_twos_comp = 0;
883 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (little_endian) {
886 p = bytes;
887 pincr = 1;
888 }
889 else {
890 p = bytes + n - 1;
891 pincr = -1;
892 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Copy over all the Python digits.
895 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300896 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 normalized. */
898 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
899 j = 0;
900 accum = 0;
901 accumbits = 0;
902 carry = do_twos_comp ? 1 : 0;
903 for (i = 0; i < ndigits; ++i) {
904 digit thisdigit = v->ob_digit[i];
905 if (do_twos_comp) {
906 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
907 carry = thisdigit >> PyLong_SHIFT;
908 thisdigit &= PyLong_MASK;
909 }
910 /* Because we're going LSB to MSB, thisdigit is more
911 significant than what's already in accum, so needs to be
912 prepended to accum. */
913 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* The most-significant digit may be (probably is) at least
916 partly empty. */
917 if (i == ndigits - 1) {
918 /* Count # of sign bits -- they needn't be stored,
919 * although for signed conversion we need later to
920 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000921 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 while (s != 0) {
923 s >>= 1;
924 accumbits++;
925 }
926 }
927 else
928 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 /* Store as many bytes as possible. */
931 while (accumbits >= 8) {
932 if (j >= n)
933 goto Overflow;
934 ++j;
935 *p = (unsigned char)(accum & 0xff);
936 p += pincr;
937 accumbits -= 8;
938 accum >>= 8;
939 }
940 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Store the straggler (if any). */
943 assert(accumbits < 8);
944 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
945 if (accumbits > 0) {
946 if (j >= n)
947 goto Overflow;
948 ++j;
949 if (do_twos_comp) {
950 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300951 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 infinite supply of sign bits). */
953 accum |= (~(twodigits)0) << accumbits;
954 }
955 *p = (unsigned char)(accum & 0xff);
956 p += pincr;
957 }
958 else if (j == n && n > 0 && is_signed) {
959 /* The main loop filled the byte array exactly, so the code
960 just above didn't get to ensure there's a sign bit, and the
961 loop below wouldn't add one either. Make sure a sign bit
962 exists. */
963 unsigned char msb = *(p - pincr);
964 int sign_bit_set = msb >= 0x80;
965 assert(accumbits == 0);
966 if (sign_bit_set == do_twos_comp)
967 return 0;
968 else
969 goto Overflow;
970 }
Tim Peters05607ad2001-06-13 21:01:27 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* Fill remaining bytes with copies of the sign bit. */
973 {
974 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
975 for ( ; j < n; ++j, p += pincr)
976 *p = signbyte;
977 }
Tim Peters05607ad2001-06-13 21:01:27 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000980
Mark Dickinson22b20182010-05-10 21:27:53 +0000981 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
983 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000984
Tim Peters2a9b3672001-06-11 21:23:58 +0000985}
986
Serhiy Storchaka95949422013-08-27 19:40:23 +0300987/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000988
989PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000990PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000991{
Mark Dickinson91044792012-10-18 19:21:43 +0100992#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100993 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
994#else
995
Tim Peters70128a12001-06-16 08:48:40 +0000996#ifndef HAVE_LONG_LONG
997# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
998#endif
999#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001000# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001001#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001003#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001004
Guido van Rossum78694d91998-09-18 14:14:13 +00001005}
1006
Serhiy Storchaka95949422013-08-27 19:40:23 +03001007/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001008
1009void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001010PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001011{
Tim Peters70128a12001-06-16 08:48:40 +00001012#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1016 x = PyLong_AsLong(vv);
1017 else
1018 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001019#else
Tim Peters70128a12001-06-16 08:48:40 +00001020
1021#ifndef HAVE_LONG_LONG
1022# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1023#endif
1024#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001025# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001026#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1030 x = PyLong_AsLongLong(vv);
1031 else
1032 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001033
1034#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 if (x == -1 && PyErr_Occurred())
1037 return NULL;
1038 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001039}
1040
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001041#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001042
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001043/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001044 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001045 */
1046
Mark Dickinson22b20182010-05-10 21:27:53 +00001047#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001048
Serhiy Storchaka95949422013-08-27 19:40:23 +03001049/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001050
1051PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001052PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 PyLongObject *v;
1055 unsigned PY_LONG_LONG abs_ival;
1056 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1057 int ndigits = 0;
1058 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 CHECK_SMALL_INT(ival);
1061 if (ival < 0) {
1062 /* avoid signed overflow on negation; see comments
1063 in PyLong_FromLong above. */
1064 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1065 negative = 1;
1066 }
1067 else {
1068 abs_ival = (unsigned PY_LONG_LONG)ival;
1069 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 /* Count the number of Python digits.
1072 We used to pick 5 ("big enough for anything"), but that's a
1073 waste of time and space given that 5*15 = 75 bits are rarely
1074 needed. */
1075 t = abs_ival;
1076 while (t) {
1077 ++ndigits;
1078 t >>= PyLong_SHIFT;
1079 }
1080 v = _PyLong_New(ndigits);
1081 if (v != NULL) {
1082 digit *p = v->ob_digit;
1083 Py_SIZE(v) = negative ? -ndigits : ndigits;
1084 t = abs_ival;
1085 while (t) {
1086 *p++ = (digit)(t & PyLong_MASK);
1087 t >>= PyLong_SHIFT;
1088 }
1089 }
1090 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001091}
1092
Serhiy Storchaka95949422013-08-27 19:40:23 +03001093/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001094
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001095PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001096PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyLongObject *v;
1099 unsigned PY_LONG_LONG t;
1100 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (ival < PyLong_BASE)
1103 return PyLong_FromLong((long)ival);
1104 /* Count the number of Python digits. */
1105 t = (unsigned PY_LONG_LONG)ival;
1106 while (t) {
1107 ++ndigits;
1108 t >>= PyLong_SHIFT;
1109 }
1110 v = _PyLong_New(ndigits);
1111 if (v != NULL) {
1112 digit *p = v->ob_digit;
1113 Py_SIZE(v) = ndigits;
1114 while (ival) {
1115 *p++ = (digit)(ival & PyLong_MASK);
1116 ival >>= PyLong_SHIFT;
1117 }
1118 }
1119 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001120}
1121
Serhiy Storchaka95949422013-08-27 19:40:23 +03001122/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123
1124PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001125PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyLongObject *v;
1128 size_t abs_ival;
1129 size_t t; /* unsigned so >> doesn't propagate sign bit */
1130 int ndigits = 0;
1131 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 CHECK_SMALL_INT(ival);
1134 if (ival < 0) {
1135 /* avoid signed overflow when ival = SIZE_T_MIN */
1136 abs_ival = (size_t)(-1-ival)+1;
1137 negative = 1;
1138 }
1139 else {
1140 abs_ival = (size_t)ival;
1141 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 /* Count the number of Python digits. */
1144 t = abs_ival;
1145 while (t) {
1146 ++ndigits;
1147 t >>= PyLong_SHIFT;
1148 }
1149 v = _PyLong_New(ndigits);
1150 if (v != NULL) {
1151 digit *p = v->ob_digit;
1152 Py_SIZE(v) = negative ? -ndigits : ndigits;
1153 t = abs_ival;
1154 while (t) {
1155 *p++ = (digit)(t & PyLong_MASK);
1156 t >>= PyLong_SHIFT;
1157 }
1158 }
1159 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001160}
1161
Serhiy Storchaka95949422013-08-27 19:40:23 +03001162/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163
1164PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001165PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 PyLongObject *v;
1168 size_t t;
1169 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (ival < PyLong_BASE)
1172 return PyLong_FromLong((long)ival);
1173 /* Count the number of Python digits. */
1174 t = ival;
1175 while (t) {
1176 ++ndigits;
1177 t >>= PyLong_SHIFT;
1178 }
1179 v = _PyLong_New(ndigits);
1180 if (v != NULL) {
1181 digit *p = v->ob_digit;
1182 Py_SIZE(v) = ndigits;
1183 while (ival) {
1184 *p++ = (digit)(ival & PyLong_MASK);
1185 ival >>= PyLong_SHIFT;
1186 }
1187 }
1188 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001189}
1190
Serhiy Storchaka95949422013-08-27 19:40:23 +03001191/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001192 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001193
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001194PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001195PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyLongObject *v;
1198 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 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,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001230 SIZEOF_LONG_LONG, PY_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;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001252
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001253 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 PyErr_BadInternalCall();
1255 return (unsigned PY_LONG_LONG)-1;
1256 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001257 if (!PyLong_Check(vv)) {
1258 PyErr_SetString(PyExc_TypeError, "an integer is required");
1259 return (unsigned PY_LONG_LONG)-1;
1260 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 v = (PyLongObject*)vv;
1263 switch(Py_SIZE(v)) {
1264 case 0: return 0;
1265 case 1: return v->ob_digit[0];
1266 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001267
Mark Dickinson22b20182010-05-10 21:27:53 +00001268 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001269 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1272 if (res < 0)
1273 return (unsigned PY_LONG_LONG)res;
1274 else
1275 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001276}
Tim Petersd1a7da62001-06-13 00:35:57 +00001277
Serhiy Storchaka95949422013-08-27 19:40:23 +03001278/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001279 Returns -1 and sets an error condition if an error occurs. */
1280
Guido van Rossumddefaf32007-01-14 03:31:43 +00001281static unsigned PY_LONG_LONG
1282_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001283{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001284 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 unsigned PY_LONG_LONG x;
1286 Py_ssize_t i;
1287 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (vv == NULL || !PyLong_Check(vv)) {
1290 PyErr_BadInternalCall();
1291 return (unsigned long) -1;
1292 }
1293 v = (PyLongObject *)vv;
1294 switch(Py_SIZE(v)) {
1295 case 0: return 0;
1296 case 1: return v->ob_digit[0];
1297 }
1298 i = Py_SIZE(v);
1299 sign = 1;
1300 x = 0;
1301 if (i < 0) {
1302 sign = -1;
1303 i = -i;
1304 }
1305 while (--i >= 0) {
1306 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1307 }
1308 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001309}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001310
1311unsigned PY_LONG_LONG
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001312PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyLongObject *lo;
1315 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001316
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001317 if (op == NULL) {
1318 PyErr_BadInternalCall();
1319 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001321
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001322 if (PyLong_Check(op)) {
1323 return _PyLong_AsUnsignedLongLongMask(op);
1324 }
1325
1326 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (lo == NULL)
1328 return (unsigned PY_LONG_LONG)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001329
1330 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1331 Py_DECREF(lo);
1332 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001333}
Tim Petersd1a7da62001-06-13 00:35:57 +00001334
Serhiy Storchaka95949422013-08-27 19:40:23 +03001335/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001336 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001337
Mark Dickinson8d48b432011-10-23 20:47:14 +01001338 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1339 the result. Otherwise *overflow is 0.
1340
1341 For other errors (e.g., TypeError), return -1 and set an error condition.
1342 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001343*/
1344
1345PY_LONG_LONG
1346PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001349 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 unsigned PY_LONG_LONG x, prev;
1351 PY_LONG_LONG res;
1352 Py_ssize_t i;
1353 int sign;
1354 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 *overflow = 0;
1357 if (vv == NULL) {
1358 PyErr_BadInternalCall();
1359 return -1;
1360 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001361
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001362 if (PyLong_Check(vv)) {
1363 v = (PyLongObject *)vv;
1364 }
1365 else {
1366 v = _PyLong_FromNbInt(vv);
1367 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 return -1;
1369 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 switch (i) {
1376 case -1:
1377 res = -(sdigit)v->ob_digit[0];
1378 break;
1379 case 0:
1380 res = 0;
1381 break;
1382 case 1:
1383 res = v->ob_digit[0];
1384 break;
1385 default:
1386 sign = 1;
1387 x = 0;
1388 if (i < 0) {
1389 sign = -1;
1390 i = -(i);
1391 }
1392 while (--i >= 0) {
1393 prev = x;
1394 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1395 if ((x >> PyLong_SHIFT) != prev) {
1396 *overflow = sign;
1397 goto exit;
1398 }
1399 }
1400 /* Haven't lost any bits, but casting to long requires extra
1401 * care (see comment above).
1402 */
1403 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1404 res = (PY_LONG_LONG)x * sign;
1405 }
1406 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1407 res = PY_LLONG_MIN;
1408 }
1409 else {
1410 *overflow = sign;
1411 /* res is already set to -1 */
1412 }
1413 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001414 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001416 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 }
1418 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001419}
1420
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001421#endif /* HAVE_LONG_LONG */
1422
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001423#define CHECK_BINOP(v,w) \
1424 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001425 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1426 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001427 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001428
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001429/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1430 2**k if d is nonzero, else 0. */
1431
1432static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1434 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001435};
1436
1437static int
1438bits_in_digit(digit d)
1439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 int d_bits = 0;
1441 while (d >= 32) {
1442 d_bits += 6;
1443 d >>= 6;
1444 }
1445 d_bits += (int)BitLengthTable[d];
1446 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001447}
1448
Tim Peters877a2122002-08-12 05:09:36 +00001449/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1450 * is modified in place, by adding y to it. Carries are propagated as far as
1451 * x[m-1], and the remaining carry (0 or 1) is returned.
1452 */
1453static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001454v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 Py_ssize_t i;
1457 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 assert(m >= n);
1460 for (i = 0; i < n; ++i) {
1461 carry += x[i] + y[i];
1462 x[i] = carry & PyLong_MASK;
1463 carry >>= PyLong_SHIFT;
1464 assert((carry & 1) == carry);
1465 }
1466 for (; carry && i < m; ++i) {
1467 carry += x[i];
1468 x[i] = carry & PyLong_MASK;
1469 carry >>= PyLong_SHIFT;
1470 assert((carry & 1) == carry);
1471 }
1472 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001473}
1474
1475/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1476 * is modified in place, by subtracting y from it. Borrows are propagated as
1477 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1478 */
1479static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001480v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 Py_ssize_t i;
1483 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 assert(m >= n);
1486 for (i = 0; i < n; ++i) {
1487 borrow = x[i] - y[i] - borrow;
1488 x[i] = borrow & PyLong_MASK;
1489 borrow >>= PyLong_SHIFT;
1490 borrow &= 1; /* keep only 1 sign bit */
1491 }
1492 for (; borrow && i < m; ++i) {
1493 borrow = x[i] - borrow;
1494 x[i] = borrow & PyLong_MASK;
1495 borrow >>= PyLong_SHIFT;
1496 borrow &= 1;
1497 }
1498 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001499}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001500
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001501/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1502 * result in z[0:m], and return the d bits shifted out of the top.
1503 */
1504static digit
1505v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 Py_ssize_t i;
1508 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 assert(0 <= d && d < PyLong_SHIFT);
1511 for (i=0; i < m; i++) {
1512 twodigits acc = (twodigits)a[i] << d | carry;
1513 z[i] = (digit)acc & PyLong_MASK;
1514 carry = (digit)(acc >> PyLong_SHIFT);
1515 }
1516 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001517}
1518
1519/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1520 * result in z[0:m], and return the d bits shifted out of the bottom.
1521 */
1522static digit
1523v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 Py_ssize_t i;
1526 digit carry = 0;
1527 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 assert(0 <= d && d < PyLong_SHIFT);
1530 for (i=m; i-- > 0;) {
1531 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1532 carry = (digit)acc & mask;
1533 z[i] = (digit)(acc >> d);
1534 }
1535 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001536}
1537
Tim Peters212e6142001-07-14 12:23:19 +00001538/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1539 in pout, and returning the remainder. pin and pout point at the LSD.
1540 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001541 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001542 immutable. */
1543
1544static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001545inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 assert(n > 0 && n <= PyLong_MASK);
1550 pin += size;
1551 pout += size;
1552 while (--size >= 0) {
1553 digit hi;
1554 rem = (rem << PyLong_SHIFT) | *--pin;
1555 *--pout = hi = (digit)(rem / n);
1556 rem -= (twodigits)hi * n;
1557 }
1558 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001559}
1560
Serhiy Storchaka95949422013-08-27 19:40:23 +03001561/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001562 (as function result) and the remainder (through *prem).
1563 The sign of a is ignored; n should not be zero. */
1564
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001565static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001566divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 const Py_ssize_t size = ABS(Py_SIZE(a));
1569 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 assert(n > 0 && n <= PyLong_MASK);
1572 z = _PyLong_New(size);
1573 if (z == NULL)
1574 return NULL;
1575 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1576 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001577}
1578
Serhiy Storchaka95949422013-08-27 19:40:23 +03001579/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001580 string. (Return value is non-shared so that callers can modify the
1581 returned value if necessary.) */
1582
Victor Stinnerd3f08822012-05-29 12:57:52 +02001583static int
1584long_to_decimal_string_internal(PyObject *aa,
1585 PyObject **p_output,
1586 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyLongObject *scratch, *a;
1589 PyObject *str;
1590 Py_ssize_t size, strlen, size_a, i, j;
1591 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001593 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 a = (PyLongObject *)aa;
1596 if (a == NULL || !PyLong_Check(a)) {
1597 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001598 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 }
1600 size_a = ABS(Py_SIZE(a));
1601 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 /* quick and dirty upper bound for the number of digits
1604 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 But log2(a) < size_a * PyLong_SHIFT, and
1609 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1610 > 3 * _PyLong_DECIMAL_SHIFT
1611 */
1612 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1613 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001614 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001615 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 }
1617 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1618 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1619 scratch = _PyLong_New(size);
1620 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001621 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 /* convert array of base _PyLong_BASE digits in pin to an array of
1624 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1625 Volume 2 (3rd edn), section 4.4, Method 1b). */
1626 pin = a->ob_digit;
1627 pout = scratch->ob_digit;
1628 size = 0;
1629 for (i = size_a; --i >= 0; ) {
1630 digit hi = pin[i];
1631 for (j = 0; j < size; j++) {
1632 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1633 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1634 pout[j] = (digit)(z - (twodigits)hi *
1635 _PyLong_DECIMAL_BASE);
1636 }
1637 while (hi) {
1638 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1639 hi /= _PyLong_DECIMAL_BASE;
1640 }
1641 /* check for keyboard interrupt */
1642 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001643 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001644 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001645 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 }
1647 /* pout should have at least one digit, so that the case when a = 0
1648 works correctly */
1649 if (size == 0)
1650 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* calculate exact length of output string, and allocate */
1653 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1654 tenpow = 10;
1655 rem = pout[size-1];
1656 while (rem >= tenpow) {
1657 tenpow *= 10;
1658 strlen++;
1659 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001660 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001661 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1662 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001663 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001664 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001665 kind = writer->kind;
1666 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001668 else {
1669 str = PyUnicode_New(strlen, '9');
1670 if (str == NULL) {
1671 Py_DECREF(scratch);
1672 return -1;
1673 }
1674 kind = PyUnicode_KIND(str);
1675 }
1676
1677#define WRITE_DIGITS(TYPE) \
1678 do { \
1679 if (writer) \
1680 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1681 else \
1682 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1683 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001684 /* pout[0] through pout[size-2] contribute exactly \
1685 _PyLong_DECIMAL_SHIFT digits each */ \
1686 for (i=0; i < size - 1; i++) { \
1687 rem = pout[i]; \
1688 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1689 *--p = '0' + rem % 10; \
1690 rem /= 10; \
1691 } \
1692 } \
1693 /* pout[size-1]: always produce at least one decimal digit */ \
1694 rem = pout[i]; \
1695 do { \
1696 *--p = '0' + rem % 10; \
1697 rem /= 10; \
1698 } while (rem != 0); \
1699 \
1700 /* and sign */ \
1701 if (negative) \
1702 *--p = '-'; \
1703 \
1704 /* check we've counted correctly */ \
1705 if (writer) \
1706 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1707 else \
1708 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1709 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001712 if (kind == PyUnicode_1BYTE_KIND) {
1713 Py_UCS1 *p;
1714 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001716 else if (kind == PyUnicode_2BYTE_KIND) {
1717 Py_UCS2 *p;
1718 WRITE_DIGITS(Py_UCS2);
1719 }
1720 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001721 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001722 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001723 WRITE_DIGITS(Py_UCS4);
1724 }
1725#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001728 if (writer) {
1729 writer->pos += strlen;
1730 }
1731 else {
1732 assert(_PyUnicode_CheckConsistency(str, 1));
1733 *p_output = (PyObject *)str;
1734 }
1735 return 0;
1736}
1737
1738static PyObject *
1739long_to_decimal_string(PyObject *aa)
1740{
1741 PyObject *v;
1742 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1743 return NULL;
1744 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001745}
1746
Serhiy Storchaka95949422013-08-27 19:40:23 +03001747/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001748 which should be one of 2, 8 or 16. Return a string object.
1749 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1750 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001751
Victor Stinnerd3f08822012-05-29 12:57:52 +02001752static int
1753long_format_binary(PyObject *aa, int base, int alternate,
1754 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001755{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001756 PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001758 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001760 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001761 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001763
Victor Stinnerd3f08822012-05-29 12:57:52 +02001764 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 if (a == NULL || !PyLong_Check(a)) {
1766 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 }
1769 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001770 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* Compute a rough upper bound for the length of the string */
1773 switch (base) {
1774 case 16:
1775 bits = 4;
1776 break;
1777 case 8:
1778 bits = 3;
1779 break;
1780 case 2:
1781 bits = 1;
1782 break;
1783 default:
1784 assert(0); /* shouldn't ever get here */
1785 bits = 0; /* to silence gcc warning */
1786 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001787
Mark Dickinsone2846542012-04-20 21:21:24 +01001788 /* Compute exact length 'sz' of output string. */
1789 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001790 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001791 }
1792 else {
1793 Py_ssize_t size_a_in_bits;
1794 /* Ensure overflow doesn't occur during computation of sz. */
1795 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1796 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001797 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001798 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001799 }
1800 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1801 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001802 /* Allow 1 character for a '-' sign. */
1803 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1804 }
1805 if (alternate) {
1806 /* 2 characters for prefix */
1807 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001808 }
1809
Victor Stinnerd3f08822012-05-29 12:57:52 +02001810 if (writer) {
1811 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1812 return -1;
1813 kind = writer->kind;
1814 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 }
1816 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001817 v = PyUnicode_New(sz, 'x');
1818 if (v == NULL)
1819 return -1;
1820 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001822
Victor Stinnerd3f08822012-05-29 12:57:52 +02001823#define WRITE_DIGITS(TYPE) \
1824 do { \
1825 if (writer) \
1826 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1827 else \
1828 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1829 \
1830 if (size_a == 0) { \
1831 *--p = '0'; \
1832 } \
1833 else { \
1834 /* JRH: special case for power-of-2 bases */ \
1835 twodigits accum = 0; \
1836 int accumbits = 0; /* # of bits in accum */ \
1837 Py_ssize_t i; \
1838 for (i = 0; i < size_a; ++i) { \
1839 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1840 accumbits += PyLong_SHIFT; \
1841 assert(accumbits >= bits); \
1842 do { \
1843 char cdigit; \
1844 cdigit = (char)(accum & (base - 1)); \
1845 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1846 *--p = cdigit; \
1847 accumbits -= bits; \
1848 accum >>= bits; \
1849 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1850 } \
1851 } \
1852 \
1853 if (alternate) { \
1854 if (base == 16) \
1855 *--p = 'x'; \
1856 else if (base == 8) \
1857 *--p = 'o'; \
1858 else /* (base == 2) */ \
1859 *--p = 'b'; \
1860 *--p = '0'; \
1861 } \
1862 if (negative) \
1863 *--p = '-'; \
1864 if (writer) \
1865 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1866 else \
1867 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1868 } while (0)
1869
1870 if (kind == PyUnicode_1BYTE_KIND) {
1871 Py_UCS1 *p;
1872 WRITE_DIGITS(Py_UCS1);
1873 }
1874 else if (kind == PyUnicode_2BYTE_KIND) {
1875 Py_UCS2 *p;
1876 WRITE_DIGITS(Py_UCS2);
1877 }
1878 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001879 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001880 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001881 WRITE_DIGITS(Py_UCS4);
1882 }
1883#undef WRITE_DIGITS
1884
1885 if (writer) {
1886 writer->pos += sz;
1887 }
1888 else {
1889 assert(_PyUnicode_CheckConsistency(v, 1));
1890 *p_output = v;
1891 }
1892 return 0;
1893}
1894
1895PyObject *
1896_PyLong_Format(PyObject *obj, int base)
1897{
1898 PyObject *str;
1899 int err;
1900 if (base == 10)
1901 err = long_to_decimal_string_internal(obj, &str, NULL);
1902 else
1903 err = long_format_binary(obj, base, 1, &str, NULL);
1904 if (err == -1)
1905 return NULL;
1906 return str;
1907}
1908
1909int
1910_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1911 PyObject *obj,
1912 int base, int alternate)
1913{
1914 if (base == 10)
1915 return long_to_decimal_string_internal(obj, NULL, writer);
1916 else
1917 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001918}
1919
Thomas Wouters477c8d52006-05-27 19:21:47 +00001920/* Table of digit values for 8-bit string -> integer conversion.
1921 * '0' maps to 0, ..., '9' maps to 9.
1922 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1923 * All other indices map to 37.
1924 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001925 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001926 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001927unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1929 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1930 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1931 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1932 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1933 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1934 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1935 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1936 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1937 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1938 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1939 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001944};
1945
1946/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001947 * 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 +03001948 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001949 * The point to this routine is that it takes time linear in the number of
1950 * string characters.
1951 */
1952static PyLongObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03001953long_from_binary_base(const char **str, int base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001954{
Serhiy Storchakac6792272013-10-19 21:03:34 +03001955 const char *p = *str;
1956 const char *start = p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 int bits_per_char;
1958 Py_ssize_t n;
1959 PyLongObject *z;
1960 twodigits accum;
1961 int bits_in_accum;
1962 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1965 n = base;
1966 for (bits_per_char = -1; n; ++bits_per_char)
1967 n >>= 1;
1968 /* n <- total # of bits needed, while setting p to end-of-string */
1969 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1970 ++p;
1971 *str = p;
1972 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1973 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1974 if (n / bits_per_char < p - start) {
1975 PyErr_SetString(PyExc_ValueError,
1976 "int string too large to convert");
1977 return NULL;
1978 }
1979 n = n / PyLong_SHIFT;
1980 z = _PyLong_New(n);
1981 if (z == NULL)
1982 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001983 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 * from least to most significant in both.
1985 */
1986 accum = 0;
1987 bits_in_accum = 0;
1988 pdigit = z->ob_digit;
1989 while (--p >= start) {
1990 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1991 assert(k >= 0 && k < base);
1992 accum |= (twodigits)k << bits_in_accum;
1993 bits_in_accum += bits_per_char;
1994 if (bits_in_accum >= PyLong_SHIFT) {
1995 *pdigit++ = (digit)(accum & PyLong_MASK);
1996 assert(pdigit - z->ob_digit <= n);
1997 accum >>= PyLong_SHIFT;
1998 bits_in_accum -= PyLong_SHIFT;
1999 assert(bits_in_accum < PyLong_SHIFT);
2000 }
2001 }
2002 if (bits_in_accum) {
2003 assert(bits_in_accum <= PyLong_SHIFT);
2004 *pdigit++ = (digit)accum;
2005 assert(pdigit - z->ob_digit <= n);
2006 }
2007 while (pdigit - z->ob_digit < n)
2008 *pdigit++ = 0;
2009 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002010}
2011
Serhiy Storchaka95949422013-08-27 19:40:23 +03002012/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002013 * ignored.
2014 *
2015 * If successful, a PyLong object will be returned and 'pend' will be pointing
2016 * to the first unused byte unless it's NULL.
2017 *
2018 * If unsuccessful, NULL will be returned.
2019 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002020PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002021PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002024 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 PyLongObject *z = NULL;
2026 PyObject *strobj;
2027 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if ((base != 0 && base < 2) || base > 36) {
2030 PyErr_SetString(PyExc_ValueError,
2031 "int() arg 2 must be >= 2 and <= 36");
2032 return NULL;
2033 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002034 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 str++;
2036 if (*str == '+')
2037 ++str;
2038 else if (*str == '-') {
2039 ++str;
2040 sign = -1;
2041 }
2042 if (base == 0) {
2043 if (str[0] != '0')
2044 base = 10;
2045 else if (str[1] == 'x' || str[1] == 'X')
2046 base = 16;
2047 else if (str[1] == 'o' || str[1] == 'O')
2048 base = 8;
2049 else if (str[1] == 'b' || str[1] == 'B')
2050 base = 2;
2051 else {
2052 /* "old" (C-style) octal literal, now invalid.
2053 it might still be zero though */
2054 error_if_nonzero = 1;
2055 base = 10;
2056 }
2057 }
2058 if (str[0] == '0' &&
2059 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2060 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2061 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2062 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 start = str;
2065 if ((base & (base - 1)) == 0)
2066 z = long_from_binary_base(&str, base);
2067 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002068/***
2069Binary bases can be converted in time linear in the number of digits, because
2070Python's representation base is binary. Other bases (including decimal!) use
2071the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002072
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073First some math: the largest integer that can be expressed in N base-B digits
2074is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2075case number of Python digits needed to hold it is the smallest integer n s.t.
2076
2077 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2078 BASE**n >= B**N [taking logs to base BASE]
2079 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2080
2081The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002082this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002083and the result is computed into it.
2084
2085The input string is actually treated as being in base base**i (i.e., i digits
2086are processed at a time), where two more static arrays hold:
2087
2088 convwidth_base[base] = the largest integer i such that base**i <= BASE
2089 convmultmax_base[base] = base ** convwidth_base[base]
2090
2091The first of these is the largest i such that i consecutive input digits
2092must fit in a single Python digit. The second is effectively the input
2093base we're really using.
2094
2095Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2096convmultmax_base[base], the result is "simply"
2097
2098 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2099
2100where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002101
2102Error analysis: as above, the number of Python digits `n` needed is worst-
2103case
2104
2105 n >= N * log(B)/log(BASE)
2106
2107where `N` is the number of input digits in base `B`. This is computed via
2108
2109 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2110
2111below. Two numeric concerns are how much space this can waste, and whether
2112the computed result can be too small. To be concrete, assume BASE = 2**15,
2113which is the default (and it's unlikely anyone changes that).
2114
2115Waste isn't a problem: provided the first input digit isn't 0, the difference
2116between the worst-case input with N digits and the smallest input with N
2117digits is about a factor of B, but B is small compared to BASE so at most
2118one allocated Python digit can remain unused on that count. If
2119N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2120and adding 1 returns a result 1 larger than necessary. However, that can't
2121happen: whenever B is a power of 2, long_from_binary_base() is called
2122instead, and it's impossible for B**i to be an integer power of 2**15 when
2123B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2124an exact integer when B is not a power of 2, since B**i has a prime factor
2125other than 2 in that case, but (2**15)**j's only prime factor is 2).
2126
2127The computed result can be too small if the true value of N*log(B)/log(BASE)
2128is a little bit larger than an exact integer, but due to roundoff errors (in
2129computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2130yields a numeric result a little less than that integer. Unfortunately, "how
2131close can a transcendental function get to an integer over some range?"
2132questions are generally theoretically intractable. Computer analysis via
2133continued fractions is practical: expand log(B)/log(BASE) via continued
2134fractions, giving a sequence i/j of "the best" rational approximations. Then
2135j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2136we can get very close to being in trouble, but very rarely. For example,
213776573 is a denominator in one of the continued-fraction approximations to
2138log(10)/log(2**15), and indeed:
2139
2140 >>> log(10)/log(2**15)*76573
2141 16958.000000654003
2142
2143is very close to an integer. If we were working with IEEE single-precision,
2144rounding errors could kill us. Finding worst cases in IEEE double-precision
2145requires better-than-double-precision log() functions, and Tim didn't bother.
2146Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002147new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002148This should happen extremely rarely, and in fact I don't have a test case
2149that triggers it(!). Instead the code was tested by artificially allocating
2150just 1 digit at the start, so that the copying code was exercised for every
2151digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002152***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002153 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 Py_ssize_t size_z;
2155 int i;
2156 int convwidth;
2157 twodigits convmultmax, convmult;
2158 digit *pz, *pzstop;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002159 const char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 static double log_base_BASE[37] = {0.0e0,};
2162 static int convwidth_base[37] = {0,};
2163 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (log_base_BASE[base] == 0.0) {
2166 twodigits convmax = base;
2167 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002168
Mark Dickinson22b20182010-05-10 21:27:53 +00002169 log_base_BASE[base] = (log((double)base) /
2170 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 for (;;) {
2172 twodigits next = convmax * base;
2173 if (next > PyLong_BASE)
2174 break;
2175 convmax = next;
2176 ++i;
2177 }
2178 convmultmax_base[base] = convmax;
2179 assert(i > 0);
2180 convwidth_base[base] = i;
2181 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 /* Find length of the string of numeric characters. */
2184 scan = str;
2185 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2186 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002187
Serhiy Storchaka95949422013-08-27 19:40:23 +03002188 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 * integer with this base and length. Note that there's no
2190 * need to initialize z->ob_digit -- no slot is read up before
2191 * being stored into.
2192 */
2193 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2194 /* Uncomment next line to test exceedingly rare copy code */
2195 /* size_z = 1; */
2196 assert(size_z > 0);
2197 z = _PyLong_New(size_z);
2198 if (z == NULL)
2199 return NULL;
2200 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 /* `convwidth` consecutive input digits are treated as a single
2203 * digit in base `convmultmax`.
2204 */
2205 convwidth = convwidth_base[base];
2206 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 /* Work ;-) */
2209 while (str < scan) {
2210 /* grab up to convwidth digits from the input string */
2211 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2212 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2213 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002214 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 assert(c < PyLong_BASE);
2216 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 convmult = convmultmax;
2219 /* Calculate the shift only if we couldn't get
2220 * convwidth digits.
2221 */
2222 if (i != convwidth) {
2223 convmult = base;
2224 for ( ; i > 1; --i)
2225 convmult *= base;
2226 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 /* Multiply z by convmult, and add c. */
2229 pz = z->ob_digit;
2230 pzstop = pz + Py_SIZE(z);
2231 for (; pz < pzstop; ++pz) {
2232 c += (twodigits)*pz * convmult;
2233 *pz = (digit)(c & PyLong_MASK);
2234 c >>= PyLong_SHIFT;
2235 }
2236 /* carry off the current end? */
2237 if (c) {
2238 assert(c < PyLong_BASE);
2239 if (Py_SIZE(z) < size_z) {
2240 *pz = (digit)c;
2241 ++Py_SIZE(z);
2242 }
2243 else {
2244 PyLongObject *tmp;
2245 /* Extremely rare. Get more space. */
2246 assert(Py_SIZE(z) == size_z);
2247 tmp = _PyLong_New(size_z + 1);
2248 if (tmp == NULL) {
2249 Py_DECREF(z);
2250 return NULL;
2251 }
2252 memcpy(tmp->ob_digit,
2253 z->ob_digit,
2254 sizeof(digit) * size_z);
2255 Py_DECREF(z);
2256 z = tmp;
2257 z->ob_digit[size_z] = (digit)c;
2258 ++size_z;
2259 }
2260 }
2261 }
2262 }
2263 if (z == NULL)
2264 return NULL;
2265 if (error_if_nonzero) {
2266 /* reset the base to 0, else the exception message
2267 doesn't make too much sense */
2268 base = 0;
2269 if (Py_SIZE(z) != 0)
2270 goto onError;
2271 /* there might still be other problems, therefore base
2272 remains zero here for the same reason */
2273 }
2274 if (str == start)
2275 goto onError;
2276 if (sign < 0)
2277 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002278 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 str++;
2280 if (*str != '\0')
2281 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002283 z = maybe_small_long(z);
2284 if (z == NULL)
2285 return NULL;
2286 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002287 *pend = (char *)str;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002288 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002289
Mark Dickinson22b20182010-05-10 21:27:53 +00002290 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002291 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002292 *pend = (char *)str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_XDECREF(z);
2294 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2295 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2296 if (strobj == NULL)
2297 return NULL;
2298 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002299 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 base, strobj);
2301 Py_DECREF(strobj);
2302 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002303}
2304
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002305/* Since PyLong_FromString doesn't have a length parameter,
2306 * check here for possible NULs in the string.
2307 *
2308 * Reports an invalid literal as a bytes object.
2309 */
2310PyObject *
2311_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2312{
2313 PyObject *result, *strobj;
2314 char *end = NULL;
2315
2316 result = PyLong_FromString((char*)s, &end, base);
2317 if (end == NULL || (result != NULL && end == s + len))
2318 return result;
2319 Py_XDECREF(result);
2320 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2321 if (strobj != NULL) {
2322 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002323 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002324 base, strobj);
2325 Py_DECREF(strobj);
2326 }
2327 return NULL;
2328}
2329
Guido van Rossum9e896b32000-04-05 20:11:21 +00002330PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002331PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002332{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002333 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2334 if (unicode == NULL)
2335 return NULL;
2336 v = PyLong_FromUnicodeObject(unicode, base);
2337 Py_DECREF(unicode);
2338 return v;
2339}
2340
2341PyObject *
2342PyLong_FromUnicodeObject(PyObject *u, int base)
2343{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002344 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002345 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002346 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002348 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002349 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002351 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002352 if (buffer == NULL) {
2353 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002354 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2355 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002357 else {
2358 result = PyLong_FromString(buffer, &end, base);
2359 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2360 Py_DECREF(asciidig);
2361 return result;
2362 }
2363 Py_DECREF(asciidig);
2364 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002365 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002366 PyErr_Format(PyExc_ValueError,
2367 "invalid literal for int() with base %d: %.200R",
2368 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002369 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002370}
2371
Tim Peters9f688bf2000-07-07 15:53:28 +00002372/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002373static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002375static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376
Serhiy Storchaka95949422013-08-27 19:40:23 +03002377/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002378
Guido van Rossume32e0141992-01-19 16:31:05 +00002379static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002380long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2384 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 if (size_b == 0) {
2387 PyErr_SetString(PyExc_ZeroDivisionError,
2388 "integer division or modulo by zero");
2389 return -1;
2390 }
2391 if (size_a < size_b ||
2392 (size_a == size_b &&
2393 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2394 /* |a| < |b|. */
2395 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2396 if (*pdiv == NULL)
2397 return -1;
2398 Py_INCREF(a);
2399 *prem = (PyLongObject *) a;
2400 return 0;
2401 }
2402 if (size_b == 1) {
2403 digit rem = 0;
2404 z = divrem1(a, b->ob_digit[0], &rem);
2405 if (z == NULL)
2406 return -1;
2407 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2408 if (*prem == NULL) {
2409 Py_DECREF(z);
2410 return -1;
2411 }
2412 }
2413 else {
2414 z = x_divrem(a, b, prem);
2415 if (z == NULL)
2416 return -1;
2417 }
2418 /* Set the signs.
2419 The quotient z has the sign of a*b;
2420 the remainder r has the sign of a,
2421 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002422 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2423 _PyLong_Negate(&z);
2424 if (z == NULL) {
2425 Py_CLEAR(*prem);
2426 return -1;
2427 }
2428 }
2429 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2430 _PyLong_Negate(prem);
2431 if (*prem == NULL) {
2432 Py_DECREF(z);
2433 Py_CLEAR(*prem);
2434 return -1;
2435 }
2436 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 *pdiv = maybe_small_long(z);
2438 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002439}
2440
Serhiy Storchaka95949422013-08-27 19:40:23 +03002441/* Unsigned int division with remainder -- the algorithm. The arguments v1
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002442 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002443
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002444static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002445x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 PyLongObject *v, *w, *a;
2448 Py_ssize_t i, k, size_v, size_w;
2449 int d;
2450 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2451 twodigits vv;
2452 sdigit zhi;
2453 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2456 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2457 handle the special case when the initial estimate q for a quotient
2458 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2459 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 /* allocate space; w will also be used to hold the final remainder */
2462 size_v = ABS(Py_SIZE(v1));
2463 size_w = ABS(Py_SIZE(w1));
2464 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2465 v = _PyLong_New(size_v+1);
2466 if (v == NULL) {
2467 *prem = NULL;
2468 return NULL;
2469 }
2470 w = _PyLong_New(size_w);
2471 if (w == NULL) {
2472 Py_DECREF(v);
2473 *prem = NULL;
2474 return NULL;
2475 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2478 shift v1 left by the same amount. Results go into w and v. */
2479 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2480 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2481 assert(carry == 0);
2482 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2483 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2484 v->ob_digit[size_v] = carry;
2485 size_v++;
2486 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2489 at most (and usually exactly) k = size_v - size_w digits. */
2490 k = size_v - size_w;
2491 assert(k >= 0);
2492 a = _PyLong_New(k);
2493 if (a == NULL) {
2494 Py_DECREF(w);
2495 Py_DECREF(v);
2496 *prem = NULL;
2497 return NULL;
2498 }
2499 v0 = v->ob_digit;
2500 w0 = w->ob_digit;
2501 wm1 = w0[size_w-1];
2502 wm2 = w0[size_w-2];
2503 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2504 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2505 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002508 Py_DECREF(a);
2509 Py_DECREF(w);
2510 Py_DECREF(v);
2511 *prem = NULL;
2512 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002513 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 /* estimate quotient digit q; may overestimate by 1 (rare) */
2516 vtop = vk[size_w];
2517 assert(vtop <= wm1);
2518 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2519 q = (digit)(vv / wm1);
2520 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2521 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2522 | vk[size_w-2])) {
2523 --q;
2524 r += wm1;
2525 if (r >= PyLong_BASE)
2526 break;
2527 }
2528 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2531 zhi = 0;
2532 for (i = 0; i < size_w; ++i) {
2533 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2534 -PyLong_BASE * q <= z < PyLong_BASE */
2535 z = (sdigit)vk[i] + zhi -
2536 (stwodigits)q * (stwodigits)w0[i];
2537 vk[i] = (digit)z & PyLong_MASK;
2538 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002539 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 /* add w back if q was too large (this branch taken rarely) */
2543 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2544 if ((sdigit)vtop + zhi < 0) {
2545 carry = 0;
2546 for (i = 0; i < size_w; ++i) {
2547 carry += vk[i] + w0[i];
2548 vk[i] = carry & PyLong_MASK;
2549 carry >>= PyLong_SHIFT;
2550 }
2551 --q;
2552 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 /* store quotient digit */
2555 assert(q < PyLong_BASE);
2556 *--ak = q;
2557 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 /* unshift remainder; we reuse w to store the result */
2560 carry = v_rshift(w0, v0, size_w, d);
2561 assert(carry==0);
2562 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 *prem = long_normalize(w);
2565 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002566}
2567
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002568/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2569 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2570 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2571 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2572 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2573 -1.0. */
2574
2575/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2576#if DBL_MANT_DIG == 53
2577#define EXP2_DBL_MANT_DIG 9007199254740992.0
2578#else
2579#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2580#endif
2581
2582double
2583_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2586 /* See below for why x_digits is always large enough. */
2587 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2588 double dx;
2589 /* Correction term for round-half-to-even rounding. For a digit x,
2590 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2591 multiple of 4, rounding ties to a multiple of 8. */
2592 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 a_size = ABS(Py_SIZE(a));
2595 if (a_size == 0) {
2596 /* Special case for 0: significand 0.0, exponent 0. */
2597 *e = 0;
2598 return 0.0;
2599 }
2600 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2601 /* The following is an overflow-free version of the check
2602 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2603 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2604 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2605 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002606 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2610 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Number of digits needed for result: write // for floor division.
2613 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2622 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2625 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2626 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 in both cases.
2633 */
2634 if (a_bits <= DBL_MANT_DIG + 2) {
2635 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2636 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2637 x_size = 0;
2638 while (x_size < shift_digits)
2639 x_digits[x_size++] = 0;
2640 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2641 (int)shift_bits);
2642 x_size += a_size;
2643 x_digits[x_size++] = rem;
2644 }
2645 else {
2646 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2647 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2648 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2649 a_size - shift_digits, (int)shift_bits);
2650 x_size = a_size - shift_digits;
2651 /* For correct rounding below, we need the least significant
2652 bit of x to be 'sticky' for this shift: if any of the bits
2653 shifted out was nonzero, we set the least significant bit
2654 of x. */
2655 if (rem)
2656 x_digits[0] |= 1;
2657 else
2658 while (shift_digits > 0)
2659 if (a->ob_digit[--shift_digits]) {
2660 x_digits[0] |= 1;
2661 break;
2662 }
2663 }
Victor Stinner63941882011-09-29 00:42:28 +02002664 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 /* Round, and convert to double. */
2667 x_digits[0] += half_even_correction[x_digits[0] & 7];
2668 dx = x_digits[--x_size];
2669 while (x_size > 0)
2670 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* Rescale; make correction if result is 1.0. */
2673 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2674 if (dx == 1.0) {
2675 if (a_bits == PY_SSIZE_T_MAX)
2676 goto overflow;
2677 dx = 0.5;
2678 a_bits += 1;
2679 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 *e = a_bits;
2682 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002683
2684 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 /* exponent > PY_SSIZE_T_MAX */
2686 PyErr_SetString(PyExc_OverflowError,
2687 "huge integer: number of bits overflows a Py_ssize_t");
2688 *e = 0;
2689 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002690}
2691
Serhiy Storchaka95949422013-08-27 19:40:23 +03002692/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002693 using the round-half-to-even rule in the case of a tie. */
2694
2695double
2696PyLong_AsDouble(PyObject *v)
2697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 Py_ssize_t exponent;
2699 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002700
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002701 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 PyErr_BadInternalCall();
2703 return -1.0;
2704 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002705 if (!PyLong_Check(v)) {
2706 PyErr_SetString(PyExc_TypeError, "an integer is required");
2707 return -1.0;
2708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2710 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2711 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002712 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return -1.0;
2714 }
2715 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002716}
2717
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002718/* Methods */
2719
2720static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002721long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002724}
2725
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002726static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002727long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (Py_SIZE(a) != Py_SIZE(b)) {
2732 sign = Py_SIZE(a) - Py_SIZE(b);
2733 }
2734 else {
2735 Py_ssize_t i = ABS(Py_SIZE(a));
2736 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2737 ;
2738 if (i < 0)
2739 sign = 0;
2740 else {
2741 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2742 if (Py_SIZE(a) < 0)
2743 sign = -sign;
2744 }
2745 }
2746 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002747}
2748
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002749#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002751
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002752static PyObject *
2753long_richcompare(PyObject *self, PyObject *other, int op)
2754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 int result;
2756 PyObject *v;
2757 CHECK_BINOP(self, other);
2758 if (self == other)
2759 result = 0;
2760 else
2761 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2762 /* Convert the return value to a Boolean */
2763 switch (op) {
2764 case Py_EQ:
2765 v = TEST_COND(result == 0);
2766 break;
2767 case Py_NE:
2768 v = TEST_COND(result != 0);
2769 break;
2770 case Py_LE:
2771 v = TEST_COND(result <= 0);
2772 break;
2773 case Py_GE:
2774 v = TEST_COND(result >= 0);
2775 break;
2776 case Py_LT:
2777 v = TEST_COND(result == -1);
2778 break;
2779 case Py_GT:
2780 v = TEST_COND(result == 1);
2781 break;
2782 default:
2783 PyErr_BadArgument();
2784 return NULL;
2785 }
2786 Py_INCREF(v);
2787 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002788}
2789
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002790static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002791long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002792{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002793 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 Py_ssize_t i;
2795 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 i = Py_SIZE(v);
2798 switch(i) {
2799 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2800 case 0: return 0;
2801 case 1: return v->ob_digit[0];
2802 }
2803 sign = 1;
2804 x = 0;
2805 if (i < 0) {
2806 sign = -1;
2807 i = -(i);
2808 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002810 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2811 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2812 _PyHASH_MODULUS.
2813
2814 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2815 amounts to a rotation of the bits of x. To see this, write
2816
2817 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2818
2819 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2820 PyLong_SHIFT bits of x (those that are shifted out of the
2821 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2822 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2823 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2824 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2825 congruent to y modulo _PyHASH_MODULUS. So
2826
2827 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2828
2829 The right-hand side is just the result of rotating the
2830 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2831 not all _PyHASH_BITS bits of x are 1s, the same is true
2832 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2833 the reduction of x*2**PyLong_SHIFT modulo
2834 _PyHASH_MODULUS. */
2835 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2836 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002838 if (x >= _PyHASH_MODULUS)
2839 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 }
2841 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002842 if (x == (Py_uhash_t)-1)
2843 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002844 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002845}
2846
2847
Serhiy Storchaka95949422013-08-27 19:40:23 +03002848/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002849
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002850static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002851x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2854 PyLongObject *z;
2855 Py_ssize_t i;
2856 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 /* Ensure a is the larger of the two: */
2859 if (size_a < size_b) {
2860 { PyLongObject *temp = a; a = b; b = temp; }
2861 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002862 size_a = size_b;
2863 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 }
2865 z = _PyLong_New(size_a+1);
2866 if (z == NULL)
2867 return NULL;
2868 for (i = 0; i < size_b; ++i) {
2869 carry += a->ob_digit[i] + b->ob_digit[i];
2870 z->ob_digit[i] = carry & PyLong_MASK;
2871 carry >>= PyLong_SHIFT;
2872 }
2873 for (; i < size_a; ++i) {
2874 carry += a->ob_digit[i];
2875 z->ob_digit[i] = carry & PyLong_MASK;
2876 carry >>= PyLong_SHIFT;
2877 }
2878 z->ob_digit[i] = carry;
2879 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002880}
2881
2882/* Subtract the absolute values of two integers. */
2883
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002884static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002885x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002886{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2888 PyLongObject *z;
2889 Py_ssize_t i;
2890 int sign = 1;
2891 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 /* Ensure a is the larger of the two: */
2894 if (size_a < size_b) {
2895 sign = -1;
2896 { PyLongObject *temp = a; a = b; b = temp; }
2897 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002898 size_a = size_b;
2899 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 }
2901 else if (size_a == size_b) {
2902 /* Find highest digit where a and b differ: */
2903 i = size_a;
2904 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2905 ;
2906 if (i < 0)
2907 return (PyLongObject *)PyLong_FromLong(0);
2908 if (a->ob_digit[i] < b->ob_digit[i]) {
2909 sign = -1;
2910 { PyLongObject *temp = a; a = b; b = temp; }
2911 }
2912 size_a = size_b = i+1;
2913 }
2914 z = _PyLong_New(size_a);
2915 if (z == NULL)
2916 return NULL;
2917 for (i = 0; i < size_b; ++i) {
2918 /* The following assumes unsigned arithmetic
2919 works module 2**N for some N>PyLong_SHIFT. */
2920 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2921 z->ob_digit[i] = borrow & PyLong_MASK;
2922 borrow >>= PyLong_SHIFT;
2923 borrow &= 1; /* Keep only one sign bit */
2924 }
2925 for (; i < size_a; ++i) {
2926 borrow = a->ob_digit[i] - borrow;
2927 z->ob_digit[i] = borrow & PyLong_MASK;
2928 borrow >>= PyLong_SHIFT;
2929 borrow &= 1; /* Keep only one sign bit */
2930 }
2931 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002932 if (sign < 0) {
2933 _PyLong_Negate(&z);
2934 if (z == NULL)
2935 return NULL;
2936 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002938}
2939
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002940static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002941long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2948 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2949 MEDIUM_VALUE(b));
2950 return result;
2951 }
2952 if (Py_SIZE(a) < 0) {
2953 if (Py_SIZE(b) < 0) {
2954 z = x_add(a, b);
2955 if (z != NULL && Py_SIZE(z) != 0)
2956 Py_SIZE(z) = -(Py_SIZE(z));
2957 }
2958 else
2959 z = x_sub(b, a);
2960 }
2961 else {
2962 if (Py_SIZE(b) < 0)
2963 z = x_sub(a, b);
2964 else
2965 z = x_add(a, b);
2966 }
2967 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002968}
2969
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002970static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002971long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2978 PyObject* r;
2979 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2980 return r;
2981 }
2982 if (Py_SIZE(a) < 0) {
2983 if (Py_SIZE(b) < 0)
2984 z = x_sub(a, b);
2985 else
2986 z = x_add(a, b);
2987 if (z != NULL && Py_SIZE(z) != 0)
2988 Py_SIZE(z) = -(Py_SIZE(z));
2989 }
2990 else {
2991 if (Py_SIZE(b) < 0)
2992 z = x_add(a, b);
2993 else
2994 z = x_sub(a, b);
2995 }
2996 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002997}
2998
Tim Peters5af4e6c2002-08-12 02:31:19 +00002999/* Grade school multiplication, ignoring the signs.
3000 * Returns the absolute value of the product, or NULL if error.
3001 */
3002static PyLongObject *
3003x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 PyLongObject *z;
3006 Py_ssize_t size_a = ABS(Py_SIZE(a));
3007 Py_ssize_t size_b = ABS(Py_SIZE(b));
3008 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 z = _PyLong_New(size_a + size_b);
3011 if (z == NULL)
3012 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3015 if (a == b) {
3016 /* Efficient squaring per HAC, Algorithm 14.16:
3017 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3018 * Gives slightly less than a 2x speedup when a == b,
3019 * via exploiting that each entry in the multiplication
3020 * pyramid appears twice (except for the size_a squares).
3021 */
3022 for (i = 0; i < size_a; ++i) {
3023 twodigits carry;
3024 twodigits f = a->ob_digit[i];
3025 digit *pz = z->ob_digit + (i << 1);
3026 digit *pa = a->ob_digit + i + 1;
3027 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003030 Py_DECREF(z);
3031 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003032 });
Tim Peters0973b992004-08-29 22:16:50 +00003033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 carry = *pz + f * f;
3035 *pz++ = (digit)(carry & PyLong_MASK);
3036 carry >>= PyLong_SHIFT;
3037 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003039 /* Now f is added in twice in each column of the
3040 * pyramid it appears. Same as adding f<<1 once.
3041 */
3042 f <<= 1;
3043 while (pa < paend) {
3044 carry += *pz + *pa++ * f;
3045 *pz++ = (digit)(carry & PyLong_MASK);
3046 carry >>= PyLong_SHIFT;
3047 assert(carry <= (PyLong_MASK << 1));
3048 }
3049 if (carry) {
3050 carry += *pz;
3051 *pz++ = (digit)(carry & PyLong_MASK);
3052 carry >>= PyLong_SHIFT;
3053 }
3054 if (carry)
3055 *pz += (digit)(carry & PyLong_MASK);
3056 assert((carry >> PyLong_SHIFT) == 0);
3057 }
3058 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003059 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 for (i = 0; i < size_a; ++i) {
3061 twodigits carry = 0;
3062 twodigits f = a->ob_digit[i];
3063 digit *pz = z->ob_digit + i;
3064 digit *pb = b->ob_digit;
3065 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003068 Py_DECREF(z);
3069 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003070 });
Tim Peters0973b992004-08-29 22:16:50 +00003071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 while (pb < pbend) {
3073 carry += *pz + *pb++ * f;
3074 *pz++ = (digit)(carry & PyLong_MASK);
3075 carry >>= PyLong_SHIFT;
3076 assert(carry <= PyLong_MASK);
3077 }
3078 if (carry)
3079 *pz += (digit)(carry & PyLong_MASK);
3080 assert((carry >> PyLong_SHIFT) == 0);
3081 }
3082 }
3083 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003084}
3085
3086/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003087 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003088 split, and sets low and high such that abs(n) == (high << size) + low,
3089 viewing the shift as being by digits. The sign bit is ignored, and
3090 the return values are >= 0.
3091 Returns 0 on success, -1 on failure.
3092*/
3093static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003094kmul_split(PyLongObject *n,
3095 Py_ssize_t size,
3096 PyLongObject **high,
3097 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 PyLongObject *hi, *lo;
3100 Py_ssize_t size_lo, size_hi;
3101 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003102
Victor Stinner640c35c2013-06-04 23:14:37 +02003103 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 if ((hi = _PyLong_New(size_hi)) == NULL)
3107 return -1;
3108 if ((lo = _PyLong_New(size_lo)) == NULL) {
3109 Py_DECREF(hi);
3110 return -1;
3111 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3114 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 *high = long_normalize(hi);
3117 *low = long_normalize(lo);
3118 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003119}
3120
Tim Peters60004642002-08-12 22:01:34 +00003121static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3122
Tim Peters5af4e6c2002-08-12 02:31:19 +00003123/* Karatsuba multiplication. Ignores the input signs, and returns the
3124 * absolute value of the product (or NULL if error).
3125 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3126 */
3127static PyLongObject *
3128k_mul(PyLongObject *a, PyLongObject *b)
3129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 Py_ssize_t asize = ABS(Py_SIZE(a));
3131 Py_ssize_t bsize = ABS(Py_SIZE(b));
3132 PyLongObject *ah = NULL;
3133 PyLongObject *al = NULL;
3134 PyLongObject *bh = NULL;
3135 PyLongObject *bl = NULL;
3136 PyLongObject *ret = NULL;
3137 PyLongObject *t1, *t2, *t3;
3138 Py_ssize_t shift; /* the number of digits we split off */
3139 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3142 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3143 * Then the original product is
3144 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3145 * By picking X to be a power of 2, "*X" is just shifting, and it's
3146 * been reduced to 3 multiplies on numbers half the size.
3147 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 /* We want to split based on the larger number; fiddle so that b
3150 * is largest.
3151 */
3152 if (asize > bsize) {
3153 t1 = a;
3154 a = b;
3155 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 i = asize;
3158 asize = bsize;
3159 bsize = i;
3160 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 /* Use gradeschool math when either number is too small. */
3163 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3164 if (asize <= i) {
3165 if (asize == 0)
3166 return (PyLongObject *)PyLong_FromLong(0);
3167 else
3168 return x_mul(a, b);
3169 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 /* If a is small compared to b, splitting on b gives a degenerate
3172 * case with ah==0, and Karatsuba may be (even much) less efficient
3173 * than "grade school" then. However, we can still win, by viewing
3174 * b as a string of "big digits", each of width a->ob_size. That
3175 * leads to a sequence of balanced calls to k_mul.
3176 */
3177 if (2 * asize <= bsize)
3178 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 /* Split a & b into hi & lo pieces. */
3181 shift = bsize >> 1;
3182 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3183 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 if (a == b) {
3186 bh = ah;
3187 bl = al;
3188 Py_INCREF(bh);
3189 Py_INCREF(bl);
3190 }
3191 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* The plan:
3194 * 1. Allocate result space (asize + bsize digits: that's always
3195 * enough).
3196 * 2. Compute ah*bh, and copy into result at 2*shift.
3197 * 3. Compute al*bl, and copy into result at 0. Note that this
3198 * can't overlap with #2.
3199 * 4. Subtract al*bl from the result, starting at shift. This may
3200 * underflow (borrow out of the high digit), but we don't care:
3201 * we're effectively doing unsigned arithmetic mod
3202 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3203 * borrows and carries out of the high digit can be ignored.
3204 * 5. Subtract ah*bh from the result, starting at shift.
3205 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3206 * at shift.
3207 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 /* 1. Allocate result space. */
3210 ret = _PyLong_New(asize + bsize);
3211 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003212#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 /* Fill with trash, to catch reference to uninitialized digits. */
3214 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003215#endif
Tim Peters44121a62002-08-12 06:17:58 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3218 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3219 assert(Py_SIZE(t1) >= 0);
3220 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3221 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3222 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 /* Zero-out the digits higher than the ah*bh copy. */
3225 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3226 if (i)
3227 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3228 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003230 /* 3. t2 <- al*bl, and copy into the low digits. */
3231 if ((t2 = k_mul(al, bl)) == NULL) {
3232 Py_DECREF(t1);
3233 goto fail;
3234 }
3235 assert(Py_SIZE(t2) >= 0);
3236 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3237 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 /* Zero out remaining digits. */
3240 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3241 if (i)
3242 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3245 * because it's fresher in cache.
3246 */
3247 i = Py_SIZE(ret) - shift; /* # digits after shift */
3248 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3249 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3252 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003254 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3255 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3256 Py_DECREF(ah);
3257 Py_DECREF(al);
3258 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003260 if (a == b) {
3261 t2 = t1;
3262 Py_INCREF(t2);
3263 }
3264 else if ((t2 = x_add(bh, bl)) == NULL) {
3265 Py_DECREF(t1);
3266 goto fail;
3267 }
3268 Py_DECREF(bh);
3269 Py_DECREF(bl);
3270 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 t3 = k_mul(t1, t2);
3273 Py_DECREF(t1);
3274 Py_DECREF(t2);
3275 if (t3 == NULL) goto fail;
3276 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 /* Add t3. It's not obvious why we can't run out of room here.
3279 * See the (*) comment after this function.
3280 */
3281 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3282 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003285
Mark Dickinson22b20182010-05-10 21:27:53 +00003286 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 Py_XDECREF(ret);
3288 Py_XDECREF(ah);
3289 Py_XDECREF(al);
3290 Py_XDECREF(bh);
3291 Py_XDECREF(bl);
3292 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003293}
3294
Tim Petersd6974a52002-08-13 20:37:51 +00003295/* (*) Why adding t3 can't "run out of room" above.
3296
Tim Petersab86c2b2002-08-15 20:06:00 +00003297Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3298to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003299
Tim Petersab86c2b2002-08-15 20:06:00 +000033001. For any integer i, i = c(i/2) + f(i/2). In particular,
3301 bsize = c(bsize/2) + f(bsize/2).
33022. shift = f(bsize/2)
33033. asize <= bsize
33044. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3305 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003306
Tim Petersab86c2b2002-08-15 20:06:00 +00003307We allocated asize + bsize result digits, and add t3 into them at an offset
3308of shift. This leaves asize+bsize-shift allocated digit positions for t3
3309to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3310asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003311
Tim Petersab86c2b2002-08-15 20:06:00 +00003312bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3313at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003314
Tim Petersab86c2b2002-08-15 20:06:00 +00003315If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3316digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3317most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003318
Tim Petersab86c2b2002-08-15 20:06:00 +00003319The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003320
Tim Petersab86c2b2002-08-15 20:06:00 +00003321 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003322
Tim Petersab86c2b2002-08-15 20:06:00 +00003323and we have asize + c(bsize/2) available digit positions. We need to show
3324this is always enough. An instance of c(bsize/2) cancels out in both, so
3325the question reduces to whether asize digits is enough to hold
3326(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3327then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3328asize 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 +00003329digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003330asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003331c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3332is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3333bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003334
Tim Peters48d52c02002-08-14 17:07:32 +00003335Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3336clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3337ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003338*/
3339
Tim Peters60004642002-08-12 22:01:34 +00003340/* b has at least twice the digits of a, and a is big enough that Karatsuba
3341 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3342 * of slices, each with a->ob_size digits, and multiply the slices by a,
3343 * one at a time. This gives k_mul balanced inputs to work with, and is
3344 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003345 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003346 * single-width slice overlap between successive partial sums).
3347 */
3348static PyLongObject *
3349k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 const Py_ssize_t asize = ABS(Py_SIZE(a));
3352 Py_ssize_t bsize = ABS(Py_SIZE(b));
3353 Py_ssize_t nbdone; /* # of b digits already multiplied */
3354 PyLongObject *ret;
3355 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 assert(asize > KARATSUBA_CUTOFF);
3358 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* Allocate result space, and zero it out. */
3361 ret = _PyLong_New(asize + bsize);
3362 if (ret == NULL)
3363 return NULL;
3364 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 /* Successive slices of b are copied into bslice. */
3367 bslice = _PyLong_New(asize);
3368 if (bslice == NULL)
3369 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 nbdone = 0;
3372 while (bsize > 0) {
3373 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003374 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 /* Multiply the next slice of b by a. */
3377 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3378 nbtouse * sizeof(digit));
3379 Py_SIZE(bslice) = nbtouse;
3380 product = k_mul(a, bslice);
3381 if (product == NULL)
3382 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* Add into result. */
3385 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3386 product->ob_digit, Py_SIZE(product));
3387 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 bsize -= nbtouse;
3390 nbdone += nbtouse;
3391 }
Tim Peters60004642002-08-12 22:01:34 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 Py_DECREF(bslice);
3394 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003395
Mark Dickinson22b20182010-05-10 21:27:53 +00003396 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 Py_DECREF(ret);
3398 Py_XDECREF(bslice);
3399 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003400}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003401
3402static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003403long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 /* fast path for single-digit multiplication */
3410 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3411 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003412#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003414#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 /* if we don't have long long then we're almost certainly
3416 using 15-bit digits, so v will fit in a long. In the
3417 unlikely event that we're using 30-bit digits on a platform
3418 without long long, a large v will just cause us to fall
3419 through to the general multiplication code below. */
3420 if (v >= LONG_MIN && v <= LONG_MAX)
3421 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003422#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 z = k_mul(a, b);
3426 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003427 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3428 _PyLong_Negate(&z);
3429 if (z == NULL)
3430 return NULL;
3431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003433}
3434
Guido van Rossume32e0141992-01-19 16:31:05 +00003435/* The / and % operators are now defined in terms of divmod().
3436 The expression a mod b has the value a - b*floor(a/b).
3437 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003438 |a| by |b|, with the sign of a. This is also expressed
3439 as a - b*trunc(a/b), if trunc truncates towards zero.
3440 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 a b a rem b a mod b
3442 13 10 3 3
3443 -13 10 -3 7
3444 13 -10 3 -7
3445 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003446 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003447 have different signs. We then subtract one from the 'div'
3448 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003449
Tim Peters47e52ee2004-08-30 02:44:38 +00003450/* Compute
3451 * *pdiv, *pmod = divmod(v, w)
3452 * NULL can be passed for pdiv or pmod, in which case that part of
3453 * the result is simply thrown away. The caller owns a reference to
3454 * each of these it requests (does not pass NULL for).
3455 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003456static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003457l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003462 if (long_divrem(v, w, &div, &mod) < 0)
3463 return -1;
3464 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3465 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3466 PyLongObject *temp;
3467 PyLongObject *one;
3468 temp = (PyLongObject *) long_add(mod, w);
3469 Py_DECREF(mod);
3470 mod = temp;
3471 if (mod == NULL) {
3472 Py_DECREF(div);
3473 return -1;
3474 }
3475 one = (PyLongObject *) PyLong_FromLong(1L);
3476 if (one == NULL ||
3477 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3478 Py_DECREF(mod);
3479 Py_DECREF(div);
3480 Py_XDECREF(one);
3481 return -1;
3482 }
3483 Py_DECREF(one);
3484 Py_DECREF(div);
3485 div = temp;
3486 }
3487 if (pdiv != NULL)
3488 *pdiv = div;
3489 else
3490 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 if (pmod != NULL)
3493 *pmod = mod;
3494 else
3495 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003497 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003498}
3499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003500static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003501long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 CHECK_BINOP(a, b);
3506 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3507 div = NULL;
3508 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003509}
3510
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003511/* PyLong/PyLong -> float, with correctly rounded result. */
3512
3513#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3514#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3515
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003516static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003517long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003519 PyLongObject *a, *b, *x;
3520 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3521 digit mask, low;
3522 int inexact, negate, a_is_small, b_is_small;
3523 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003525 CHECK_BINOP(v, w);
3526 a = (PyLongObject *)v;
3527 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 /*
3530 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3533 1. choose a suitable integer 'shift'
3534 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3535 3. adjust x for correct rounding
3536 4. convert x to a double dx with the same value
3537 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3542 returns either 0.0 or -0.0, depending on the sign of b. For a and
3543 b both nonzero, ignore signs of a and b, and add the sign back in
3544 at the end. Now write a_bits and b_bits for the bit lengths of a
3545 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3546 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003550 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3551 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3552 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3553 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003557 1. The integer 'shift' is chosen so that x has the right number of
3558 bits for a double, plus two or three extra bits that will be used
3559 in the rounding decisions. Writing a_bits and b_bits for the
3560 number of significant bits in a and b respectively, a
3561 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 This is fine in the usual case, but if a/b is smaller than the
3566 smallest normal float then it can lead to double rounding on an
3567 IEEE 754 platform, giving incorrectly rounded results. So we
3568 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003572 2. The quantity x is computed by first shifting a (left -shift bits
3573 if shift <= 0, right shift bits if shift > 0) and then dividing by
3574 b. For both the shift and the division, we keep track of whether
3575 the result is inexact, in a flag 'inexact'; this information is
3576 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 With the choice of shift above, together with our assumption that
3579 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3580 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3583 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 For float representability, we need x/2**extra_bits <
3588 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3589 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 To round, we just modify the bottom digit of x in-place; this can
3594 end up giving a digit with value > PyLONG_MASK, but that's not a
3595 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 With the original choices for shift above, extra_bits will always
3598 be 2 or 3. Then rounding under the round-half-to-even rule, we
3599 round up iff the most significant of the extra bits is 1, and
3600 either: (a) the computation of x in step 2 had an inexact result,
3601 or (b) at least one other of the extra bits is 1, or (c) the least
3602 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 4. Conversion to a double is straightforward; all floating-point
3605 operations involved in the conversion are exact, so there's no
3606 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3609 The result will always be exactly representable as a double, except
3610 in the case that it overflows. To avoid dependence on the exact
3611 behaviour of ldexp on overflow, we check for overflow before
3612 applying ldexp. The result of ldexp is adjusted for sign before
3613 returning.
3614 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 /* Reduce to case where a and b are both positive. */
3617 a_size = ABS(Py_SIZE(a));
3618 b_size = ABS(Py_SIZE(b));
3619 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3620 if (b_size == 0) {
3621 PyErr_SetString(PyExc_ZeroDivisionError,
3622 "division by zero");
3623 goto error;
3624 }
3625 if (a_size == 0)
3626 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 /* Fast path for a and b small (exactly representable in a double).
3629 Relies on floating-point division being correctly rounded; results
3630 may be subject to double rounding on x86 machines that operate with
3631 the x87 FPU set to 64-bit precision. */
3632 a_is_small = a_size <= MANT_DIG_DIGITS ||
3633 (a_size == MANT_DIG_DIGITS+1 &&
3634 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3635 b_is_small = b_size <= MANT_DIG_DIGITS ||
3636 (b_size == MANT_DIG_DIGITS+1 &&
3637 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3638 if (a_is_small && b_is_small) {
3639 double da, db;
3640 da = a->ob_digit[--a_size];
3641 while (a_size > 0)
3642 da = da * PyLong_BASE + a->ob_digit[--a_size];
3643 db = b->ob_digit[--b_size];
3644 while (b_size > 0)
3645 db = db * PyLong_BASE + b->ob_digit[--b_size];
3646 result = da / db;
3647 goto success;
3648 }
Tim Peterse2a60002001-09-04 06:17:36 +00003649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 /* Catch obvious cases of underflow and overflow */
3651 diff = a_size - b_size;
3652 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3653 /* Extreme overflow */
3654 goto overflow;
3655 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3656 /* Extreme underflow */
3657 goto underflow_or_zero;
3658 /* Next line is now safe from overflowing a Py_ssize_t */
3659 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3660 bits_in_digit(b->ob_digit[b_size - 1]);
3661 /* Now diff = a_bits - b_bits. */
3662 if (diff > DBL_MAX_EXP)
3663 goto overflow;
3664 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3665 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003668 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003672 /* x = abs(a * 2**-shift) */
3673 if (shift <= 0) {
3674 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3675 digit rem;
3676 /* x = a << -shift */
3677 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3678 /* In practice, it's probably impossible to end up
3679 here. Both a and b would have to be enormous,
3680 using close to SIZE_T_MAX bytes of memory each. */
3681 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003682 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 goto error;
3684 }
3685 x = _PyLong_New(a_size + shift_digits + 1);
3686 if (x == NULL)
3687 goto error;
3688 for (i = 0; i < shift_digits; i++)
3689 x->ob_digit[i] = 0;
3690 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3691 a_size, -shift % PyLong_SHIFT);
3692 x->ob_digit[a_size + shift_digits] = rem;
3693 }
3694 else {
3695 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3696 digit rem;
3697 /* x = a >> shift */
3698 assert(a_size >= shift_digits);
3699 x = _PyLong_New(a_size - shift_digits);
3700 if (x == NULL)
3701 goto error;
3702 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3703 a_size - shift_digits, shift % PyLong_SHIFT);
3704 /* set inexact if any of the bits shifted out is nonzero */
3705 if (rem)
3706 inexact = 1;
3707 while (!inexact && shift_digits > 0)
3708 if (a->ob_digit[--shift_digits])
3709 inexact = 1;
3710 }
3711 long_normalize(x);
3712 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003714 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3715 reference to x, so it's safe to modify it in-place. */
3716 if (b_size == 1) {
3717 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3718 b->ob_digit[0]);
3719 long_normalize(x);
3720 if (rem)
3721 inexact = 1;
3722 }
3723 else {
3724 PyLongObject *div, *rem;
3725 div = x_divrem(x, b, &rem);
3726 Py_DECREF(x);
3727 x = div;
3728 if (x == NULL)
3729 goto error;
3730 if (Py_SIZE(rem))
3731 inexact = 1;
3732 Py_DECREF(rem);
3733 }
3734 x_size = ABS(Py_SIZE(x));
3735 assert(x_size > 0); /* result of division is never zero */
3736 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003739 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003742 /* Round by directly modifying the low digit of x. */
3743 mask = (digit)1 << (extra_bits - 1);
3744 low = x->ob_digit[0] | inexact;
3745 if (low & mask && low & (3*mask-1))
3746 low += mask;
3747 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003749 /* Convert x to a double dx; the conversion is exact. */
3750 dx = x->ob_digit[--x_size];
3751 while (x_size > 0)
3752 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3753 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 /* Check whether ldexp result will overflow a double. */
3756 if (shift + x_bits >= DBL_MAX_EXP &&
3757 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3758 goto overflow;
3759 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003760
3761 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003763
3764 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003766
3767 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003768 PyErr_SetString(PyExc_OverflowError,
3769 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003770 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003772}
3773
3774static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003775long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003779 CHECK_BINOP(a, b);
3780
3781 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3782 mod = NULL;
3783 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003784}
3785
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003786static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003787long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 PyLongObject *div, *mod;
3790 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003794 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3795 return NULL;
3796 }
3797 z = PyTuple_New(2);
3798 if (z != NULL) {
3799 PyTuple_SetItem(z, 0, (PyObject *) div);
3800 PyTuple_SetItem(z, 1, (PyObject *) mod);
3801 }
3802 else {
3803 Py_DECREF(div);
3804 Py_DECREF(mod);
3805 }
3806 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003807}
3808
Tim Peters47e52ee2004-08-30 02:44:38 +00003809/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003810static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003811long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003813 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3814 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003816 PyLongObject *z = NULL; /* accumulated result */
3817 Py_ssize_t i, j, k; /* counters */
3818 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003820 /* 5-ary values. If the exponent is large enough, table is
3821 * precomputed so that table[i] == a**i % c for i in range(32).
3822 */
3823 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3824 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003826 /* a, b, c = v, w, x */
3827 CHECK_BINOP(v, w);
3828 a = (PyLongObject*)v; Py_INCREF(a);
3829 b = (PyLongObject*)w; Py_INCREF(b);
3830 if (PyLong_Check(x)) {
3831 c = (PyLongObject *)x;
3832 Py_INCREF(x);
3833 }
3834 else if (x == Py_None)
3835 c = NULL;
3836 else {
3837 Py_DECREF(a);
3838 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003839 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 }
Tim Peters4c483c42001-09-05 06:24:58 +00003841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003842 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3843 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04003844 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003845 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003846 goto Error;
3847 }
3848 else {
3849 /* else return a float. This works because we know
3850 that this calls float_pow() which converts its
3851 arguments to double. */
3852 Py_DECREF(a);
3853 Py_DECREF(b);
3854 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3855 }
3856 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003858 if (c) {
3859 /* if modulus == 0:
3860 raise ValueError() */
3861 if (Py_SIZE(c) == 0) {
3862 PyErr_SetString(PyExc_ValueError,
3863 "pow() 3rd argument cannot be 0");
3864 goto Error;
3865 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003867 /* if modulus < 0:
3868 negativeOutput = True
3869 modulus = -modulus */
3870 if (Py_SIZE(c) < 0) {
3871 negativeOutput = 1;
3872 temp = (PyLongObject *)_PyLong_Copy(c);
3873 if (temp == NULL)
3874 goto Error;
3875 Py_DECREF(c);
3876 c = temp;
3877 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02003878 _PyLong_Negate(&c);
3879 if (c == NULL)
3880 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003883 /* if modulus == 1:
3884 return 0 */
3885 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3886 z = (PyLongObject *)PyLong_FromLong(0L);
3887 goto Done;
3888 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003889
Tim Peters81a93152013-10-05 16:53:52 -05003890 /* Reduce base by modulus in some cases:
3891 1. If base < 0. Forcing the base non-negative makes things easier.
3892 2. If base is obviously larger than the modulus. The "small
3893 exponent" case later can multiply directly by base repeatedly,
3894 while the "large exponent" case multiplies directly by base 31
3895 times. It can be unboundedly faster to multiply by
3896 base % modulus instead.
3897 We could _always_ do this reduction, but l_divmod() isn't cheap,
3898 so we only do it when it buys something. */
3899 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003900 if (l_divmod(a, c, NULL, &temp) < 0)
3901 goto Error;
3902 Py_DECREF(a);
3903 a = temp;
3904 temp = NULL;
3905 }
3906 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 /* At this point a, b, and c are guaranteed non-negative UNLESS
3909 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 z = (PyLongObject *)PyLong_FromLong(1L);
3912 if (z == NULL)
3913 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 /* Perform a modular reduction, X = X % c, but leave X alone if c
3916 * is NULL.
3917 */
3918#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003919 do { \
3920 if (c != NULL) { \
3921 if (l_divmod(X, c, NULL, &temp) < 0) \
3922 goto Error; \
3923 Py_XDECREF(X); \
3924 X = temp; \
3925 temp = NULL; \
3926 } \
3927 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 /* Multiply two values, then reduce the result:
3930 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003931#define MULT(X, Y, result) \
3932 do { \
3933 temp = (PyLongObject *)long_mul(X, Y); \
3934 if (temp == NULL) \
3935 goto Error; \
3936 Py_XDECREF(result); \
3937 result = temp; \
3938 temp = NULL; \
3939 REDUCE(result); \
3940 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3943 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3944 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3945 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3946 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003949 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003951 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 }
3953 }
3954 }
3955 else {
3956 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3957 Py_INCREF(z); /* still holds 1L */
3958 table[0] = z;
3959 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003960 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3963 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3966 const int index = (bi >> j) & 0x1f;
3967 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003968 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003970 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 }
3972 }
3973 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003975 if (negativeOutput && (Py_SIZE(z) != 0)) {
3976 temp = (PyLongObject *)long_sub(z, c);
3977 if (temp == NULL)
3978 goto Error;
3979 Py_DECREF(z);
3980 z = temp;
3981 temp = NULL;
3982 }
3983 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003984
Mark Dickinson22b20182010-05-10 21:27:53 +00003985 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02003986 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003988 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003989 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3990 for (i = 0; i < 32; ++i)
3991 Py_XDECREF(table[i]);
3992 }
3993 Py_DECREF(a);
3994 Py_DECREF(b);
3995 Py_XDECREF(c);
3996 Py_XDECREF(temp);
3997 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003998}
3999
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004000static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004001long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 /* Implement ~x as -(x+1) */
4004 PyLongObject *x;
4005 PyLongObject *w;
4006 if (ABS(Py_SIZE(v)) <=1)
4007 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4008 w = (PyLongObject *)PyLong_FromLong(1L);
4009 if (w == NULL)
4010 return NULL;
4011 x = (PyLongObject *) long_add(v, w);
4012 Py_DECREF(w);
4013 if (x == NULL)
4014 return NULL;
4015 Py_SIZE(x) = -(Py_SIZE(x));
4016 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004017}
4018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004019static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004020long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004022 PyLongObject *z;
4023 if (ABS(Py_SIZE(v)) <= 1)
4024 return PyLong_FromLong(-MEDIUM_VALUE(v));
4025 z = (PyLongObject *)_PyLong_Copy(v);
4026 if (z != NULL)
4027 Py_SIZE(z) = -(Py_SIZE(v));
4028 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004029}
4030
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004031static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004032long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004034 if (Py_SIZE(v) < 0)
4035 return long_neg(v);
4036 else
4037 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004038}
4039
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004040static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004041long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004043 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004044}
4045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004046static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004047long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 PyLongObject *z = NULL;
4050 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4051 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004055 if (Py_SIZE(a) < 0) {
4056 /* Right shifting negative numbers is harder */
4057 PyLongObject *a1, *a2;
4058 a1 = (PyLongObject *) long_invert(a);
4059 if (a1 == NULL)
4060 goto rshift_error;
4061 a2 = (PyLongObject *) long_rshift(a1, b);
4062 Py_DECREF(a1);
4063 if (a2 == NULL)
4064 goto rshift_error;
4065 z = (PyLongObject *) long_invert(a2);
4066 Py_DECREF(a2);
4067 }
4068 else {
4069 shiftby = PyLong_AsSsize_t((PyObject *)b);
4070 if (shiftby == -1L && PyErr_Occurred())
4071 goto rshift_error;
4072 if (shiftby < 0) {
4073 PyErr_SetString(PyExc_ValueError,
4074 "negative shift count");
4075 goto rshift_error;
4076 }
4077 wordshift = shiftby / PyLong_SHIFT;
4078 newsize = ABS(Py_SIZE(a)) - wordshift;
4079 if (newsize <= 0)
4080 return PyLong_FromLong(0);
4081 loshift = shiftby % PyLong_SHIFT;
4082 hishift = PyLong_SHIFT - loshift;
4083 lomask = ((digit)1 << hishift) - 1;
4084 himask = PyLong_MASK ^ lomask;
4085 z = _PyLong_New(newsize);
4086 if (z == NULL)
4087 goto rshift_error;
4088 if (Py_SIZE(a) < 0)
4089 Py_SIZE(z) = -(Py_SIZE(z));
4090 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4091 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4092 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004093 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 }
4095 z = long_normalize(z);
4096 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004097 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004098 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004099
Guido van Rossumc6913e71991-11-19 20:26:46 +00004100}
4101
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004102static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004103long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004105 /* This version due to Tim Peters */
4106 PyLongObject *a = (PyLongObject*)v;
4107 PyLongObject *b = (PyLongObject*)w;
4108 PyLongObject *z = NULL;
4109 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4110 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004114 shiftby = PyLong_AsSsize_t((PyObject *)b);
4115 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004116 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 if (shiftby < 0) {
4118 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004119 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004120 }
4121 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4122 wordshift = shiftby / PyLong_SHIFT;
4123 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 oldsize = ABS(Py_SIZE(a));
4126 newsize = oldsize + wordshift;
4127 if (remshift)
4128 ++newsize;
4129 z = _PyLong_New(newsize);
4130 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004131 return NULL;
4132 if (Py_SIZE(a) < 0) {
4133 assert(Py_REFCNT(z) == 1);
4134 Py_SIZE(z) = -Py_SIZE(z);
4135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 for (i = 0; i < wordshift; i++)
4137 z->ob_digit[i] = 0;
4138 accum = 0;
4139 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4140 accum |= (twodigits)a->ob_digit[j] << remshift;
4141 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4142 accum >>= PyLong_SHIFT;
4143 }
4144 if (remshift)
4145 z->ob_digit[newsize-1] = (digit)accum;
4146 else
4147 assert(!accum);
4148 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004149 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004150}
4151
Mark Dickinson27a87a22009-10-25 20:43:34 +00004152/* Compute two's complement of digit vector a[0:m], writing result to
4153 z[0:m]. The digit vector a need not be normalized, but should not
4154 be entirely zero. a and z may point to the same digit vector. */
4155
4156static void
4157v_complement(digit *z, digit *a, Py_ssize_t m)
4158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 Py_ssize_t i;
4160 digit carry = 1;
4161 for (i = 0; i < m; ++i) {
4162 carry += a[i] ^ PyLong_MASK;
4163 z[i] = carry & PyLong_MASK;
4164 carry >>= PyLong_SHIFT;
4165 }
4166 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004167}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004168
4169/* Bitwise and/xor/or operations */
4170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004171static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004172long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004173 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004174 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004176 int nega, negb, negz;
4177 Py_ssize_t size_a, size_b, size_z, i;
4178 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004180 /* Bitwise operations for negative numbers operate as though
4181 on a two's complement representation. So convert arguments
4182 from sign-magnitude to two's complement, and convert the
4183 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004185 /* If a is negative, replace it by its two's complement. */
4186 size_a = ABS(Py_SIZE(a));
4187 nega = Py_SIZE(a) < 0;
4188 if (nega) {
4189 z = _PyLong_New(size_a);
4190 if (z == NULL)
4191 return NULL;
4192 v_complement(z->ob_digit, a->ob_digit, size_a);
4193 a = z;
4194 }
4195 else
4196 /* Keep reference count consistent. */
4197 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004199 /* Same for b. */
4200 size_b = ABS(Py_SIZE(b));
4201 negb = Py_SIZE(b) < 0;
4202 if (negb) {
4203 z = _PyLong_New(size_b);
4204 if (z == NULL) {
4205 Py_DECREF(a);
4206 return NULL;
4207 }
4208 v_complement(z->ob_digit, b->ob_digit, size_b);
4209 b = z;
4210 }
4211 else
4212 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004214 /* Swap a and b if necessary to ensure size_a >= size_b. */
4215 if (size_a < size_b) {
4216 z = a; a = b; b = z;
4217 size_z = size_a; size_a = size_b; size_b = size_z;
4218 negz = nega; nega = negb; negb = negz;
4219 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004221 /* JRH: The original logic here was to allocate the result value (z)
4222 as the longer of the two operands. However, there are some cases
4223 where the result is guaranteed to be shorter than that: AND of two
4224 positives, OR of two negatives: use the shorter number. AND with
4225 mixed signs: use the positive number. OR with mixed signs: use the
4226 negative number.
4227 */
4228 switch (op) {
4229 case '^':
4230 negz = nega ^ negb;
4231 size_z = size_a;
4232 break;
4233 case '&':
4234 negz = nega & negb;
4235 size_z = negb ? size_a : size_b;
4236 break;
4237 case '|':
4238 negz = nega | negb;
4239 size_z = negb ? size_b : size_a;
4240 break;
4241 default:
4242 PyErr_BadArgument();
4243 return NULL;
4244 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004246 /* We allow an extra digit if z is negative, to make sure that
4247 the final two's complement of z doesn't overflow. */
4248 z = _PyLong_New(size_z + negz);
4249 if (z == NULL) {
4250 Py_DECREF(a);
4251 Py_DECREF(b);
4252 return NULL;
4253 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 /* Compute digits for overlap of a and b. */
4256 switch(op) {
4257 case '&':
4258 for (i = 0; i < size_b; ++i)
4259 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4260 break;
4261 case '|':
4262 for (i = 0; i < size_b; ++i)
4263 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4264 break;
4265 case '^':
4266 for (i = 0; i < size_b; ++i)
4267 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4268 break;
4269 default:
4270 PyErr_BadArgument();
4271 return NULL;
4272 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004274 /* Copy any remaining digits of a, inverting if necessary. */
4275 if (op == '^' && negb)
4276 for (; i < size_z; ++i)
4277 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4278 else if (i < size_z)
4279 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4280 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004282 /* Complement result if negative. */
4283 if (negz) {
4284 Py_SIZE(z) = -(Py_SIZE(z));
4285 z->ob_digit[size_z] = PyLong_MASK;
4286 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4287 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 Py_DECREF(a);
4290 Py_DECREF(b);
4291 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004292}
4293
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004294static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004295long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004297 PyObject *c;
4298 CHECK_BINOP(a, b);
4299 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4300 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004301}
4302
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004303static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004304long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004306 PyObject *c;
4307 CHECK_BINOP(a, b);
4308 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4309 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004310}
4311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004312static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004313long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 PyObject *c;
4316 CHECK_BINOP(a, b);
4317 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4318 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004319}
4320
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004321static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004322long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 if (PyLong_CheckExact(v))
4325 Py_INCREF(v);
4326 else
4327 v = _PyLong_Copy((PyLongObject *)v);
4328 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004329}
4330
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004331static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004332long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004334 double result;
4335 result = PyLong_AsDouble(v);
4336 if (result == -1.0 && PyErr_Occurred())
4337 return NULL;
4338 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004339}
4340
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004341static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004342long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004343
Tim Peters6d6c1a32001-08-02 04:15:00 +00004344static PyObject *
4345long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4346{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004347 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004348 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004351 if (type != &PyLong_Type)
4352 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004353 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4354 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004355 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004356 if (x == NULL) {
4357 if (obase != NULL) {
4358 PyErr_SetString(PyExc_TypeError,
4359 "int() missing string argument");
4360 return NULL;
4361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004363 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004364 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004366
Gregory P. Smitha689e522012-12-25 22:38:32 -08004367 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004368 if (base == -1 && PyErr_Occurred())
4369 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004370 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004371 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004372 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004373 return NULL;
4374 }
4375
4376 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004377 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004380 if (PyByteArray_Check(x))
4381 string = PyByteArray_AS_STRING(x);
4382 else
4383 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004384 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 }
4386 else {
4387 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004388 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 return NULL;
4390 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004391}
4392
Serhiy Storchaka95949422013-08-27 19:40:23 +03004393/* Wimpy, slow approach to tp_new calls for subtypes of int:
4394 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004395 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004396 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004397*/
4398static PyObject *
4399long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 PyLongObject *tmp, *newobj;
4402 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004404 assert(PyType_IsSubtype(type, &PyLong_Type));
4405 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4406 if (tmp == NULL)
4407 return NULL;
4408 assert(PyLong_CheckExact(tmp));
4409 n = Py_SIZE(tmp);
4410 if (n < 0)
4411 n = -n;
4412 newobj = (PyLongObject *)type->tp_alloc(type, n);
4413 if (newobj == NULL) {
4414 Py_DECREF(tmp);
4415 return NULL;
4416 }
4417 assert(PyLong_Check(newobj));
4418 Py_SIZE(newobj) = Py_SIZE(tmp);
4419 for (i = 0; i < n; i++)
4420 newobj->ob_digit[i] = tmp->ob_digit[i];
4421 Py_DECREF(tmp);
4422 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004423}
4424
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004425static PyObject *
4426long_getnewargs(PyLongObject *v)
4427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004428 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004429}
4430
Guido van Rossumb43daf72007-08-01 18:08:08 +00004431static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004432long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004434}
4435
4436static PyObject *
4437long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004439}
4440
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004441static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004442long__format__(PyObject *self, PyObject *args)
4443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004445 _PyUnicodeWriter writer;
4446 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4449 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004450
Victor Stinner8f674cc2013-04-17 23:02:17 +02004451 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004452 ret = _PyLong_FormatAdvancedWriter(
4453 &writer,
4454 self,
4455 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4456 if (ret == -1) {
4457 _PyUnicodeWriter_Dealloc(&writer);
4458 return NULL;
4459 }
4460 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004461}
4462
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004463/* Return a pair (q, r) such that a = b * q + r, and
4464 abs(r) <= abs(b)/2, with equality possible only if q is even.
4465 In other words, q == a / b, rounded to the nearest integer using
4466 round-half-to-even. */
4467
4468PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004469_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004470{
4471 PyLongObject *quo = NULL, *rem = NULL;
4472 PyObject *one = NULL, *twice_rem, *result, *temp;
4473 int cmp, quo_is_odd, quo_is_neg;
4474
4475 /* Equivalent Python code:
4476
4477 def divmod_near(a, b):
4478 q, r = divmod(a, b)
4479 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4480 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4481 # positive, 2 * r < b if b negative.
4482 greater_than_half = 2*r > b if b > 0 else 2*r < b
4483 exactly_half = 2*r == b
4484 if greater_than_half or exactly_half and q % 2 == 1:
4485 q += 1
4486 r -= b
4487 return q, r
4488
4489 */
4490 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4491 PyErr_SetString(PyExc_TypeError,
4492 "non-integer arguments in division");
4493 return NULL;
4494 }
4495
4496 /* Do a and b have different signs? If so, quotient is negative. */
4497 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4498
4499 one = PyLong_FromLong(1L);
4500 if (one == NULL)
4501 return NULL;
4502
4503 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4504 goto error;
4505
4506 /* compare twice the remainder with the divisor, to see
4507 if we need to adjust the quotient and remainder */
4508 twice_rem = long_lshift((PyObject *)rem, one);
4509 if (twice_rem == NULL)
4510 goto error;
4511 if (quo_is_neg) {
4512 temp = long_neg((PyLongObject*)twice_rem);
4513 Py_DECREF(twice_rem);
4514 twice_rem = temp;
4515 if (twice_rem == NULL)
4516 goto error;
4517 }
4518 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4519 Py_DECREF(twice_rem);
4520
4521 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4522 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4523 /* fix up quotient */
4524 if (quo_is_neg)
4525 temp = long_sub(quo, (PyLongObject *)one);
4526 else
4527 temp = long_add(quo, (PyLongObject *)one);
4528 Py_DECREF(quo);
4529 quo = (PyLongObject *)temp;
4530 if (quo == NULL)
4531 goto error;
4532 /* and remainder */
4533 if (quo_is_neg)
4534 temp = long_add(rem, (PyLongObject *)b);
4535 else
4536 temp = long_sub(rem, (PyLongObject *)b);
4537 Py_DECREF(rem);
4538 rem = (PyLongObject *)temp;
4539 if (rem == NULL)
4540 goto error;
4541 }
4542
4543 result = PyTuple_New(2);
4544 if (result == NULL)
4545 goto error;
4546
4547 /* PyTuple_SET_ITEM steals references */
4548 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4549 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4550 Py_DECREF(one);
4551 return result;
4552
4553 error:
4554 Py_XDECREF(quo);
4555 Py_XDECREF(rem);
4556 Py_XDECREF(one);
4557 return NULL;
4558}
4559
Eric Smith8c663262007-08-25 02:26:07 +00004560static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004561long_round(PyObject *self, PyObject *args)
4562{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004563 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004564
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004565 /* To round an integer m to the nearest 10**n (n positive), we make use of
4566 * the divmod_near operation, defined by:
4567 *
4568 * divmod_near(a, b) = (q, r)
4569 *
4570 * where q is the nearest integer to the quotient a / b (the
4571 * nearest even integer in the case of a tie) and r == a - q * b.
4572 * Hence q * b = a - r is the nearest multiple of b to a,
4573 * preferring even multiples in the case of a tie.
4574 *
4575 * So the nearest multiple of 10**n to m is:
4576 *
4577 * m - divmod_near(m, 10**n)[1].
4578 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004579 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4580 return NULL;
4581 if (o_ndigits == NULL)
4582 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004583
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004584 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004585 if (ndigits == NULL)
4586 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004587
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004588 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (Py_SIZE(ndigits) >= 0) {
4590 Py_DECREF(ndigits);
4591 return long_long(self);
4592 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004593
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004594 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4595 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004597 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004599 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004600
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004601 result = PyLong_FromLong(10L);
4602 if (result == NULL) {
4603 Py_DECREF(ndigits);
4604 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004606
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004607 temp = long_pow(result, ndigits, Py_None);
4608 Py_DECREF(ndigits);
4609 Py_DECREF(result);
4610 result = temp;
4611 if (result == NULL)
4612 return NULL;
4613
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004614 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004615 Py_DECREF(result);
4616 result = temp;
4617 if (result == NULL)
4618 return NULL;
4619
4620 temp = long_sub((PyLongObject *)self,
4621 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4622 Py_DECREF(result);
4623 result = temp;
4624
4625 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004626}
4627
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004628static PyObject *
4629long_sizeof(PyLongObject *v)
4630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4634 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004635}
4636
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004637static PyObject *
4638long_bit_length(PyLongObject *v)
4639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 PyLongObject *result, *x, *y;
4641 Py_ssize_t ndigits, msd_bits = 0;
4642 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 assert(v != NULL);
4645 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 ndigits = ABS(Py_SIZE(v));
4648 if (ndigits == 0)
4649 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004651 msd = v->ob_digit[ndigits-1];
4652 while (msd >= 32) {
4653 msd_bits += 6;
4654 msd >>= 6;
4655 }
4656 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4659 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 /* expression above may overflow; use Python integers instead */
4662 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4663 if (result == NULL)
4664 return NULL;
4665 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4666 if (x == NULL)
4667 goto error;
4668 y = (PyLongObject *)long_mul(result, x);
4669 Py_DECREF(x);
4670 if (y == NULL)
4671 goto error;
4672 Py_DECREF(result);
4673 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4676 if (x == NULL)
4677 goto error;
4678 y = (PyLongObject *)long_add(result, x);
4679 Py_DECREF(x);
4680 if (y == NULL)
4681 goto error;
4682 Py_DECREF(result);
4683 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004685 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004686
Mark Dickinson22b20182010-05-10 21:27:53 +00004687 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 Py_DECREF(result);
4689 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004690}
4691
4692PyDoc_STRVAR(long_bit_length_doc,
4693"int.bit_length() -> int\n\
4694\n\
4695Number of bits necessary to represent self in binary.\n\
4696>>> bin(37)\n\
4697'0b100101'\n\
4698>>> (37).bit_length()\n\
46996");
4700
Christian Heimes53876d92008-04-19 00:31:39 +00004701#if 0
4702static PyObject *
4703long_is_finite(PyObject *v)
4704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004706}
4707#endif
4708
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004709
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004710static PyObject *
4711long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 PyObject *byteorder_str;
4714 PyObject *is_signed_obj = NULL;
4715 Py_ssize_t length;
4716 int little_endian;
4717 int is_signed;
4718 PyObject *bytes;
4719 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4722 &length, &byteorder_str,
4723 &is_signed_obj))
4724 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 if (args != NULL && Py_SIZE(args) > 2) {
4727 PyErr_SetString(PyExc_TypeError,
4728 "'signed' is a keyword-only argument");
4729 return NULL;
4730 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004732 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4733 little_endian = 1;
4734 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4735 little_endian = 0;
4736 else {
4737 PyErr_SetString(PyExc_ValueError,
4738 "byteorder must be either 'little' or 'big'");
4739 return NULL;
4740 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004742 if (is_signed_obj != NULL) {
4743 int cmp = PyObject_IsTrue(is_signed_obj);
4744 if (cmp < 0)
4745 return NULL;
4746 is_signed = cmp ? 1 : 0;
4747 }
4748 else {
4749 /* If the signed argument was omitted, use False as the
4750 default. */
4751 is_signed = 0;
4752 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754 if (length < 0) {
4755 PyErr_SetString(PyExc_ValueError,
4756 "length argument must be non-negative");
4757 return NULL;
4758 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760 bytes = PyBytes_FromStringAndSize(NULL, length);
4761 if (bytes == NULL)
4762 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4765 length, little_endian, is_signed) < 0) {
4766 Py_DECREF(bytes);
4767 return NULL;
4768 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004770 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004771}
4772
Mark Dickinson078c2532010-01-30 18:06:17 +00004773PyDoc_STRVAR(long_to_bytes_doc,
4774"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004775\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004776Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004777\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004778The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004779raised if the integer is not representable with the given number of\n\
4780bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004781\n\
4782The byteorder argument determines the byte order used to represent the\n\
4783integer. If byteorder is 'big', the most significant byte is at the\n\
4784beginning of the byte array. If byteorder is 'little', the most\n\
4785significant byte is at the end of the byte array. To request the native\n\
4786byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4787\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004788The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004789used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004790is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004791
4792static PyObject *
4793long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004795 PyObject *byteorder_str;
4796 PyObject *is_signed_obj = NULL;
4797 int little_endian;
4798 int is_signed;
4799 PyObject *obj;
4800 PyObject *bytes;
4801 PyObject *long_obj;
4802 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4805 &obj, &byteorder_str,
4806 &is_signed_obj))
4807 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 if (args != NULL && Py_SIZE(args) > 2) {
4810 PyErr_SetString(PyExc_TypeError,
4811 "'signed' is a keyword-only argument");
4812 return NULL;
4813 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004815 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4816 little_endian = 1;
4817 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4818 little_endian = 0;
4819 else {
4820 PyErr_SetString(PyExc_ValueError,
4821 "byteorder must be either 'little' or 'big'");
4822 return NULL;
4823 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 if (is_signed_obj != NULL) {
4826 int cmp = PyObject_IsTrue(is_signed_obj);
4827 if (cmp < 0)
4828 return NULL;
4829 is_signed = cmp ? 1 : 0;
4830 }
4831 else {
4832 /* If the signed argument was omitted, use False as the
4833 default. */
4834 is_signed = 0;
4835 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 bytes = PyObject_Bytes(obj);
4838 if (bytes == NULL)
4839 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004841 long_obj = _PyLong_FromByteArray(
4842 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4843 little_endian, is_signed);
4844 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004847 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004848 */
4849 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4850 PyLongObject *newobj;
4851 int i;
4852 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004854 newobj = (PyLongObject *)type->tp_alloc(type, n);
4855 if (newobj == NULL) {
4856 Py_DECREF(long_obj);
4857 return NULL;
4858 }
4859 assert(PyLong_Check(newobj));
4860 Py_SIZE(newobj) = Py_SIZE(long_obj);
4861 for (i = 0; i < n; i++) {
4862 newobj->ob_digit[i] =
4863 ((PyLongObject *)long_obj)->ob_digit[i];
4864 }
4865 Py_DECREF(long_obj);
4866 return (PyObject *)newobj;
4867 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004869 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004870}
4871
Mark Dickinson078c2532010-01-30 18:06:17 +00004872PyDoc_STRVAR(long_from_bytes_doc,
4873"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4874\n\
4875Return the integer represented by the given array of bytes.\n\
4876\n\
4877The bytes argument must either support the buffer protocol or be an\n\
4878iterable object producing bytes. Bytes and bytearray are examples of\n\
4879built-in objects that support the buffer protocol.\n\
4880\n\
4881The byteorder argument determines the byte order used to represent the\n\
4882integer. If byteorder is 'big', the most significant byte is at the\n\
4883beginning of the byte array. If byteorder is 'little', the most\n\
4884significant byte is at the end of the byte array. To request the native\n\
4885byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4886\n\
4887The signed keyword-only argument indicates whether two's complement is\n\
4888used to represent the integer.");
4889
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004890static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004891 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4892 "Returns self, the complex conjugate of any int."},
4893 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4894 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004895#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4897 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004898#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004899 {"to_bytes", (PyCFunction)long_to_bytes,
4900 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4901 {"from_bytes", (PyCFunction)long_from_bytes,
4902 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4903 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4904 "Truncating an Integral returns itself."},
4905 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4906 "Flooring an Integral returns itself."},
4907 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4908 "Ceiling of an Integral returns itself."},
4909 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4910 "Rounding an Integral returns itself.\n"
4911 "Rounding with an ndigits argument also returns an integer."},
4912 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4913 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4914 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4915 "Returns size in memory, in bytes"},
4916 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004917};
4918
Guido van Rossumb43daf72007-08-01 18:08:08 +00004919static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004920 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004921 (getter)long_long, (setter)NULL,
4922 "the real part of a complex number",
4923 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004924 {"imag",
4925 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004926 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004927 NULL},
4928 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004929 (getter)long_long, (setter)NULL,
4930 "the numerator of a rational number in lowest terms",
4931 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004932 {"denominator",
4933 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004934 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004935 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004936 {NULL} /* Sentinel */
4937};
4938
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004939PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004940"int(x=0) -> integer\n\
4941int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004942\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004943Convert a number or string to an integer, or return 0 if no arguments\n\
4944are given. If x is a number, return x.__int__(). For floating point\n\
4945numbers, this truncates towards zero.\n\
4946\n\
4947If x is not a number or if base is given, then x must be a string,\n\
4948bytes, or bytearray instance representing an integer literal in the\n\
4949given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4950by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4951Base 0 means to interpret the base from the string as an integer literal.\n\
4952>>> int('0b100', base=0)\n\
49534");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004954
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004955static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004956 (binaryfunc)long_add, /*nb_add*/
4957 (binaryfunc)long_sub, /*nb_subtract*/
4958 (binaryfunc)long_mul, /*nb_multiply*/
4959 long_mod, /*nb_remainder*/
4960 long_divmod, /*nb_divmod*/
4961 long_pow, /*nb_power*/
4962 (unaryfunc)long_neg, /*nb_negative*/
4963 (unaryfunc)long_long, /*tp_positive*/
4964 (unaryfunc)long_abs, /*tp_absolute*/
4965 (inquiry)long_bool, /*tp_bool*/
4966 (unaryfunc)long_invert, /*nb_invert*/
4967 long_lshift, /*nb_lshift*/
4968 (binaryfunc)long_rshift, /*nb_rshift*/
4969 long_and, /*nb_and*/
4970 long_xor, /*nb_xor*/
4971 long_or, /*nb_or*/
4972 long_long, /*nb_int*/
4973 0, /*nb_reserved*/
4974 long_float, /*nb_float*/
4975 0, /* nb_inplace_add */
4976 0, /* nb_inplace_subtract */
4977 0, /* nb_inplace_multiply */
4978 0, /* nb_inplace_remainder */
4979 0, /* nb_inplace_power */
4980 0, /* nb_inplace_lshift */
4981 0, /* nb_inplace_rshift */
4982 0, /* nb_inplace_and */
4983 0, /* nb_inplace_xor */
4984 0, /* nb_inplace_or */
4985 long_div, /* nb_floor_divide */
4986 long_true_divide, /* nb_true_divide */
4987 0, /* nb_inplace_floor_divide */
4988 0, /* nb_inplace_true_divide */
4989 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004990};
4991
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004992PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4994 "int", /* tp_name */
4995 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4996 sizeof(digit), /* tp_itemsize */
4997 long_dealloc, /* tp_dealloc */
4998 0, /* tp_print */
4999 0, /* tp_getattr */
5000 0, /* tp_setattr */
5001 0, /* tp_reserved */
5002 long_to_decimal_string, /* tp_repr */
5003 &long_as_number, /* tp_as_number */
5004 0, /* tp_as_sequence */
5005 0, /* tp_as_mapping */
5006 (hashfunc)long_hash, /* tp_hash */
5007 0, /* tp_call */
5008 long_to_decimal_string, /* tp_str */
5009 PyObject_GenericGetAttr, /* tp_getattro */
5010 0, /* tp_setattro */
5011 0, /* tp_as_buffer */
5012 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5013 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5014 long_doc, /* tp_doc */
5015 0, /* tp_traverse */
5016 0, /* tp_clear */
5017 long_richcompare, /* tp_richcompare */
5018 0, /* tp_weaklistoffset */
5019 0, /* tp_iter */
5020 0, /* tp_iternext */
5021 long_methods, /* tp_methods */
5022 0, /* tp_members */
5023 long_getset, /* tp_getset */
5024 0, /* tp_base */
5025 0, /* tp_dict */
5026 0, /* tp_descr_get */
5027 0, /* tp_descr_set */
5028 0, /* tp_dictoffset */
5029 0, /* tp_init */
5030 0, /* tp_alloc */
5031 long_new, /* tp_new */
5032 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005033};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005034
Mark Dickinsonbd792642009-03-18 20:06:12 +00005035static PyTypeObject Int_InfoType;
5036
5037PyDoc_STRVAR(int_info__doc__,
5038"sys.int_info\n\
5039\n\
5040A struct sequence that holds information about Python's\n\
5041internal representation of integers. The attributes are read only.");
5042
5043static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005045 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005047};
5048
5049static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 "sys.int_info", /* name */
5051 int_info__doc__, /* doc */
5052 int_info_fields, /* fields */
5053 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005054};
5055
5056PyObject *
5057PyLong_GetInfo(void)
5058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 PyObject* int_info;
5060 int field = 0;
5061 int_info = PyStructSequence_New(&Int_InfoType);
5062 if (int_info == NULL)
5063 return NULL;
5064 PyStructSequence_SET_ITEM(int_info, field++,
5065 PyLong_FromLong(PyLong_SHIFT));
5066 PyStructSequence_SET_ITEM(int_info, field++,
5067 PyLong_FromLong(sizeof(digit)));
5068 if (PyErr_Occurred()) {
5069 Py_CLEAR(int_info);
5070 return NULL;
5071 }
5072 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005073}
5074
Guido van Rossumddefaf32007-01-14 03:31:43 +00005075int
5076_PyLong_Init(void)
5077{
5078#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 int ival, size;
5080 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5083 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5084 if (Py_TYPE(v) == &PyLong_Type) {
5085 /* The element is already initialized, most likely
5086 * the Python interpreter was initialized before.
5087 */
5088 Py_ssize_t refcnt;
5089 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5092 _Py_NewReference(op);
5093 /* _Py_NewReference sets the ref count to 1 but
5094 * the ref count might be larger. Set the refcnt
5095 * to the original refcnt + 1 */
5096 Py_REFCNT(op) = refcnt + 1;
5097 assert(Py_SIZE(op) == size);
5098 assert(v->ob_digit[0] == abs(ival));
5099 }
5100 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005101 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 }
5103 Py_SIZE(v) = size;
5104 v->ob_digit[0] = abs(ival);
5105 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005106#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005108 if (Int_InfoType.tp_name == NULL) {
5109 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5110 return 0;
5111 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005114}
5115
5116void
5117PyLong_Fini(void)
5118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 /* Integers are currently statically allocated. Py_DECREF is not
5120 needed, but Python must forget about the reference or multiple
5121 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005122#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005123 int i;
5124 PyLongObject *v = small_ints;
5125 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5126 _Py_DEC_REFTOTAL;
5127 _Py_ForgetReference((PyObject*)v);
5128 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005129#endif
5130}