blob: 27bee50b8ce74646f51e91c5753b5b666bf3e660 [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
Guido van Rossumddefaf32007-01-14 03:31:43 +000025#if NSMALLNEGINTS + NSMALLPOSINTS > 0
26/* Small integers are preallocated in this array so that they
27 can be shared.
28 The integers that are preallocated are those in the range
29 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
30*/
31static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
32#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010033Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000034#endif
35
Guido van Rossum7eaf8222007-06-18 17:58:50 +000036static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000037get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000038{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050039 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050040 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050041 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000043#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 if (ival >= 0)
45 quick_int_allocs++;
46 else
47 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000048#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000050}
51#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000052 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
53 return get_small_int((sdigit)ival); \
54 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000057maybe_small_long(PyLongObject *v)
58{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020059 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 sdigit ival = MEDIUM_VALUE(v);
61 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
62 Py_DECREF(v);
63 return (PyLongObject *)get_small_int(ival);
64 }
65 }
66 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000067}
Guido van Rossumddefaf32007-01-14 03:31:43 +000068#else
69#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000070#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000071#endif
72
Serhiy Storchaka95949422013-08-27 19:40:23 +030073/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000074 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020075Py_LOCAL_INLINE(void)
76_PyLong_Negate(PyLongObject **x_p)
77{
78 PyLongObject *x;
79
80 x = (PyLongObject *)*x_p;
81 if (Py_REFCNT(x) == 1) {
82 Py_SIZE(x) = -Py_SIZE(x);
83 return;
84 }
85
86 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
87 Py_DECREF(x);
88}
89
Serhiy Storchaka95949422013-08-27 19:40:23 +030090/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000091 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030092 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000093 */
Tim Peters0973b992004-08-29 22:16:50 +000094#define KARATSUBA_CUTOFF 70
95#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000096
Tim Peters47e52ee2004-08-30 02:44:38 +000097/* For exponentiation, use the binary left-to-right algorithm
98 * unless the exponent contains more than FIVEARY_CUTOFF digits.
99 * In that case, do 5 bits at a time. The potential drawback is that
100 * a table of 2**5 intermediate results is computed.
101 */
102#define FIVEARY_CUTOFF 8
103
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000104#define SIGCHECK(PyTryBlock) \
105 do { \
106 if (PyErr_CheckSignals()) PyTryBlock \
107 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000108
Serhiy Storchaka95949422013-08-27 19:40:23 +0300109/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000110 Doesn't attempt to free the storage--in most cases, due to the nature
111 of the algorithms used, this could save at most be one word anyway. */
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200114long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000115{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200116 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 while (i > 0 && v->ob_digit[i-1] == 0)
120 --i;
121 if (i != j)
122 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
123 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000124}
125
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200126/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
127 using the nb_int slot, if available. Raise TypeError if either the
128 nb_int slot is not available or the result of the call to nb_int
129 returns something not of type int.
130*/
131PyLongObject *
132_PyLong_FromNbInt(PyObject *integral)
133{
134 PyNumberMethods *nb;
135 PyObject *result;
136
137 /* Fast path for the case that we already have an int. */
138 if (PyLong_CheckExact(integral)) {
139 Py_INCREF(integral);
140 return (PyLongObject *)integral;
141 }
142
143 nb = Py_TYPE(integral)->tp_as_number;
144 if (nb == NULL || nb->nb_int == NULL) {
145 PyErr_Format(PyExc_TypeError,
146 "an integer is required (got type %.200s)",
147 Py_TYPE(integral)->tp_name);
148 return NULL;
149 }
150
151 /* Convert using the nb_int slot, which should return something
152 of exact type int. */
153 result = nb->nb_int(integral);
154 if (!result || PyLong_CheckExact(result))
155 return (PyLongObject *)result;
156 if (!PyLong_Check(result)) {
157 PyErr_Format(PyExc_TypeError,
158 "__int__ returned non-int (type %.200s)",
159 result->ob_type->tp_name);
160 Py_DECREF(result);
161 return NULL;
162 }
163 /* Issue #17576: warn if 'result' not of exact type int. */
164 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
165 "__int__ returned non-int (type %.200s). "
166 "The ability to return an instance of a strict subclass of int "
167 "is deprecated, and may be removed in a future version of Python.",
168 result->ob_type->tp_name)) {
169 Py_DECREF(result);
170 return NULL;
171 }
172 return (PyLongObject *)result;
173}
174
175
Serhiy Storchaka95949422013-08-27 19:40:23 +0300176/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000177 Return NULL and set exception if we run out of memory. */
178
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000179#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000181
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyLongObject *result;
186 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
187 sizeof(digit)*size. Previous incarnations of this code used
188 sizeof(PyVarObject) instead of the offsetof, but this risks being
189 incorrect in the presence of padding between the PyVarObject header
190 and the digits. */
191 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
192 PyErr_SetString(PyExc_OverflowError,
193 "too many digits in integer");
194 return NULL;
195 }
196 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
197 size*sizeof(digit));
198 if (!result) {
199 PyErr_NoMemory();
200 return NULL;
201 }
202 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000203}
204
Tim Peters64b5ce32001-09-10 20:52:51 +0000205PyObject *
206_PyLong_Copy(PyLongObject *src)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 PyLongObject *result;
209 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 assert(src != NULL);
212 i = Py_SIZE(src);
213 if (i < 0)
214 i = -(i);
215 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100216 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 CHECK_SMALL_INT(ival);
218 }
219 result = _PyLong_New(i);
220 if (result != NULL) {
221 Py_SIZE(result) = Py_SIZE(src);
222 while (--i >= 0)
223 result->ob_digit[i] = src->ob_digit[i];
224 }
225 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000226}
227
Serhiy Storchaka95949422013-08-27 19:40:23 +0300228/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000229
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000230PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000231PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 PyLongObject *v;
234 unsigned long abs_ival;
235 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
236 int ndigits = 0;
237 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (ival < 0) {
242 /* negate: can't write this as abs_ival = -ival since that
243 invokes undefined behaviour when ival is LONG_MIN */
244 abs_ival = 0U-(unsigned long)ival;
245 sign = -1;
246 }
247 else {
248 abs_ival = (unsigned long)ival;
249 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* Fast path for single-digit ints */
252 if (!(abs_ival >> PyLong_SHIFT)) {
253 v = _PyLong_New(1);
254 if (v) {
255 Py_SIZE(v) = sign;
256 v->ob_digit[0] = Py_SAFE_DOWNCAST(
257 abs_ival, unsigned long, digit);
258 }
259 return (PyObject*)v;
260 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000261
Mark Dickinson249b8982009-04-27 19:41:00 +0000262#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* 2 digits */
264 if (!(abs_ival >> 2*PyLong_SHIFT)) {
265 v = _PyLong_New(2);
266 if (v) {
267 Py_SIZE(v) = 2*sign;
268 v->ob_digit[0] = Py_SAFE_DOWNCAST(
269 abs_ival & PyLong_MASK, unsigned long, digit);
270 v->ob_digit[1] = Py_SAFE_DOWNCAST(
271 abs_ival >> PyLong_SHIFT, unsigned long, digit);
272 }
273 return (PyObject*)v;
274 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000275#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* Larger numbers: loop to determine number of digits */
278 t = abs_ival;
279 while (t) {
280 ++ndigits;
281 t >>= PyLong_SHIFT;
282 }
283 v = _PyLong_New(ndigits);
284 if (v != NULL) {
285 digit *p = v->ob_digit;
286 Py_SIZE(v) = ndigits*sign;
287 t = abs_ival;
288 while (t) {
289 *p++ = Py_SAFE_DOWNCAST(
290 t & PyLong_MASK, unsigned long, digit);
291 t >>= PyLong_SHIFT;
292 }
293 }
294 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000295}
296
Serhiy Storchaka95949422013-08-27 19:40:23 +0300297/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000300PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 PyLongObject *v;
303 unsigned long t;
304 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (ival < PyLong_BASE)
307 return PyLong_FromLong(ival);
308 /* Count the number of Python digits. */
309 t = (unsigned long)ival;
310 while (t) {
311 ++ndigits;
312 t >>= PyLong_SHIFT;
313 }
314 v = _PyLong_New(ndigits);
315 if (v != NULL) {
316 digit *p = v->ob_digit;
317 Py_SIZE(v) = ndigits;
318 while (ival) {
319 *p++ = (digit)(ival & PyLong_MASK);
320 ival >>= PyLong_SHIFT;
321 }
322 }
323 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000324}
325
Serhiy Storchaka95949422013-08-27 19:40:23 +0300326/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000327
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000329PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyLongObject *v;
332 double frac;
333 int i, ndig, expo, neg;
334 neg = 0;
335 if (Py_IS_INFINITY(dval)) {
336 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000337 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return NULL;
339 }
340 if (Py_IS_NAN(dval)) {
341 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000342 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return NULL;
344 }
345 if (dval < 0.0) {
346 neg = 1;
347 dval = -dval;
348 }
349 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
350 if (expo <= 0)
351 return PyLong_FromLong(0L);
352 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
353 v = _PyLong_New(ndig);
354 if (v == NULL)
355 return NULL;
356 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
357 for (i = ndig; --i >= 0; ) {
358 digit bits = (digit)frac;
359 v->ob_digit[i] = bits;
360 frac = frac - (double)bits;
361 frac = ldexp(frac, PyLong_SHIFT);
362 }
363 if (neg)
364 Py_SIZE(v) = -(Py_SIZE(v));
365 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000366}
367
Thomas Wouters89f507f2006-12-13 04:49:30 +0000368/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
369 * anything about what happens when a signed integer operation overflows,
370 * and some compilers think they're doing you a favor by being "clever"
371 * then. The bit pattern for the largest postive signed long is
372 * (unsigned long)LONG_MAX, and for the smallest negative signed long
373 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
374 * However, some other compilers warn about applying unary minus to an
375 * unsigned operand. Hence the weird "0-".
376 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
378#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000379
Serhiy Storchaka95949422013-08-27 19:40:23 +0300380/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100381 method.
382
383 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
384 the result. Otherwise *overflow is 0.
385
386 For other errors (e.g., TypeError), return -1 and set an error condition.
387 In this case *overflow will be 0.
388*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000389
390long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000391PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200394 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 unsigned long x, prev;
396 long res;
397 Py_ssize_t i;
398 int sign;
399 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 *overflow = 0;
402 if (vv == NULL) {
403 PyErr_BadInternalCall();
404 return -1;
405 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000406
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200407 if (PyLong_Check(vv)) {
408 v = (PyLongObject *)vv;
409 }
410 else {
411 v = _PyLong_FromNbInt(vv);
412 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 return -1;
414 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 switch (i) {
421 case -1:
422 res = -(sdigit)v->ob_digit[0];
423 break;
424 case 0:
425 res = 0;
426 break;
427 case 1:
428 res = v->ob_digit[0];
429 break;
430 default:
431 sign = 1;
432 x = 0;
433 if (i < 0) {
434 sign = -1;
435 i = -(i);
436 }
437 while (--i >= 0) {
438 prev = x;
439 x = (x << PyLong_SHIFT) | v->ob_digit[i];
440 if ((x >> PyLong_SHIFT) != prev) {
441 *overflow = sign;
442 goto exit;
443 }
444 }
445 /* Haven't lost any bits, but casting to long requires extra
446 * care (see comment above).
447 */
448 if (x <= (unsigned long)LONG_MAX) {
449 res = (long)x * sign;
450 }
451 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
452 res = LONG_MIN;
453 }
454 else {
455 *overflow = sign;
456 /* res is already set to -1 */
457 }
458 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000459 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200461 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
463 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000464}
465
Serhiy Storchaka95949422013-08-27 19:40:23 +0300466/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100467 method. Return -1 and set an error if overflow occurs. */
468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000470PyLong_AsLong(PyObject *obj)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 int overflow;
473 long result = PyLong_AsLongAndOverflow(obj, &overflow);
474 if (overflow) {
475 /* XXX: could be cute and give a different
476 message for overflow == -1 */
477 PyErr_SetString(PyExc_OverflowError,
478 "Python int too large to convert to C long");
479 }
480 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000481}
482
Serhiy Storchaka95949422013-08-27 19:40:23 +0300483/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200484 method. Return -1 and set an error if overflow occurs. */
485
486int
487_PyLong_AsInt(PyObject *obj)
488{
489 int overflow;
490 long result = PyLong_AsLongAndOverflow(obj, &overflow);
491 if (overflow || result > INT_MAX || result < INT_MIN) {
492 /* XXX: could be cute and give a different
493 message for overflow == -1 */
494 PyErr_SetString(PyExc_OverflowError,
495 "Python int too large to convert to C int");
496 return -1;
497 }
498 return (int)result;
499}
500
Serhiy Storchaka95949422013-08-27 19:40:23 +0300501/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000502 Returns -1 and sets an error condition if overflow occurs. */
503
504Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200506 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 size_t x, prev;
508 Py_ssize_t i;
509 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (vv == NULL) {
512 PyErr_BadInternalCall();
513 return -1;
514 }
515 if (!PyLong_Check(vv)) {
516 PyErr_SetString(PyExc_TypeError, "an integer is required");
517 return -1;
518 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 v = (PyLongObject *)vv;
521 i = Py_SIZE(v);
522 switch (i) {
523 case -1: return -(sdigit)v->ob_digit[0];
524 case 0: return 0;
525 case 1: return v->ob_digit[0];
526 }
527 sign = 1;
528 x = 0;
529 if (i < 0) {
530 sign = -1;
531 i = -(i);
532 }
533 while (--i >= 0) {
534 prev = x;
535 x = (x << PyLong_SHIFT) | v->ob_digit[i];
536 if ((x >> PyLong_SHIFT) != prev)
537 goto overflow;
538 }
539 /* Haven't lost any bits, but casting to a signed type requires
540 * extra care (see comment above).
541 */
542 if (x <= (size_t)PY_SSIZE_T_MAX) {
543 return (Py_ssize_t)x * sign;
544 }
545 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
546 return PY_SSIZE_T_MIN;
547 }
548 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000549
Mark Dickinson22b20182010-05-10 21:27:53 +0000550 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyErr_SetString(PyExc_OverflowError,
552 "Python int too large to convert to C ssize_t");
553 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000554}
555
Serhiy Storchaka95949422013-08-27 19:40:23 +0300556/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000557 Returns -1 and sets an error condition if overflow occurs. */
558
559unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000560PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000561{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200562 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 unsigned long x, prev;
564 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (vv == NULL) {
567 PyErr_BadInternalCall();
568 return (unsigned long)-1;
569 }
570 if (!PyLong_Check(vv)) {
571 PyErr_SetString(PyExc_TypeError, "an integer is required");
572 return (unsigned long)-1;
573 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 v = (PyLongObject *)vv;
576 i = Py_SIZE(v);
577 x = 0;
578 if (i < 0) {
579 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000580 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return (unsigned long) -1;
582 }
583 switch (i) {
584 case 0: return 0;
585 case 1: return v->ob_digit[0];
586 }
587 while (--i >= 0) {
588 prev = x;
589 x = (x << PyLong_SHIFT) | v->ob_digit[i];
590 if ((x >> PyLong_SHIFT) != prev) {
591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100592 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000593 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return (unsigned long) -1;
595 }
596 }
597 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000598}
599
Serhiy Storchaka95949422013-08-27 19:40:23 +0300600/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200601 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000602
603size_t
604PyLong_AsSize_t(PyObject *vv)
605{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200606 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 size_t x, prev;
608 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (vv == NULL) {
611 PyErr_BadInternalCall();
612 return (size_t) -1;
613 }
614 if (!PyLong_Check(vv)) {
615 PyErr_SetString(PyExc_TypeError, "an integer is required");
616 return (size_t)-1;
617 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 v = (PyLongObject *)vv;
620 i = Py_SIZE(v);
621 x = 0;
622 if (i < 0) {
623 PyErr_SetString(PyExc_OverflowError,
624 "can't convert negative value to size_t");
625 return (size_t) -1;
626 }
627 switch (i) {
628 case 0: return 0;
629 case 1: return v->ob_digit[0];
630 }
631 while (--i >= 0) {
632 prev = x;
633 x = (x << PyLong_SHIFT) | v->ob_digit[i];
634 if ((x >> PyLong_SHIFT) != prev) {
635 PyErr_SetString(PyExc_OverflowError,
636 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200637 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 }
639 }
640 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000641}
642
Serhiy Storchaka95949422013-08-27 19:40:23 +0300643/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000644 Returns -1 and sets an error condition if an error occurs. */
645
Guido van Rossumddefaf32007-01-14 03:31:43 +0000646static unsigned long
647_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000648{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200649 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 unsigned long x;
651 Py_ssize_t i;
652 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (vv == NULL || !PyLong_Check(vv)) {
655 PyErr_BadInternalCall();
656 return (unsigned long) -1;
657 }
658 v = (PyLongObject *)vv;
659 i = Py_SIZE(v);
660 switch (i) {
661 case 0: return 0;
662 case 1: return v->ob_digit[0];
663 }
664 sign = 1;
665 x = 0;
666 if (i < 0) {
667 sign = -1;
668 i = -i;
669 }
670 while (--i >= 0) {
671 x = (x << PyLong_SHIFT) | v->ob_digit[i];
672 }
673 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000674}
675
Guido van Rossumddefaf32007-01-14 03:31:43 +0000676unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200677PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyLongObject *lo;
680 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000681
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200682 if (op == NULL) {
683 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 return (unsigned long)-1;
685 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000686
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200687 if (PyLong_Check(op)) {
688 return _PyLong_AsUnsignedLongMask(op);
689 }
690
691 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (lo == NULL)
693 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200694
695 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
696 Py_DECREF(lo);
697 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698}
699
Tim Peters5b8132f2003-01-31 15:52:05 +0000700int
701_PyLong_Sign(PyObject *vv)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 assert(v != NULL);
706 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000709}
710
Tim Petersbaefd9e2003-01-28 20:37:45 +0000711size_t
712_PyLong_NumBits(PyObject *vv)
713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyLongObject *v = (PyLongObject *)vv;
715 size_t result = 0;
716 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 assert(v != NULL);
719 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200720 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
722 if (ndigits > 0) {
723 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100724 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100726 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 do {
728 ++result;
729 if (result == 0)
730 goto Overflow;
731 msd >>= 1;
732 } while (msd);
733 }
734 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000735
Mark Dickinson22b20182010-05-10 21:27:53 +0000736 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
738 "to express in a platform size_t");
739 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000740}
741
Tim Peters2a9b3672001-06-11 21:23:58 +0000742PyObject *
743_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000745{
Mark Dickinson22b20182010-05-10 21:27:53 +0000746 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 int incr; /* direction to move pstartbyte */
748 const unsigned char* pendbyte; /* MSB of bytes */
749 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300750 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 PyLongObject* v; /* result */
752 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (n == 0)
755 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (little_endian) {
758 pstartbyte = bytes;
759 pendbyte = bytes + n - 1;
760 incr = 1;
761 }
762 else {
763 pstartbyte = bytes + n - 1;
764 pendbyte = bytes;
765 incr = -1;
766 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (is_signed)
769 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200772 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 is positive, and leading 0xff bytes if negative. */
774 {
775 size_t i;
776 const unsigned char* p = pendbyte;
777 const int pincr = -incr; /* search MSB to LSB */
778 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 for (i = 0; i < n; ++i, p += pincr) {
781 if (*p != insignficant)
782 break;
783 }
784 numsignificantbytes = n - i;
785 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
786 actually has 2 significant bytes. OTOH, 0xff0001 ==
787 -0x00ffff, so we wouldn't *need* to bump it there; but we
788 do for 0xffff = -0x0001. To be safe without bothering to
789 check every case, bump it regardless. */
790 if (is_signed && numsignificantbytes < n)
791 ++numsignificantbytes;
792 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000793
Serhiy Storchaka95949422013-08-27 19:40:23 +0300794 /* How many Python int digits do we need? We have
795 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
797 /* catch overflow before it happens */
798 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
799 PyErr_SetString(PyExc_OverflowError,
800 "byte array too long to convert to int");
801 return NULL;
802 }
803 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
804 v = _PyLong_New(ndigits);
805 if (v == NULL)
806 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 /* Copy the bits over. The tricky parts are computing 2's-comp on
809 the fly for signed numbers, and dealing with the mismatch between
810 8-bit bytes and (probably) 15-bit Python digits.*/
811 {
812 size_t i;
813 twodigits carry = 1; /* for 2's-comp calculation */
814 twodigits accum = 0; /* sliding register */
815 unsigned int accumbits = 0; /* number of bits in accum */
816 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
819 twodigits thisbyte = *p;
820 /* Compute correction for 2's comp, if needed. */
821 if (is_signed) {
822 thisbyte = (0xff ^ thisbyte) + carry;
823 carry = thisbyte >> 8;
824 thisbyte &= 0xff;
825 }
826 /* Because we're going LSB to MSB, thisbyte is
827 more significant than what's already in accum,
828 so needs to be prepended to accum. */
829 accum |= (twodigits)thisbyte << accumbits;
830 accumbits += 8;
831 if (accumbits >= PyLong_SHIFT) {
832 /* There's enough to fill a Python digit. */
833 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000834 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 ++idigit;
836 accum >>= PyLong_SHIFT;
837 accumbits -= PyLong_SHIFT;
838 assert(accumbits < PyLong_SHIFT);
839 }
840 }
841 assert(accumbits < PyLong_SHIFT);
842 if (accumbits) {
843 assert(idigit < ndigits);
844 v->ob_digit[idigit] = (digit)accum;
845 ++idigit;
846 }
847 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_SIZE(v) = is_signed ? -idigit : idigit;
850 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000851}
852
853int
854_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 unsigned char* bytes, size_t n,
856 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000859 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000861 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
863 digit carry; /* for computing 2's-comp */
864 size_t j; /* # bytes filled */
865 unsigned char* p; /* pointer to next byte in bytes */
866 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (Py_SIZE(v) < 0) {
871 ndigits = -(Py_SIZE(v));
872 if (!is_signed) {
873 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000874 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return -1;
876 }
877 do_twos_comp = 1;
878 }
879 else {
880 ndigits = Py_SIZE(v);
881 do_twos_comp = 0;
882 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (little_endian) {
885 p = bytes;
886 pincr = 1;
887 }
888 else {
889 p = bytes + n - 1;
890 pincr = -1;
891 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Copy over all the Python digits.
894 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300895 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 normalized. */
897 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
898 j = 0;
899 accum = 0;
900 accumbits = 0;
901 carry = do_twos_comp ? 1 : 0;
902 for (i = 0; i < ndigits; ++i) {
903 digit thisdigit = v->ob_digit[i];
904 if (do_twos_comp) {
905 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
906 carry = thisdigit >> PyLong_SHIFT;
907 thisdigit &= PyLong_MASK;
908 }
909 /* Because we're going LSB to MSB, thisdigit is more
910 significant than what's already in accum, so needs to be
911 prepended to accum. */
912 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* The most-significant digit may be (probably is) at least
915 partly empty. */
916 if (i == ndigits - 1) {
917 /* Count # of sign bits -- they needn't be stored,
918 * although for signed conversion we need later to
919 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000920 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 while (s != 0) {
922 s >>= 1;
923 accumbits++;
924 }
925 }
926 else
927 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Store as many bytes as possible. */
930 while (accumbits >= 8) {
931 if (j >= n)
932 goto Overflow;
933 ++j;
934 *p = (unsigned char)(accum & 0xff);
935 p += pincr;
936 accumbits -= 8;
937 accum >>= 8;
938 }
939 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Store the straggler (if any). */
942 assert(accumbits < 8);
943 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
944 if (accumbits > 0) {
945 if (j >= n)
946 goto Overflow;
947 ++j;
948 if (do_twos_comp) {
949 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300950 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 infinite supply of sign bits). */
952 accum |= (~(twodigits)0) << accumbits;
953 }
954 *p = (unsigned char)(accum & 0xff);
955 p += pincr;
956 }
957 else if (j == n && n > 0 && is_signed) {
958 /* The main loop filled the byte array exactly, so the code
959 just above didn't get to ensure there's a sign bit, and the
960 loop below wouldn't add one either. Make sure a sign bit
961 exists. */
962 unsigned char msb = *(p - pincr);
963 int sign_bit_set = msb >= 0x80;
964 assert(accumbits == 0);
965 if (sign_bit_set == do_twos_comp)
966 return 0;
967 else
968 goto Overflow;
969 }
Tim Peters05607ad2001-06-13 21:01:27 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Fill remaining bytes with copies of the sign bit. */
972 {
973 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
974 for ( ; j < n; ++j, p += pincr)
975 *p = signbyte;
976 }
Tim Peters05607ad2001-06-13 21:01:27 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000979
Mark Dickinson22b20182010-05-10 21:27:53 +0000980 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
982 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000983
Tim Peters2a9b3672001-06-11 21:23:58 +0000984}
985
Serhiy Storchaka95949422013-08-27 19:40:23 +0300986/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000987
988PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000989PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000990{
Mark Dickinson91044792012-10-18 19:21:43 +0100991#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100992 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
993#else
994
Tim Peters70128a12001-06-16 08:48:40 +0000995#ifndef HAVE_LONG_LONG
996# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
997#endif
998#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000999# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001000#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001002#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001003
Guido van Rossum78694d91998-09-18 14:14:13 +00001004}
1005
Serhiy Storchaka95949422013-08-27 19:40:23 +03001006/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001007
1008void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001009PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001010{
Tim Peters70128a12001-06-16 08:48:40 +00001011#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1015 x = PyLong_AsLong(vv);
1016 else
1017 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001018#else
Tim Peters70128a12001-06-16 08:48:40 +00001019
1020#ifndef HAVE_LONG_LONG
1021# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1022#endif
1023#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001024# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001025#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1029 x = PyLong_AsLongLong(vv);
1030 else
1031 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001032
1033#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 if (x == -1 && PyErr_Occurred())
1036 return NULL;
1037 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001038}
1039
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001040#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001041
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001042/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001043 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001044 */
1045
Mark Dickinson22b20182010-05-10 21:27:53 +00001046#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001047
Serhiy Storchaka95949422013-08-27 19:40:23 +03001048/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001049
1050PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001051PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyLongObject *v;
1054 unsigned PY_LONG_LONG abs_ival;
1055 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1056 int ndigits = 0;
1057 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 CHECK_SMALL_INT(ival);
1060 if (ival < 0) {
1061 /* avoid signed overflow on negation; see comments
1062 in PyLong_FromLong above. */
1063 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1064 negative = 1;
1065 }
1066 else {
1067 abs_ival = (unsigned PY_LONG_LONG)ival;
1068 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Count the number of Python digits.
1071 We used to pick 5 ("big enough for anything"), but that's a
1072 waste of time and space given that 5*15 = 75 bits are rarely
1073 needed. */
1074 t = abs_ival;
1075 while (t) {
1076 ++ndigits;
1077 t >>= PyLong_SHIFT;
1078 }
1079 v = _PyLong_New(ndigits);
1080 if (v != NULL) {
1081 digit *p = v->ob_digit;
1082 Py_SIZE(v) = negative ? -ndigits : ndigits;
1083 t = abs_ival;
1084 while (t) {
1085 *p++ = (digit)(t & PyLong_MASK);
1086 t >>= PyLong_SHIFT;
1087 }
1088 }
1089 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001090}
1091
Serhiy Storchaka95949422013-08-27 19:40:23 +03001092/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001093
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001094PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001095PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyLongObject *v;
1098 unsigned PY_LONG_LONG t;
1099 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (ival < PyLong_BASE)
1102 return PyLong_FromLong((long)ival);
1103 /* Count the number of Python digits. */
1104 t = (unsigned PY_LONG_LONG)ival;
1105 while (t) {
1106 ++ndigits;
1107 t >>= PyLong_SHIFT;
1108 }
1109 v = _PyLong_New(ndigits);
1110 if (v != NULL) {
1111 digit *p = v->ob_digit;
1112 Py_SIZE(v) = ndigits;
1113 while (ival) {
1114 *p++ = (digit)(ival & PyLong_MASK);
1115 ival >>= PyLong_SHIFT;
1116 }
1117 }
1118 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001119}
1120
Serhiy Storchaka95949422013-08-27 19:40:23 +03001121/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001122
1123PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001124PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyLongObject *v;
1127 size_t abs_ival;
1128 size_t t; /* unsigned so >> doesn't propagate sign bit */
1129 int ndigits = 0;
1130 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 CHECK_SMALL_INT(ival);
1133 if (ival < 0) {
1134 /* avoid signed overflow when ival = SIZE_T_MIN */
1135 abs_ival = (size_t)(-1-ival)+1;
1136 negative = 1;
1137 }
1138 else {
1139 abs_ival = (size_t)ival;
1140 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Count the number of Python digits. */
1143 t = abs_ival;
1144 while (t) {
1145 ++ndigits;
1146 t >>= PyLong_SHIFT;
1147 }
1148 v = _PyLong_New(ndigits);
1149 if (v != NULL) {
1150 digit *p = v->ob_digit;
1151 Py_SIZE(v) = negative ? -ndigits : ndigits;
1152 t = abs_ival;
1153 while (t) {
1154 *p++ = (digit)(t & PyLong_MASK);
1155 t >>= PyLong_SHIFT;
1156 }
1157 }
1158 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159}
1160
Serhiy Storchaka95949422013-08-27 19:40:23 +03001161/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162
1163PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001164PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyLongObject *v;
1167 size_t t;
1168 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 if (ival < PyLong_BASE)
1171 return PyLong_FromLong((long)ival);
1172 /* Count the number of Python digits. */
1173 t = ival;
1174 while (t) {
1175 ++ndigits;
1176 t >>= PyLong_SHIFT;
1177 }
1178 v = _PyLong_New(ndigits);
1179 if (v != NULL) {
1180 digit *p = v->ob_digit;
1181 Py_SIZE(v) = ndigits;
1182 while (ival) {
1183 *p++ = (digit)(ival & PyLong_MASK);
1184 ival >>= PyLong_SHIFT;
1185 }
1186 }
1187 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188}
1189
Serhiy Storchaka95949422013-08-27 19:40:23 +03001190/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001191 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001192
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001193PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001194PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyLongObject *v;
1197 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001199 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 if (vv == NULL) {
1202 PyErr_BadInternalCall();
1203 return -1;
1204 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001205
1206 if (PyLong_Check(vv)) {
1207 v = (PyLongObject *)vv;
1208 }
1209 else {
1210 v = _PyLong_FromNbInt(vv);
1211 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001213 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001215
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001216 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001218 case -1:
1219 bytes = -(sdigit)v->ob_digit[0];
1220 break;
1221 case 0:
1222 bytes = 0;
1223 break;
1224 case 1:
1225 bytes = v->ob_digit[0];
1226 break;
1227 default:
1228 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001229 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001231 if (do_decref) {
1232 Py_DECREF(v);
1233 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1236 if (res < 0)
1237 return (PY_LONG_LONG)-1;
1238 else
1239 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001240}
1241
Serhiy Storchaka95949422013-08-27 19:40:23 +03001242/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001243 Return -1 and set an error if overflow occurs. */
1244
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001245unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001246PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyLongObject *v;
1249 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001251
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001252 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyErr_BadInternalCall();
1254 return (unsigned PY_LONG_LONG)-1;
1255 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001256 if (!PyLong_Check(vv)) {
1257 PyErr_SetString(PyExc_TypeError, "an integer is required");
1258 return (unsigned PY_LONG_LONG)-1;
1259 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 v = (PyLongObject*)vv;
1262 switch(Py_SIZE(v)) {
1263 case 0: return 0;
1264 case 1: return v->ob_digit[0];
1265 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001266
Mark Dickinson22b20182010-05-10 21:27:53 +00001267 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001268 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1271 if (res < 0)
1272 return (unsigned PY_LONG_LONG)res;
1273 else
1274 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001275}
Tim Petersd1a7da62001-06-13 00:35:57 +00001276
Serhiy Storchaka95949422013-08-27 19:40:23 +03001277/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001278 Returns -1 and sets an error condition if an error occurs. */
1279
Guido van Rossumddefaf32007-01-14 03:31:43 +00001280static unsigned PY_LONG_LONG
1281_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001282{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001283 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 unsigned PY_LONG_LONG x;
1285 Py_ssize_t i;
1286 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (vv == NULL || !PyLong_Check(vv)) {
1289 PyErr_BadInternalCall();
1290 return (unsigned long) -1;
1291 }
1292 v = (PyLongObject *)vv;
1293 switch(Py_SIZE(v)) {
1294 case 0: return 0;
1295 case 1: return v->ob_digit[0];
1296 }
1297 i = Py_SIZE(v);
1298 sign = 1;
1299 x = 0;
1300 if (i < 0) {
1301 sign = -1;
1302 i = -i;
1303 }
1304 while (--i >= 0) {
1305 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1306 }
1307 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001308}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001309
1310unsigned PY_LONG_LONG
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001311PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyLongObject *lo;
1314 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001315
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001316 if (op == NULL) {
1317 PyErr_BadInternalCall();
1318 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001320
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001321 if (PyLong_Check(op)) {
1322 return _PyLong_AsUnsignedLongLongMask(op);
1323 }
1324
1325 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (lo == NULL)
1327 return (unsigned PY_LONG_LONG)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001328
1329 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1330 Py_DECREF(lo);
1331 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001332}
Tim Petersd1a7da62001-06-13 00:35:57 +00001333
Serhiy Storchaka95949422013-08-27 19:40:23 +03001334/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001335 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001336
Mark Dickinson8d48b432011-10-23 20:47:14 +01001337 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1338 the result. Otherwise *overflow is 0.
1339
1340 For other errors (e.g., TypeError), return -1 and set an error condition.
1341 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001342*/
1343
1344PY_LONG_LONG
1345PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001348 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 unsigned PY_LONG_LONG x, prev;
1350 PY_LONG_LONG res;
1351 Py_ssize_t i;
1352 int sign;
1353 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 *overflow = 0;
1356 if (vv == NULL) {
1357 PyErr_BadInternalCall();
1358 return -1;
1359 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001360
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001361 if (PyLong_Check(vv)) {
1362 v = (PyLongObject *)vv;
1363 }
1364 else {
1365 v = _PyLong_FromNbInt(vv);
1366 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 return -1;
1368 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 switch (i) {
1375 case -1:
1376 res = -(sdigit)v->ob_digit[0];
1377 break;
1378 case 0:
1379 res = 0;
1380 break;
1381 case 1:
1382 res = v->ob_digit[0];
1383 break;
1384 default:
1385 sign = 1;
1386 x = 0;
1387 if (i < 0) {
1388 sign = -1;
1389 i = -(i);
1390 }
1391 while (--i >= 0) {
1392 prev = x;
1393 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1394 if ((x >> PyLong_SHIFT) != prev) {
1395 *overflow = sign;
1396 goto exit;
1397 }
1398 }
1399 /* Haven't lost any bits, but casting to long requires extra
1400 * care (see comment above).
1401 */
1402 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1403 res = (PY_LONG_LONG)x * sign;
1404 }
1405 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1406 res = PY_LLONG_MIN;
1407 }
1408 else {
1409 *overflow = sign;
1410 /* res is already set to -1 */
1411 }
1412 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001413 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001415 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 }
1417 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001418}
1419
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001420#endif /* HAVE_LONG_LONG */
1421
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001422#define CHECK_BINOP(v,w) \
1423 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001424 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1425 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001426 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001427
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001428/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1429 2**k if d is nonzero, else 0. */
1430
1431static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1433 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001434};
1435
1436static int
1437bits_in_digit(digit d)
1438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 int d_bits = 0;
1440 while (d >= 32) {
1441 d_bits += 6;
1442 d >>= 6;
1443 }
1444 d_bits += (int)BitLengthTable[d];
1445 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001446}
1447
Tim Peters877a2122002-08-12 05:09:36 +00001448/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1449 * is modified in place, by adding y to it. Carries are propagated as far as
1450 * x[m-1], and the remaining carry (0 or 1) is returned.
1451 */
1452static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001453v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 Py_ssize_t i;
1456 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 assert(m >= n);
1459 for (i = 0; i < n; ++i) {
1460 carry += x[i] + y[i];
1461 x[i] = carry & PyLong_MASK;
1462 carry >>= PyLong_SHIFT;
1463 assert((carry & 1) == carry);
1464 }
1465 for (; carry && i < m; ++i) {
1466 carry += x[i];
1467 x[i] = carry & PyLong_MASK;
1468 carry >>= PyLong_SHIFT;
1469 assert((carry & 1) == carry);
1470 }
1471 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001472}
1473
1474/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1475 * is modified in place, by subtracting y from it. Borrows are propagated as
1476 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1477 */
1478static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001479v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_ssize_t i;
1482 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 assert(m >= n);
1485 for (i = 0; i < n; ++i) {
1486 borrow = x[i] - y[i] - borrow;
1487 x[i] = borrow & PyLong_MASK;
1488 borrow >>= PyLong_SHIFT;
1489 borrow &= 1; /* keep only 1 sign bit */
1490 }
1491 for (; borrow && i < m; ++i) {
1492 borrow = x[i] - borrow;
1493 x[i] = borrow & PyLong_MASK;
1494 borrow >>= PyLong_SHIFT;
1495 borrow &= 1;
1496 }
1497 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001498}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001499
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001500/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1501 * result in z[0:m], and return the d bits shifted out of the top.
1502 */
1503static digit
1504v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 Py_ssize_t i;
1507 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 assert(0 <= d && d < PyLong_SHIFT);
1510 for (i=0; i < m; i++) {
1511 twodigits acc = (twodigits)a[i] << d | carry;
1512 z[i] = (digit)acc & PyLong_MASK;
1513 carry = (digit)(acc >> PyLong_SHIFT);
1514 }
1515 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001516}
1517
1518/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1519 * result in z[0:m], and return the d bits shifted out of the bottom.
1520 */
1521static digit
1522v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_ssize_t i;
1525 digit carry = 0;
1526 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 assert(0 <= d && d < PyLong_SHIFT);
1529 for (i=m; i-- > 0;) {
1530 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1531 carry = (digit)acc & mask;
1532 z[i] = (digit)(acc >> d);
1533 }
1534 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001535}
1536
Tim Peters212e6142001-07-14 12:23:19 +00001537/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1538 in pout, and returning the remainder. pin and pout point at the LSD.
1539 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001540 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001541 immutable. */
1542
1543static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001544inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 assert(n > 0 && n <= PyLong_MASK);
1549 pin += size;
1550 pout += size;
1551 while (--size >= 0) {
1552 digit hi;
1553 rem = (rem << PyLong_SHIFT) | *--pin;
1554 *--pout = hi = (digit)(rem / n);
1555 rem -= (twodigits)hi * n;
1556 }
1557 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001558}
1559
Serhiy Storchaka95949422013-08-27 19:40:23 +03001560/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001561 (as function result) and the remainder (through *prem).
1562 The sign of a is ignored; n should not be zero. */
1563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001564static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001565divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001566{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001567 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 assert(n > 0 && n <= PyLong_MASK);
1571 z = _PyLong_New(size);
1572 if (z == NULL)
1573 return NULL;
1574 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1575 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001576}
1577
Serhiy Storchaka95949422013-08-27 19:40:23 +03001578/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579 string. (Return value is non-shared so that callers can modify the
1580 returned value if necessary.) */
1581
Victor Stinnerd3f08822012-05-29 12:57:52 +02001582static int
1583long_to_decimal_string_internal(PyObject *aa,
1584 PyObject **p_output,
1585 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 PyLongObject *scratch, *a;
1588 PyObject *str;
1589 Py_ssize_t size, strlen, size_a, i, j;
1590 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001592 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 a = (PyLongObject *)aa;
1595 if (a == NULL || !PyLong_Check(a)) {
1596 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001597 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001599 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 /* quick and dirty upper bound for the number of digits
1603 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 But log2(a) < size_a * PyLong_SHIFT, and
1608 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1609 > 3 * _PyLong_DECIMAL_SHIFT
1610 */
1611 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1612 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001613 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001614 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 }
1616 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1617 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1618 scratch = _PyLong_New(size);
1619 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001620 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* convert array of base _PyLong_BASE digits in pin to an array of
1623 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1624 Volume 2 (3rd edn), section 4.4, Method 1b). */
1625 pin = a->ob_digit;
1626 pout = scratch->ob_digit;
1627 size = 0;
1628 for (i = size_a; --i >= 0; ) {
1629 digit hi = pin[i];
1630 for (j = 0; j < size; j++) {
1631 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1632 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1633 pout[j] = (digit)(z - (twodigits)hi *
1634 _PyLong_DECIMAL_BASE);
1635 }
1636 while (hi) {
1637 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1638 hi /= _PyLong_DECIMAL_BASE;
1639 }
1640 /* check for keyboard interrupt */
1641 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001642 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001643 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001644 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 }
1646 /* pout should have at least one digit, so that the case when a = 0
1647 works correctly */
1648 if (size == 0)
1649 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 /* calculate exact length of output string, and allocate */
1652 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1653 tenpow = 10;
1654 rem = pout[size-1];
1655 while (rem >= tenpow) {
1656 tenpow *= 10;
1657 strlen++;
1658 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001659 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001660 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1661 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001662 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001663 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001664 kind = writer->kind;
1665 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001667 else {
1668 str = PyUnicode_New(strlen, '9');
1669 if (str == NULL) {
1670 Py_DECREF(scratch);
1671 return -1;
1672 }
1673 kind = PyUnicode_KIND(str);
1674 }
1675
1676#define WRITE_DIGITS(TYPE) \
1677 do { \
1678 if (writer) \
1679 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1680 else \
1681 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1682 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001683 /* pout[0] through pout[size-2] contribute exactly \
1684 _PyLong_DECIMAL_SHIFT digits each */ \
1685 for (i=0; i < size - 1; i++) { \
1686 rem = pout[i]; \
1687 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1688 *--p = '0' + rem % 10; \
1689 rem /= 10; \
1690 } \
1691 } \
1692 /* pout[size-1]: always produce at least one decimal digit */ \
1693 rem = pout[i]; \
1694 do { \
1695 *--p = '0' + rem % 10; \
1696 rem /= 10; \
1697 } while (rem != 0); \
1698 \
1699 /* and sign */ \
1700 if (negative) \
1701 *--p = '-'; \
1702 \
1703 /* check we've counted correctly */ \
1704 if (writer) \
1705 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1706 else \
1707 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1708 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001711 if (kind == PyUnicode_1BYTE_KIND) {
1712 Py_UCS1 *p;
1713 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001715 else if (kind == PyUnicode_2BYTE_KIND) {
1716 Py_UCS2 *p;
1717 WRITE_DIGITS(Py_UCS2);
1718 }
1719 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001720 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001721 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001722 WRITE_DIGITS(Py_UCS4);
1723 }
1724#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001727 if (writer) {
1728 writer->pos += strlen;
1729 }
1730 else {
1731 assert(_PyUnicode_CheckConsistency(str, 1));
1732 *p_output = (PyObject *)str;
1733 }
1734 return 0;
1735}
1736
1737static PyObject *
1738long_to_decimal_string(PyObject *aa)
1739{
1740 PyObject *v;
1741 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1742 return NULL;
1743 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001744}
1745
Serhiy Storchaka95949422013-08-27 19:40:23 +03001746/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001747 which should be one of 2, 8 or 16. Return a string object.
1748 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1749 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001750
Victor Stinnerd3f08822012-05-29 12:57:52 +02001751static int
1752long_format_binary(PyObject *aa, int base, int alternate,
1753 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001754{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001755 PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001757 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001759 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001760 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001762
Victor Stinnerd3f08822012-05-29 12:57:52 +02001763 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (a == NULL || !PyLong_Check(a)) {
1765 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001766 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001768 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001769 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* Compute a rough upper bound for the length of the string */
1772 switch (base) {
1773 case 16:
1774 bits = 4;
1775 break;
1776 case 8:
1777 bits = 3;
1778 break;
1779 case 2:
1780 bits = 1;
1781 break;
1782 default:
1783 assert(0); /* shouldn't ever get here */
1784 bits = 0; /* to silence gcc warning */
1785 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001786
Mark Dickinsone2846542012-04-20 21:21:24 +01001787 /* Compute exact length 'sz' of output string. */
1788 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001790 }
1791 else {
1792 Py_ssize_t size_a_in_bits;
1793 /* Ensure overflow doesn't occur during computation of sz. */
1794 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1795 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001796 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001797 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001798 }
1799 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1800 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001801 /* Allow 1 character for a '-' sign. */
1802 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1803 }
1804 if (alternate) {
1805 /* 2 characters for prefix */
1806 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001807 }
1808
Victor Stinnerd3f08822012-05-29 12:57:52 +02001809 if (writer) {
1810 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1811 return -1;
1812 kind = writer->kind;
1813 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 }
1815 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001816 v = PyUnicode_New(sz, 'x');
1817 if (v == NULL)
1818 return -1;
1819 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001821
Victor Stinnerd3f08822012-05-29 12:57:52 +02001822#define WRITE_DIGITS(TYPE) \
1823 do { \
1824 if (writer) \
1825 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1826 else \
1827 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1828 \
1829 if (size_a == 0) { \
1830 *--p = '0'; \
1831 } \
1832 else { \
1833 /* JRH: special case for power-of-2 bases */ \
1834 twodigits accum = 0; \
1835 int accumbits = 0; /* # of bits in accum */ \
1836 Py_ssize_t i; \
1837 for (i = 0; i < size_a; ++i) { \
1838 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1839 accumbits += PyLong_SHIFT; \
1840 assert(accumbits >= bits); \
1841 do { \
1842 char cdigit; \
1843 cdigit = (char)(accum & (base - 1)); \
1844 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1845 *--p = cdigit; \
1846 accumbits -= bits; \
1847 accum >>= bits; \
1848 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1849 } \
1850 } \
1851 \
1852 if (alternate) { \
1853 if (base == 16) \
1854 *--p = 'x'; \
1855 else if (base == 8) \
1856 *--p = 'o'; \
1857 else /* (base == 2) */ \
1858 *--p = 'b'; \
1859 *--p = '0'; \
1860 } \
1861 if (negative) \
1862 *--p = '-'; \
1863 if (writer) \
1864 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1865 else \
1866 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1867 } while (0)
1868
1869 if (kind == PyUnicode_1BYTE_KIND) {
1870 Py_UCS1 *p;
1871 WRITE_DIGITS(Py_UCS1);
1872 }
1873 else if (kind == PyUnicode_2BYTE_KIND) {
1874 Py_UCS2 *p;
1875 WRITE_DIGITS(Py_UCS2);
1876 }
1877 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001878 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001879 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001880 WRITE_DIGITS(Py_UCS4);
1881 }
1882#undef WRITE_DIGITS
1883
1884 if (writer) {
1885 writer->pos += sz;
1886 }
1887 else {
1888 assert(_PyUnicode_CheckConsistency(v, 1));
1889 *p_output = v;
1890 }
1891 return 0;
1892}
1893
1894PyObject *
1895_PyLong_Format(PyObject *obj, int base)
1896{
1897 PyObject *str;
1898 int err;
1899 if (base == 10)
1900 err = long_to_decimal_string_internal(obj, &str, NULL);
1901 else
1902 err = long_format_binary(obj, base, 1, &str, NULL);
1903 if (err == -1)
1904 return NULL;
1905 return str;
1906}
1907
1908int
1909_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1910 PyObject *obj,
1911 int base, int alternate)
1912{
1913 if (base == 10)
1914 return long_to_decimal_string_internal(obj, NULL, writer);
1915 else
1916 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001917}
1918
Thomas Wouters477c8d52006-05-27 19:21:47 +00001919/* Table of digit values for 8-bit string -> integer conversion.
1920 * '0' maps to 0, ..., '9' maps to 9.
1921 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1922 * All other indices map to 37.
1923 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001924 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001925 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001926unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1928 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1929 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1930 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1931 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1932 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1933 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1934 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1935 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1936 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1937 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1938 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1939 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001943};
1944
1945/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001946 * 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 +03001947 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001948 * The point to this routine is that it takes time linear in the number of
1949 * string characters.
1950 */
1951static PyLongObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03001952long_from_binary_base(const char **str, int base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001953{
Serhiy Storchakac6792272013-10-19 21:03:34 +03001954 const char *p = *str;
1955 const char *start = p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 int bits_per_char;
1957 Py_ssize_t n;
1958 PyLongObject *z;
1959 twodigits accum;
1960 int bits_in_accum;
1961 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1964 n = base;
1965 for (bits_per_char = -1; n; ++bits_per_char)
1966 n >>= 1;
1967 /* n <- total # of bits needed, while setting p to end-of-string */
1968 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1969 ++p;
1970 *str = p;
1971 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1972 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1973 if (n / bits_per_char < p - start) {
1974 PyErr_SetString(PyExc_ValueError,
1975 "int string too large to convert");
1976 return NULL;
1977 }
1978 n = n / PyLong_SHIFT;
1979 z = _PyLong_New(n);
1980 if (z == NULL)
1981 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001982 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 * from least to most significant in both.
1984 */
1985 accum = 0;
1986 bits_in_accum = 0;
1987 pdigit = z->ob_digit;
1988 while (--p >= start) {
1989 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1990 assert(k >= 0 && k < base);
1991 accum |= (twodigits)k << bits_in_accum;
1992 bits_in_accum += bits_per_char;
1993 if (bits_in_accum >= PyLong_SHIFT) {
1994 *pdigit++ = (digit)(accum & PyLong_MASK);
1995 assert(pdigit - z->ob_digit <= n);
1996 accum >>= PyLong_SHIFT;
1997 bits_in_accum -= PyLong_SHIFT;
1998 assert(bits_in_accum < PyLong_SHIFT);
1999 }
2000 }
2001 if (bits_in_accum) {
2002 assert(bits_in_accum <= PyLong_SHIFT);
2003 *pdigit++ = (digit)accum;
2004 assert(pdigit - z->ob_digit <= n);
2005 }
2006 while (pdigit - z->ob_digit < n)
2007 *pdigit++ = 0;
2008 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002009}
2010
Serhiy Storchaka95949422013-08-27 19:40:23 +03002011/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002012 * ignored.
2013 *
2014 * If successful, a PyLong object will be returned and 'pend' will be pointing
2015 * to the first unused byte unless it's NULL.
2016 *
2017 * If unsuccessful, NULL will be returned.
2018 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002020PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002023 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyLongObject *z = NULL;
2025 PyObject *strobj;
2026 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if ((base != 0 && base < 2) || base > 36) {
2029 PyErr_SetString(PyExc_ValueError,
2030 "int() arg 2 must be >= 2 and <= 36");
2031 return NULL;
2032 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002033 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 str++;
2035 if (*str == '+')
2036 ++str;
2037 else if (*str == '-') {
2038 ++str;
2039 sign = -1;
2040 }
2041 if (base == 0) {
2042 if (str[0] != '0')
2043 base = 10;
2044 else if (str[1] == 'x' || str[1] == 'X')
2045 base = 16;
2046 else if (str[1] == 'o' || str[1] == 'O')
2047 base = 8;
2048 else if (str[1] == 'b' || str[1] == 'B')
2049 base = 2;
2050 else {
2051 /* "old" (C-style) octal literal, now invalid.
2052 it might still be zero though */
2053 error_if_nonzero = 1;
2054 base = 10;
2055 }
2056 }
2057 if (str[0] == '0' &&
2058 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2059 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2060 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2061 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 start = str;
2064 if ((base & (base - 1)) == 0)
2065 z = long_from_binary_base(&str, base);
2066 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002067/***
2068Binary bases can be converted in time linear in the number of digits, because
2069Python's representation base is binary. Other bases (including decimal!) use
2070the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002071
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072First some math: the largest integer that can be expressed in N base-B digits
2073is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2074case number of Python digits needed to hold it is the smallest integer n s.t.
2075
2076 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2077 BASE**n >= B**N [taking logs to base BASE]
2078 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2079
2080The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002081this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002082and the result is computed into it.
2083
2084The input string is actually treated as being in base base**i (i.e., i digits
2085are processed at a time), where two more static arrays hold:
2086
2087 convwidth_base[base] = the largest integer i such that base**i <= BASE
2088 convmultmax_base[base] = base ** convwidth_base[base]
2089
2090The first of these is the largest i such that i consecutive input digits
2091must fit in a single Python digit. The second is effectively the input
2092base we're really using.
2093
2094Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2095convmultmax_base[base], the result is "simply"
2096
2097 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2098
2099where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002100
2101Error analysis: as above, the number of Python digits `n` needed is worst-
2102case
2103
2104 n >= N * log(B)/log(BASE)
2105
2106where `N` is the number of input digits in base `B`. This is computed via
2107
2108 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2109
2110below. Two numeric concerns are how much space this can waste, and whether
2111the computed result can be too small. To be concrete, assume BASE = 2**15,
2112which is the default (and it's unlikely anyone changes that).
2113
2114Waste isn't a problem: provided the first input digit isn't 0, the difference
2115between the worst-case input with N digits and the smallest input with N
2116digits is about a factor of B, but B is small compared to BASE so at most
2117one allocated Python digit can remain unused on that count. If
2118N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2119and adding 1 returns a result 1 larger than necessary. However, that can't
2120happen: whenever B is a power of 2, long_from_binary_base() is called
2121instead, and it's impossible for B**i to be an integer power of 2**15 when
2122B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2123an exact integer when B is not a power of 2, since B**i has a prime factor
2124other than 2 in that case, but (2**15)**j's only prime factor is 2).
2125
2126The computed result can be too small if the true value of N*log(B)/log(BASE)
2127is a little bit larger than an exact integer, but due to roundoff errors (in
2128computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2129yields a numeric result a little less than that integer. Unfortunately, "how
2130close can a transcendental function get to an integer over some range?"
2131questions are generally theoretically intractable. Computer analysis via
2132continued fractions is practical: expand log(B)/log(BASE) via continued
2133fractions, giving a sequence i/j of "the best" rational approximations. Then
2134j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2135we can get very close to being in trouble, but very rarely. For example,
213676573 is a denominator in one of the continued-fraction approximations to
2137log(10)/log(2**15), and indeed:
2138
2139 >>> log(10)/log(2**15)*76573
2140 16958.000000654003
2141
2142is very close to an integer. If we were working with IEEE single-precision,
2143rounding errors could kill us. Finding worst cases in IEEE double-precision
2144requires better-than-double-precision log() functions, and Tim didn't bother.
2145Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002146new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002147This should happen extremely rarely, and in fact I don't have a test case
2148that triggers it(!). Instead the code was tested by artificially allocating
2149just 1 digit at the start, so that the copying code was exercised for every
2150digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002151***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002152 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 Py_ssize_t size_z;
2154 int i;
2155 int convwidth;
2156 twodigits convmultmax, convmult;
2157 digit *pz, *pzstop;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002158 const char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 static double log_base_BASE[37] = {0.0e0,};
2161 static int convwidth_base[37] = {0,};
2162 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (log_base_BASE[base] == 0.0) {
2165 twodigits convmax = base;
2166 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002167
Mark Dickinson22b20182010-05-10 21:27:53 +00002168 log_base_BASE[base] = (log((double)base) /
2169 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 for (;;) {
2171 twodigits next = convmax * base;
2172 if (next > PyLong_BASE)
2173 break;
2174 convmax = next;
2175 ++i;
2176 }
2177 convmultmax_base[base] = convmax;
2178 assert(i > 0);
2179 convwidth_base[base] = i;
2180 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 /* Find length of the string of numeric characters. */
2183 scan = str;
2184 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2185 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002186
Serhiy Storchaka95949422013-08-27 19:40:23 +03002187 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 * integer with this base and length. Note that there's no
2189 * need to initialize z->ob_digit -- no slot is read up before
2190 * being stored into.
2191 */
2192 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2193 /* Uncomment next line to test exceedingly rare copy code */
2194 /* size_z = 1; */
2195 assert(size_z > 0);
2196 z = _PyLong_New(size_z);
2197 if (z == NULL)
2198 return NULL;
2199 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 /* `convwidth` consecutive input digits are treated as a single
2202 * digit in base `convmultmax`.
2203 */
2204 convwidth = convwidth_base[base];
2205 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 /* Work ;-) */
2208 while (str < scan) {
2209 /* grab up to convwidth digits from the input string */
2210 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2211 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2212 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002213 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 assert(c < PyLong_BASE);
2215 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 convmult = convmultmax;
2218 /* Calculate the shift only if we couldn't get
2219 * convwidth digits.
2220 */
2221 if (i != convwidth) {
2222 convmult = base;
2223 for ( ; i > 1; --i)
2224 convmult *= base;
2225 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /* Multiply z by convmult, and add c. */
2228 pz = z->ob_digit;
2229 pzstop = pz + Py_SIZE(z);
2230 for (; pz < pzstop; ++pz) {
2231 c += (twodigits)*pz * convmult;
2232 *pz = (digit)(c & PyLong_MASK);
2233 c >>= PyLong_SHIFT;
2234 }
2235 /* carry off the current end? */
2236 if (c) {
2237 assert(c < PyLong_BASE);
2238 if (Py_SIZE(z) < size_z) {
2239 *pz = (digit)c;
2240 ++Py_SIZE(z);
2241 }
2242 else {
2243 PyLongObject *tmp;
2244 /* Extremely rare. Get more space. */
2245 assert(Py_SIZE(z) == size_z);
2246 tmp = _PyLong_New(size_z + 1);
2247 if (tmp == NULL) {
2248 Py_DECREF(z);
2249 return NULL;
2250 }
2251 memcpy(tmp->ob_digit,
2252 z->ob_digit,
2253 sizeof(digit) * size_z);
2254 Py_DECREF(z);
2255 z = tmp;
2256 z->ob_digit[size_z] = (digit)c;
2257 ++size_z;
2258 }
2259 }
2260 }
2261 }
2262 if (z == NULL)
2263 return NULL;
2264 if (error_if_nonzero) {
2265 /* reset the base to 0, else the exception message
2266 doesn't make too much sense */
2267 base = 0;
2268 if (Py_SIZE(z) != 0)
2269 goto onError;
2270 /* there might still be other problems, therefore base
2271 remains zero here for the same reason */
2272 }
2273 if (str == start)
2274 goto onError;
2275 if (sign < 0)
2276 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002277 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 str++;
2279 if (*str != '\0')
2280 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002282 z = maybe_small_long(z);
2283 if (z == NULL)
2284 return NULL;
2285 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002286 *pend = (char *)str;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002287 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002288
Mark Dickinson22b20182010-05-10 21:27:53 +00002289 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002290 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002291 *pend = (char *)str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 Py_XDECREF(z);
2293 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2294 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2295 if (strobj == NULL)
2296 return NULL;
2297 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002298 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 base, strobj);
2300 Py_DECREF(strobj);
2301 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002302}
2303
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002304/* Since PyLong_FromString doesn't have a length parameter,
2305 * check here for possible NULs in the string.
2306 *
2307 * Reports an invalid literal as a bytes object.
2308 */
2309PyObject *
2310_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2311{
2312 PyObject *result, *strobj;
2313 char *end = NULL;
2314
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002315 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002316 if (end == NULL || (result != NULL && end == s + len))
2317 return result;
2318 Py_XDECREF(result);
2319 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2320 if (strobj != NULL) {
2321 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002322 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002323 base, strobj);
2324 Py_DECREF(strobj);
2325 }
2326 return NULL;
2327}
2328
Guido van Rossum9e896b32000-04-05 20:11:21 +00002329PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002330PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002331{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002332 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2333 if (unicode == NULL)
2334 return NULL;
2335 v = PyLong_FromUnicodeObject(unicode, base);
2336 Py_DECREF(unicode);
2337 return v;
2338}
2339
2340PyObject *
2341PyLong_FromUnicodeObject(PyObject *u, int base)
2342{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002343 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002344 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002345 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002347 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002348 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002350 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002351 if (buffer == NULL) {
2352 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002353 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2354 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002356 else {
2357 result = PyLong_FromString(buffer, &end, base);
2358 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2359 Py_DECREF(asciidig);
2360 return result;
2361 }
2362 Py_DECREF(asciidig);
2363 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002364 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002365 PyErr_Format(PyExc_ValueError,
2366 "invalid literal for int() with base %d: %.200R",
2367 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002368 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002369}
2370
Tim Peters9f688bf2000-07-07 15:53:28 +00002371/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002372static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002374static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002375
Serhiy Storchaka95949422013-08-27 19:40:23 +03002376/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002377
Guido van Rossume32e0141992-01-19 16:31:05 +00002378static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002379long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002381{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002382 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (size_b == 0) {
2386 PyErr_SetString(PyExc_ZeroDivisionError,
2387 "integer division or modulo by zero");
2388 return -1;
2389 }
2390 if (size_a < size_b ||
2391 (size_a == size_b &&
2392 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2393 /* |a| < |b|. */
2394 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2395 if (*pdiv == NULL)
2396 return -1;
2397 Py_INCREF(a);
2398 *prem = (PyLongObject *) a;
2399 return 0;
2400 }
2401 if (size_b == 1) {
2402 digit rem = 0;
2403 z = divrem1(a, b->ob_digit[0], &rem);
2404 if (z == NULL)
2405 return -1;
2406 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2407 if (*prem == NULL) {
2408 Py_DECREF(z);
2409 return -1;
2410 }
2411 }
2412 else {
2413 z = x_divrem(a, b, prem);
2414 if (z == NULL)
2415 return -1;
2416 }
2417 /* Set the signs.
2418 The quotient z has the sign of a*b;
2419 the remainder r has the sign of a,
2420 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002421 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2422 _PyLong_Negate(&z);
2423 if (z == NULL) {
2424 Py_CLEAR(*prem);
2425 return -1;
2426 }
2427 }
2428 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2429 _PyLong_Negate(prem);
2430 if (*prem == NULL) {
2431 Py_DECREF(z);
2432 Py_CLEAR(*prem);
2433 return -1;
2434 }
2435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 *pdiv = maybe_small_long(z);
2437 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002438}
2439
Serhiy Storchaka95949422013-08-27 19:40:23 +03002440/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002441 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002442
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002443static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002444x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 PyLongObject *v, *w, *a;
2447 Py_ssize_t i, k, size_v, size_w;
2448 int d;
2449 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2450 twodigits vv;
2451 sdigit zhi;
2452 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2455 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2456 handle the special case when the initial estimate q for a quotient
2457 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2458 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002461 size_v = Py_ABS(Py_SIZE(v1));
2462 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2464 v = _PyLong_New(size_v+1);
2465 if (v == NULL) {
2466 *prem = NULL;
2467 return NULL;
2468 }
2469 w = _PyLong_New(size_w);
2470 if (w == NULL) {
2471 Py_DECREF(v);
2472 *prem = NULL;
2473 return NULL;
2474 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2477 shift v1 left by the same amount. Results go into w and v. */
2478 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2479 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2480 assert(carry == 0);
2481 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2482 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2483 v->ob_digit[size_v] = carry;
2484 size_v++;
2485 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2488 at most (and usually exactly) k = size_v - size_w digits. */
2489 k = size_v - size_w;
2490 assert(k >= 0);
2491 a = _PyLong_New(k);
2492 if (a == NULL) {
2493 Py_DECREF(w);
2494 Py_DECREF(v);
2495 *prem = NULL;
2496 return NULL;
2497 }
2498 v0 = v->ob_digit;
2499 w0 = w->ob_digit;
2500 wm1 = w0[size_w-1];
2501 wm2 = w0[size_w-2];
2502 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2503 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2504 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002507 Py_DECREF(a);
2508 Py_DECREF(w);
2509 Py_DECREF(v);
2510 *prem = NULL;
2511 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002512 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* estimate quotient digit q; may overestimate by 1 (rare) */
2515 vtop = vk[size_w];
2516 assert(vtop <= wm1);
2517 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2518 q = (digit)(vv / wm1);
2519 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2520 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2521 | vk[size_w-2])) {
2522 --q;
2523 r += wm1;
2524 if (r >= PyLong_BASE)
2525 break;
2526 }
2527 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2530 zhi = 0;
2531 for (i = 0; i < size_w; ++i) {
2532 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2533 -PyLong_BASE * q <= z < PyLong_BASE */
2534 z = (sdigit)vk[i] + zhi -
2535 (stwodigits)q * (stwodigits)w0[i];
2536 vk[i] = (digit)z & PyLong_MASK;
2537 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002538 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 /* add w back if q was too large (this branch taken rarely) */
2542 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2543 if ((sdigit)vtop + zhi < 0) {
2544 carry = 0;
2545 for (i = 0; i < size_w; ++i) {
2546 carry += vk[i] + w0[i];
2547 vk[i] = carry & PyLong_MASK;
2548 carry >>= PyLong_SHIFT;
2549 }
2550 --q;
2551 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 /* store quotient digit */
2554 assert(q < PyLong_BASE);
2555 *--ak = q;
2556 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 /* unshift remainder; we reuse w to store the result */
2559 carry = v_rshift(w0, v0, size_w, d);
2560 assert(carry==0);
2561 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 *prem = long_normalize(w);
2564 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002565}
2566
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002567/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2568 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2569 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2570 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2571 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2572 -1.0. */
2573
2574/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2575#if DBL_MANT_DIG == 53
2576#define EXP2_DBL_MANT_DIG 9007199254740992.0
2577#else
2578#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2579#endif
2580
2581double
2582_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2585 /* See below for why x_digits is always large enough. */
2586 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2587 double dx;
2588 /* Correction term for round-half-to-even rounding. For a digit x,
2589 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2590 multiple of 4, rounding ties to a multiple of 8. */
2591 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002592
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002593 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 if (a_size == 0) {
2595 /* Special case for 0: significand 0.0, exponent 0. */
2596 *e = 0;
2597 return 0.0;
2598 }
2599 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2600 /* The following is an overflow-free version of the check
2601 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2602 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2603 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2604 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002605 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2609 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 Number of digits needed for result: write // for floor division.
2612 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2621 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2624 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2625 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 in both cases.
2632 */
2633 if (a_bits <= DBL_MANT_DIG + 2) {
2634 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2635 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2636 x_size = 0;
2637 while (x_size < shift_digits)
2638 x_digits[x_size++] = 0;
2639 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2640 (int)shift_bits);
2641 x_size += a_size;
2642 x_digits[x_size++] = rem;
2643 }
2644 else {
2645 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2646 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2647 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2648 a_size - shift_digits, (int)shift_bits);
2649 x_size = a_size - shift_digits;
2650 /* For correct rounding below, we need the least significant
2651 bit of x to be 'sticky' for this shift: if any of the bits
2652 shifted out was nonzero, we set the least significant bit
2653 of x. */
2654 if (rem)
2655 x_digits[0] |= 1;
2656 else
2657 while (shift_digits > 0)
2658 if (a->ob_digit[--shift_digits]) {
2659 x_digits[0] |= 1;
2660 break;
2661 }
2662 }
Victor Stinner63941882011-09-29 00:42:28 +02002663 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 /* Round, and convert to double. */
2666 x_digits[0] += half_even_correction[x_digits[0] & 7];
2667 dx = x_digits[--x_size];
2668 while (x_size > 0)
2669 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 /* Rescale; make correction if result is 1.0. */
2672 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2673 if (dx == 1.0) {
2674 if (a_bits == PY_SSIZE_T_MAX)
2675 goto overflow;
2676 dx = 0.5;
2677 a_bits += 1;
2678 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 *e = a_bits;
2681 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002682
2683 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 /* exponent > PY_SSIZE_T_MAX */
2685 PyErr_SetString(PyExc_OverflowError,
2686 "huge integer: number of bits overflows a Py_ssize_t");
2687 *e = 0;
2688 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002689}
2690
Serhiy Storchaka95949422013-08-27 19:40:23 +03002691/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002692 using the round-half-to-even rule in the case of a tie. */
2693
2694double
2695PyLong_AsDouble(PyObject *v)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 Py_ssize_t exponent;
2698 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002699
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002700 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 PyErr_BadInternalCall();
2702 return -1.0;
2703 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002704 if (!PyLong_Check(v)) {
2705 PyErr_SetString(PyExc_TypeError, "an integer is required");
2706 return -1.0;
2707 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2709 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2710 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002711 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 return -1.0;
2713 }
2714 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002715}
2716
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002717/* Methods */
2718
2719static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002720long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002723}
2724
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002725static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002726long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 if (Py_SIZE(a) != Py_SIZE(b)) {
2731 sign = Py_SIZE(a) - Py_SIZE(b);
2732 }
2733 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002734 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2736 ;
2737 if (i < 0)
2738 sign = 0;
2739 else {
2740 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2741 if (Py_SIZE(a) < 0)
2742 sign = -sign;
2743 }
2744 }
2745 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002746}
2747
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002748#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002750
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002751static PyObject *
2752long_richcompare(PyObject *self, PyObject *other, int op)
2753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 int result;
2755 PyObject *v;
2756 CHECK_BINOP(self, other);
2757 if (self == other)
2758 result = 0;
2759 else
2760 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2761 /* Convert the return value to a Boolean */
2762 switch (op) {
2763 case Py_EQ:
2764 v = TEST_COND(result == 0);
2765 break;
2766 case Py_NE:
2767 v = TEST_COND(result != 0);
2768 break;
2769 case Py_LE:
2770 v = TEST_COND(result <= 0);
2771 break;
2772 case Py_GE:
2773 v = TEST_COND(result >= 0);
2774 break;
2775 case Py_LT:
2776 v = TEST_COND(result == -1);
2777 break;
2778 case Py_GT:
2779 v = TEST_COND(result == 1);
2780 break;
2781 default:
2782 PyErr_BadArgument();
2783 return NULL;
2784 }
2785 Py_INCREF(v);
2786 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002787}
2788
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002789static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002790long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002791{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002792 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 Py_ssize_t i;
2794 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 i = Py_SIZE(v);
2797 switch(i) {
2798 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2799 case 0: return 0;
2800 case 1: return v->ob_digit[0];
2801 }
2802 sign = 1;
2803 x = 0;
2804 if (i < 0) {
2805 sign = -1;
2806 i = -(i);
2807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002809 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2810 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2811 _PyHASH_MODULUS.
2812
2813 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2814 amounts to a rotation of the bits of x. To see this, write
2815
2816 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2817
2818 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2819 PyLong_SHIFT bits of x (those that are shifted out of the
2820 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2821 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2822 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2823 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2824 congruent to y modulo _PyHASH_MODULUS. So
2825
2826 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2827
2828 The right-hand side is just the result of rotating the
2829 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2830 not all _PyHASH_BITS bits of x are 1s, the same is true
2831 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2832 the reduction of x*2**PyLong_SHIFT modulo
2833 _PyHASH_MODULUS. */
2834 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2835 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002837 if (x >= _PyHASH_MODULUS)
2838 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 }
2840 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002841 if (x == (Py_uhash_t)-1)
2842 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002843 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002844}
2845
2846
Serhiy Storchaka95949422013-08-27 19:40:23 +03002847/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002848
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002849static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002850x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002851{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002852 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 PyLongObject *z;
2854 Py_ssize_t i;
2855 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 /* Ensure a is the larger of the two: */
2858 if (size_a < size_b) {
2859 { PyLongObject *temp = a; a = b; b = temp; }
2860 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002861 size_a = size_b;
2862 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 }
2864 z = _PyLong_New(size_a+1);
2865 if (z == NULL)
2866 return NULL;
2867 for (i = 0; i < size_b; ++i) {
2868 carry += a->ob_digit[i] + b->ob_digit[i];
2869 z->ob_digit[i] = carry & PyLong_MASK;
2870 carry >>= PyLong_SHIFT;
2871 }
2872 for (; i < size_a; ++i) {
2873 carry += a->ob_digit[i];
2874 z->ob_digit[i] = carry & PyLong_MASK;
2875 carry >>= PyLong_SHIFT;
2876 }
2877 z->ob_digit[i] = carry;
2878 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002879}
2880
2881/* Subtract the absolute values of two integers. */
2882
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002883static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002884x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002885{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002886 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyLongObject *z;
2888 Py_ssize_t i;
2889 int sign = 1;
2890 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 /* Ensure a is the larger of the two: */
2893 if (size_a < size_b) {
2894 sign = -1;
2895 { PyLongObject *temp = a; a = b; b = temp; }
2896 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002897 size_a = size_b;
2898 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 }
2900 else if (size_a == size_b) {
2901 /* Find highest digit where a and b differ: */
2902 i = size_a;
2903 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2904 ;
2905 if (i < 0)
2906 return (PyLongObject *)PyLong_FromLong(0);
2907 if (a->ob_digit[i] < b->ob_digit[i]) {
2908 sign = -1;
2909 { PyLongObject *temp = a; a = b; b = temp; }
2910 }
2911 size_a = size_b = i+1;
2912 }
2913 z = _PyLong_New(size_a);
2914 if (z == NULL)
2915 return NULL;
2916 for (i = 0; i < size_b; ++i) {
2917 /* The following assumes unsigned arithmetic
2918 works module 2**N for some N>PyLong_SHIFT. */
2919 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2920 z->ob_digit[i] = borrow & PyLong_MASK;
2921 borrow >>= PyLong_SHIFT;
2922 borrow &= 1; /* Keep only one sign bit */
2923 }
2924 for (; i < size_a; ++i) {
2925 borrow = a->ob_digit[i] - borrow;
2926 z->ob_digit[i] = borrow & PyLong_MASK;
2927 borrow >>= PyLong_SHIFT;
2928 borrow &= 1; /* Keep only one sign bit */
2929 }
2930 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002931 if (sign < 0) {
2932 _PyLong_Negate(&z);
2933 if (z == NULL)
2934 return NULL;
2935 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002937}
2938
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002939static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002940long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002942 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002945
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002946 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2948 MEDIUM_VALUE(b));
2949 return result;
2950 }
2951 if (Py_SIZE(a) < 0) {
2952 if (Py_SIZE(b) < 0) {
2953 z = x_add(a, b);
2954 if (z != NULL && Py_SIZE(z) != 0)
2955 Py_SIZE(z) = -(Py_SIZE(z));
2956 }
2957 else
2958 z = x_sub(b, a);
2959 }
2960 else {
2961 if (Py_SIZE(b) < 0)
2962 z = x_sub(a, b);
2963 else
2964 z = x_add(a, b);
2965 }
2966 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002967}
2968
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002969static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002970long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002975
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002976 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 PyObject* r;
2978 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2979 return r;
2980 }
2981 if (Py_SIZE(a) < 0) {
2982 if (Py_SIZE(b) < 0)
2983 z = x_sub(a, b);
2984 else
2985 z = x_add(a, b);
2986 if (z != NULL && Py_SIZE(z) != 0)
2987 Py_SIZE(z) = -(Py_SIZE(z));
2988 }
2989 else {
2990 if (Py_SIZE(b) < 0)
2991 z = x_add(a, b);
2992 else
2993 z = x_sub(a, b);
2994 }
2995 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002996}
2997
Tim Peters5af4e6c2002-08-12 02:31:19 +00002998/* Grade school multiplication, ignoring the signs.
2999 * Returns the absolute value of the product, or NULL if error.
3000 */
3001static PyLongObject *
3002x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003005 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3006 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 z = _PyLong_New(size_a + size_b);
3010 if (z == NULL)
3011 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003013 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3014 if (a == b) {
3015 /* Efficient squaring per HAC, Algorithm 14.16:
3016 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3017 * Gives slightly less than a 2x speedup when a == b,
3018 * via exploiting that each entry in the multiplication
3019 * pyramid appears twice (except for the size_a squares).
3020 */
3021 for (i = 0; i < size_a; ++i) {
3022 twodigits carry;
3023 twodigits f = a->ob_digit[i];
3024 digit *pz = z->ob_digit + (i << 1);
3025 digit *pa = a->ob_digit + i + 1;
3026 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003028 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003029 Py_DECREF(z);
3030 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003031 });
Tim Peters0973b992004-08-29 22:16:50 +00003032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 carry = *pz + f * f;
3034 *pz++ = (digit)(carry & PyLong_MASK);
3035 carry >>= PyLong_SHIFT;
3036 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 /* Now f is added in twice in each column of the
3039 * pyramid it appears. Same as adding f<<1 once.
3040 */
3041 f <<= 1;
3042 while (pa < paend) {
3043 carry += *pz + *pa++ * f;
3044 *pz++ = (digit)(carry & PyLong_MASK);
3045 carry >>= PyLong_SHIFT;
3046 assert(carry <= (PyLong_MASK << 1));
3047 }
3048 if (carry) {
3049 carry += *pz;
3050 *pz++ = (digit)(carry & PyLong_MASK);
3051 carry >>= PyLong_SHIFT;
3052 }
3053 if (carry)
3054 *pz += (digit)(carry & PyLong_MASK);
3055 assert((carry >> PyLong_SHIFT) == 0);
3056 }
3057 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003058 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 for (i = 0; i < size_a; ++i) {
3060 twodigits carry = 0;
3061 twodigits f = a->ob_digit[i];
3062 digit *pz = z->ob_digit + i;
3063 digit *pb = b->ob_digit;
3064 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003067 Py_DECREF(z);
3068 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003069 });
Tim Peters0973b992004-08-29 22:16:50 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 while (pb < pbend) {
3072 carry += *pz + *pb++ * f;
3073 *pz++ = (digit)(carry & PyLong_MASK);
3074 carry >>= PyLong_SHIFT;
3075 assert(carry <= PyLong_MASK);
3076 }
3077 if (carry)
3078 *pz += (digit)(carry & PyLong_MASK);
3079 assert((carry >> PyLong_SHIFT) == 0);
3080 }
3081 }
3082 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003083}
3084
3085/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003086 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003087 split, and sets low and high such that abs(n) == (high << size) + low,
3088 viewing the shift as being by digits. The sign bit is ignored, and
3089 the return values are >= 0.
3090 Returns 0 on success, -1 on failure.
3091*/
3092static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003093kmul_split(PyLongObject *n,
3094 Py_ssize_t size,
3095 PyLongObject **high,
3096 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 PyLongObject *hi, *lo;
3099 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003100 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003101
Victor Stinner640c35c2013-06-04 23:14:37 +02003102 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 if ((hi = _PyLong_New(size_hi)) == NULL)
3106 return -1;
3107 if ((lo = _PyLong_New(size_lo)) == NULL) {
3108 Py_DECREF(hi);
3109 return -1;
3110 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3113 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 *high = long_normalize(hi);
3116 *low = long_normalize(lo);
3117 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003118}
3119
Tim Peters60004642002-08-12 22:01:34 +00003120static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3121
Tim Peters5af4e6c2002-08-12 02:31:19 +00003122/* Karatsuba multiplication. Ignores the input signs, and returns the
3123 * absolute value of the product (or NULL if error).
3124 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3125 */
3126static PyLongObject *
3127k_mul(PyLongObject *a, PyLongObject *b)
3128{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003129 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3130 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 PyLongObject *ah = NULL;
3132 PyLongObject *al = NULL;
3133 PyLongObject *bh = NULL;
3134 PyLongObject *bl = NULL;
3135 PyLongObject *ret = NULL;
3136 PyLongObject *t1, *t2, *t3;
3137 Py_ssize_t shift; /* the number of digits we split off */
3138 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3141 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3142 * Then the original product is
3143 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3144 * By picking X to be a power of 2, "*X" is just shifting, and it's
3145 * been reduced to 3 multiplies on numbers half the size.
3146 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 /* We want to split based on the larger number; fiddle so that b
3149 * is largest.
3150 */
3151 if (asize > bsize) {
3152 t1 = a;
3153 a = b;
3154 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 i = asize;
3157 asize = bsize;
3158 bsize = i;
3159 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 /* Use gradeschool math when either number is too small. */
3162 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3163 if (asize <= i) {
3164 if (asize == 0)
3165 return (PyLongObject *)PyLong_FromLong(0);
3166 else
3167 return x_mul(a, b);
3168 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 /* If a is small compared to b, splitting on b gives a degenerate
3171 * case with ah==0, and Karatsuba may be (even much) less efficient
3172 * than "grade school" then. However, we can still win, by viewing
3173 * b as a string of "big digits", each of width a->ob_size. That
3174 * leads to a sequence of balanced calls to k_mul.
3175 */
3176 if (2 * asize <= bsize)
3177 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 /* Split a & b into hi & lo pieces. */
3180 shift = bsize >> 1;
3181 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3182 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 if (a == b) {
3185 bh = ah;
3186 bl = al;
3187 Py_INCREF(bh);
3188 Py_INCREF(bl);
3189 }
3190 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 /* The plan:
3193 * 1. Allocate result space (asize + bsize digits: that's always
3194 * enough).
3195 * 2. Compute ah*bh, and copy into result at 2*shift.
3196 * 3. Compute al*bl, and copy into result at 0. Note that this
3197 * can't overlap with #2.
3198 * 4. Subtract al*bl from the result, starting at shift. This may
3199 * underflow (borrow out of the high digit), but we don't care:
3200 * we're effectively doing unsigned arithmetic mod
3201 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3202 * borrows and carries out of the high digit can be ignored.
3203 * 5. Subtract ah*bh from the result, starting at shift.
3204 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3205 * at shift.
3206 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 /* 1. Allocate result space. */
3209 ret = _PyLong_New(asize + bsize);
3210 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003211#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 /* Fill with trash, to catch reference to uninitialized digits. */
3213 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003214#endif
Tim Peters44121a62002-08-12 06:17:58 +00003215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3217 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3218 assert(Py_SIZE(t1) >= 0);
3219 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3220 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3221 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 /* Zero-out the digits higher than the ah*bh copy. */
3224 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3225 if (i)
3226 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3227 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 /* 3. t2 <- al*bl, and copy into the low digits. */
3230 if ((t2 = k_mul(al, bl)) == NULL) {
3231 Py_DECREF(t1);
3232 goto fail;
3233 }
3234 assert(Py_SIZE(t2) >= 0);
3235 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3236 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 /* Zero out remaining digits. */
3239 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3240 if (i)
3241 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3244 * because it's fresher in cache.
3245 */
3246 i = Py_SIZE(ret) - shift; /* # digits after shift */
3247 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3248 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3251 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3254 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3255 Py_DECREF(ah);
3256 Py_DECREF(al);
3257 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 if (a == b) {
3260 t2 = t1;
3261 Py_INCREF(t2);
3262 }
3263 else if ((t2 = x_add(bh, bl)) == NULL) {
3264 Py_DECREF(t1);
3265 goto fail;
3266 }
3267 Py_DECREF(bh);
3268 Py_DECREF(bl);
3269 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 t3 = k_mul(t1, t2);
3272 Py_DECREF(t1);
3273 Py_DECREF(t2);
3274 if (t3 == NULL) goto fail;
3275 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 /* Add t3. It's not obvious why we can't run out of room here.
3278 * See the (*) comment after this function.
3279 */
3280 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3281 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003284
Mark Dickinson22b20182010-05-10 21:27:53 +00003285 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 Py_XDECREF(ret);
3287 Py_XDECREF(ah);
3288 Py_XDECREF(al);
3289 Py_XDECREF(bh);
3290 Py_XDECREF(bl);
3291 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003292}
3293
Tim Petersd6974a52002-08-13 20:37:51 +00003294/* (*) Why adding t3 can't "run out of room" above.
3295
Tim Petersab86c2b2002-08-15 20:06:00 +00003296Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3297to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003298
Tim Petersab86c2b2002-08-15 20:06:00 +000032991. For any integer i, i = c(i/2) + f(i/2). In particular,
3300 bsize = c(bsize/2) + f(bsize/2).
33012. shift = f(bsize/2)
33023. asize <= bsize
33034. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3304 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003305
Tim Petersab86c2b2002-08-15 20:06:00 +00003306We allocated asize + bsize result digits, and add t3 into them at an offset
3307of shift. This leaves asize+bsize-shift allocated digit positions for t3
3308to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3309asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003310
Tim Petersab86c2b2002-08-15 20:06:00 +00003311bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3312at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003313
Tim Petersab86c2b2002-08-15 20:06:00 +00003314If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3315digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3316most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003317
Tim Petersab86c2b2002-08-15 20:06:00 +00003318The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003319
Tim Petersab86c2b2002-08-15 20:06:00 +00003320 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003321
Tim Petersab86c2b2002-08-15 20:06:00 +00003322and we have asize + c(bsize/2) available digit positions. We need to show
3323this is always enough. An instance of c(bsize/2) cancels out in both, so
3324the question reduces to whether asize digits is enough to hold
3325(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3326then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3327asize 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 +00003328digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003329asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003330c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3331is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3332bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003333
Tim Peters48d52c02002-08-14 17:07:32 +00003334Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3335clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3336ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003337*/
3338
Tim Peters60004642002-08-12 22:01:34 +00003339/* b has at least twice the digits of a, and a is big enough that Karatsuba
3340 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3341 * of slices, each with a->ob_size digits, and multiply the slices by a,
3342 * one at a time. This gives k_mul balanced inputs to work with, and is
3343 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003344 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003345 * single-width slice overlap between successive partial sums).
3346 */
3347static PyLongObject *
3348k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3349{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003350 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3351 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 Py_ssize_t nbdone; /* # of b digits already multiplied */
3353 PyLongObject *ret;
3354 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 assert(asize > KARATSUBA_CUTOFF);
3357 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 /* Allocate result space, and zero it out. */
3360 ret = _PyLong_New(asize + bsize);
3361 if (ret == NULL)
3362 return NULL;
3363 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 /* Successive slices of b are copied into bslice. */
3366 bslice = _PyLong_New(asize);
3367 if (bslice == NULL)
3368 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 nbdone = 0;
3371 while (bsize > 0) {
3372 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003373 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003375 /* Multiply the next slice of b by a. */
3376 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3377 nbtouse * sizeof(digit));
3378 Py_SIZE(bslice) = nbtouse;
3379 product = k_mul(a, bslice);
3380 if (product == NULL)
3381 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 /* Add into result. */
3384 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3385 product->ob_digit, Py_SIZE(product));
3386 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 bsize -= nbtouse;
3389 nbdone += nbtouse;
3390 }
Tim Peters60004642002-08-12 22:01:34 +00003391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 Py_DECREF(bslice);
3393 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003394
Mark Dickinson22b20182010-05-10 21:27:53 +00003395 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 Py_DECREF(ret);
3397 Py_XDECREF(bslice);
3398 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003399}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
3401static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003402long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003406 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003409 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003411#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003413#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 /* if we don't have long long then we're almost certainly
3415 using 15-bit digits, so v will fit in a long. In the
3416 unlikely event that we're using 30-bit digits on a platform
3417 without long long, a large v will just cause us to fall
3418 through to the general multiplication code below. */
3419 if (v >= LONG_MIN && v <= LONG_MAX)
3420 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003421#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 z = k_mul(a, b);
3425 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003426 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3427 _PyLong_Negate(&z);
3428 if (z == NULL)
3429 return NULL;
3430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003432}
3433
Guido van Rossume32e0141992-01-19 16:31:05 +00003434/* The / and % operators are now defined in terms of divmod().
3435 The expression a mod b has the value a - b*floor(a/b).
3436 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003437 |a| by |b|, with the sign of a. This is also expressed
3438 as a - b*trunc(a/b), if trunc truncates towards zero.
3439 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 a b a rem b a mod b
3441 13 10 3 3
3442 -13 10 -3 7
3443 13 -10 3 -7
3444 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003445 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003446 have different signs. We then subtract one from the 'div'
3447 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003448
Tim Peters47e52ee2004-08-30 02:44:38 +00003449/* Compute
3450 * *pdiv, *pmod = divmod(v, w)
3451 * NULL can be passed for pdiv or pmod, in which case that part of
3452 * the result is simply thrown away. The caller owns a reference to
3453 * each of these it requests (does not pass NULL for).
3454 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003455static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003456l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 if (long_divrem(v, w, &div, &mod) < 0)
3462 return -1;
3463 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3464 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3465 PyLongObject *temp;
3466 PyLongObject *one;
3467 temp = (PyLongObject *) long_add(mod, w);
3468 Py_DECREF(mod);
3469 mod = temp;
3470 if (mod == NULL) {
3471 Py_DECREF(div);
3472 return -1;
3473 }
3474 one = (PyLongObject *) PyLong_FromLong(1L);
3475 if (one == NULL ||
3476 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3477 Py_DECREF(mod);
3478 Py_DECREF(div);
3479 Py_XDECREF(one);
3480 return -1;
3481 }
3482 Py_DECREF(one);
3483 Py_DECREF(div);
3484 div = temp;
3485 }
3486 if (pdiv != NULL)
3487 *pdiv = div;
3488 else
3489 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 if (pmod != NULL)
3492 *pmod = mod;
3493 else
3494 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003496 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003497}
3498
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003499static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003500long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003502 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 CHECK_BINOP(a, b);
3505 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3506 div = NULL;
3507 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003508}
3509
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003510/* PyLong/PyLong -> float, with correctly rounded result. */
3511
3512#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3513#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3514
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003515static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003516long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003518 PyLongObject *a, *b, *x;
3519 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3520 digit mask, low;
3521 int inexact, negate, a_is_small, b_is_small;
3522 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 CHECK_BINOP(v, w);
3525 a = (PyLongObject *)v;
3526 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 /*
3529 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3532 1. choose a suitable integer 'shift'
3533 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3534 3. adjust x for correct rounding
3535 4. convert x to a double dx with the same value
3536 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003538 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003540 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3541 returns either 0.0 or -0.0, depending on the sign of b. For a and
3542 b both nonzero, ignore signs of a and b, and add the sign back in
3543 at the end. Now write a_bits and b_bits for the bit lengths of a
3544 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3545 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3550 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3551 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3552 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003554 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 1. The integer 'shift' is chosen so that x has the right number of
3557 bits for a double, plus two or three extra bits that will be used
3558 in the rounding decisions. Writing a_bits and b_bits for the
3559 number of significant bits in a and b respectively, a
3560 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 This is fine in the usual case, but if a/b is smaller than the
3565 smallest normal float then it can lead to double rounding on an
3566 IEEE 754 platform, giving incorrectly rounded results. So we
3567 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 2. The quantity x is computed by first shifting a (left -shift bits
3572 if shift <= 0, right shift bits if shift > 0) and then dividing by
3573 b. For both the shift and the division, we keep track of whether
3574 the result is inexact, in a flag 'inexact'; this information is
3575 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 With the choice of shift above, together with our assumption that
3578 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3579 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3582 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 For float representability, we need x/2**extra_bits <
3587 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3588 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 To round, we just modify the bottom digit of x in-place; this can
3593 end up giving a digit with value > PyLONG_MASK, but that's not a
3594 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 With the original choices for shift above, extra_bits will always
3597 be 2 or 3. Then rounding under the round-half-to-even rule, we
3598 round up iff the most significant of the extra bits is 1, and
3599 either: (a) the computation of x in step 2 had an inexact result,
3600 or (b) at least one other of the extra bits is 1, or (c) the least
3601 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 4. Conversion to a double is straightforward; all floating-point
3604 operations involved in the conversion are exact, so there's no
3605 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3608 The result will always be exactly representable as a double, except
3609 in the case that it overflows. To avoid dependence on the exact
3610 behaviour of ldexp on overflow, we check for overflow before
3611 applying ldexp. The result of ldexp is adjusted for sign before
3612 returning.
3613 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003616 a_size = Py_ABS(Py_SIZE(a));
3617 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3619 if (b_size == 0) {
3620 PyErr_SetString(PyExc_ZeroDivisionError,
3621 "division by zero");
3622 goto error;
3623 }
3624 if (a_size == 0)
3625 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 /* Fast path for a and b small (exactly representable in a double).
3628 Relies on floating-point division being correctly rounded; results
3629 may be subject to double rounding on x86 machines that operate with
3630 the x87 FPU set to 64-bit precision. */
3631 a_is_small = a_size <= MANT_DIG_DIGITS ||
3632 (a_size == MANT_DIG_DIGITS+1 &&
3633 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3634 b_is_small = b_size <= MANT_DIG_DIGITS ||
3635 (b_size == MANT_DIG_DIGITS+1 &&
3636 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3637 if (a_is_small && b_is_small) {
3638 double da, db;
3639 da = a->ob_digit[--a_size];
3640 while (a_size > 0)
3641 da = da * PyLong_BASE + a->ob_digit[--a_size];
3642 db = b->ob_digit[--b_size];
3643 while (b_size > 0)
3644 db = db * PyLong_BASE + b->ob_digit[--b_size];
3645 result = da / db;
3646 goto success;
3647 }
Tim Peterse2a60002001-09-04 06:17:36 +00003648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 /* Catch obvious cases of underflow and overflow */
3650 diff = a_size - b_size;
3651 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3652 /* Extreme overflow */
3653 goto overflow;
3654 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3655 /* Extreme underflow */
3656 goto underflow_or_zero;
3657 /* Next line is now safe from overflowing a Py_ssize_t */
3658 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3659 bits_in_digit(b->ob_digit[b_size - 1]);
3660 /* Now diff = a_bits - b_bits. */
3661 if (diff > DBL_MAX_EXP)
3662 goto overflow;
3663 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3664 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003667 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003669 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003671 /* x = abs(a * 2**-shift) */
3672 if (shift <= 0) {
3673 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3674 digit rem;
3675 /* x = a << -shift */
3676 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3677 /* In practice, it's probably impossible to end up
3678 here. Both a and b would have to be enormous,
3679 using close to SIZE_T_MAX bytes of memory each. */
3680 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003681 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003682 goto error;
3683 }
3684 x = _PyLong_New(a_size + shift_digits + 1);
3685 if (x == NULL)
3686 goto error;
3687 for (i = 0; i < shift_digits; i++)
3688 x->ob_digit[i] = 0;
3689 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3690 a_size, -shift % PyLong_SHIFT);
3691 x->ob_digit[a_size + shift_digits] = rem;
3692 }
3693 else {
3694 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3695 digit rem;
3696 /* x = a >> shift */
3697 assert(a_size >= shift_digits);
3698 x = _PyLong_New(a_size - shift_digits);
3699 if (x == NULL)
3700 goto error;
3701 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3702 a_size - shift_digits, shift % PyLong_SHIFT);
3703 /* set inexact if any of the bits shifted out is nonzero */
3704 if (rem)
3705 inexact = 1;
3706 while (!inexact && shift_digits > 0)
3707 if (a->ob_digit[--shift_digits])
3708 inexact = 1;
3709 }
3710 long_normalize(x);
3711 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003713 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3714 reference to x, so it's safe to modify it in-place. */
3715 if (b_size == 1) {
3716 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3717 b->ob_digit[0]);
3718 long_normalize(x);
3719 if (rem)
3720 inexact = 1;
3721 }
3722 else {
3723 PyLongObject *div, *rem;
3724 div = x_divrem(x, b, &rem);
3725 Py_DECREF(x);
3726 x = div;
3727 if (x == NULL)
3728 goto error;
3729 if (Py_SIZE(rem))
3730 inexact = 1;
3731 Py_DECREF(rem);
3732 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003733 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003734 assert(x_size > 0); /* result of division is never zero */
3735 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003737 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003738 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003739 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003741 /* Round by directly modifying the low digit of x. */
3742 mask = (digit)1 << (extra_bits - 1);
3743 low = x->ob_digit[0] | inexact;
3744 if (low & mask && low & (3*mask-1))
3745 low += mask;
3746 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003748 /* Convert x to a double dx; the conversion is exact. */
3749 dx = x->ob_digit[--x_size];
3750 while (x_size > 0)
3751 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3752 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003754 /* Check whether ldexp result will overflow a double. */
3755 if (shift + x_bits >= DBL_MAX_EXP &&
3756 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3757 goto overflow;
3758 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003759
3760 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003762
3763 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003765
3766 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003767 PyErr_SetString(PyExc_OverflowError,
3768 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003769 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003771}
3772
3773static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003774long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 CHECK_BINOP(a, b);
3779
3780 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3781 mod = NULL;
3782 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003783}
3784
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003785static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003786long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003788 PyLongObject *div, *mod;
3789 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003791 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003793 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3794 return NULL;
3795 }
3796 z = PyTuple_New(2);
3797 if (z != NULL) {
3798 PyTuple_SetItem(z, 0, (PyObject *) div);
3799 PyTuple_SetItem(z, 1, (PyObject *) mod);
3800 }
3801 else {
3802 Py_DECREF(div);
3803 Py_DECREF(mod);
3804 }
3805 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003806}
3807
Tim Peters47e52ee2004-08-30 02:44:38 +00003808/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003809static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003810long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003812 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3813 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003815 PyLongObject *z = NULL; /* accumulated result */
3816 Py_ssize_t i, j, k; /* counters */
3817 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 /* 5-ary values. If the exponent is large enough, table is
3820 * precomputed so that table[i] == a**i % c for i in range(32).
3821 */
3822 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3823 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 /* a, b, c = v, w, x */
3826 CHECK_BINOP(v, w);
3827 a = (PyLongObject*)v; Py_INCREF(a);
3828 b = (PyLongObject*)w; Py_INCREF(b);
3829 if (PyLong_Check(x)) {
3830 c = (PyLongObject *)x;
3831 Py_INCREF(x);
3832 }
3833 else if (x == Py_None)
3834 c = NULL;
3835 else {
3836 Py_DECREF(a);
3837 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003838 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003839 }
Tim Peters4c483c42001-09-05 06:24:58 +00003840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003841 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3842 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04003843 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003844 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003845 goto Error;
3846 }
3847 else {
3848 /* else return a float. This works because we know
3849 that this calls float_pow() which converts its
3850 arguments to double. */
3851 Py_DECREF(a);
3852 Py_DECREF(b);
3853 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3854 }
3855 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003857 if (c) {
3858 /* if modulus == 0:
3859 raise ValueError() */
3860 if (Py_SIZE(c) == 0) {
3861 PyErr_SetString(PyExc_ValueError,
3862 "pow() 3rd argument cannot be 0");
3863 goto Error;
3864 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003866 /* if modulus < 0:
3867 negativeOutput = True
3868 modulus = -modulus */
3869 if (Py_SIZE(c) < 0) {
3870 negativeOutput = 1;
3871 temp = (PyLongObject *)_PyLong_Copy(c);
3872 if (temp == NULL)
3873 goto Error;
3874 Py_DECREF(c);
3875 c = temp;
3876 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02003877 _PyLong_Negate(&c);
3878 if (c == NULL)
3879 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003880 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* if modulus == 1:
3883 return 0 */
3884 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3885 z = (PyLongObject *)PyLong_FromLong(0L);
3886 goto Done;
3887 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003888
Tim Peters81a93152013-10-05 16:53:52 -05003889 /* Reduce base by modulus in some cases:
3890 1. If base < 0. Forcing the base non-negative makes things easier.
3891 2. If base is obviously larger than the modulus. The "small
3892 exponent" case later can multiply directly by base repeatedly,
3893 while the "large exponent" case multiplies directly by base 31
3894 times. It can be unboundedly faster to multiply by
3895 base % modulus instead.
3896 We could _always_ do this reduction, but l_divmod() isn't cheap,
3897 so we only do it when it buys something. */
3898 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 if (l_divmod(a, c, NULL, &temp) < 0)
3900 goto Error;
3901 Py_DECREF(a);
3902 a = temp;
3903 temp = NULL;
3904 }
3905 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003907 /* At this point a, b, and c are guaranteed non-negative UNLESS
3908 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003910 z = (PyLongObject *)PyLong_FromLong(1L);
3911 if (z == NULL)
3912 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 /* Perform a modular reduction, X = X % c, but leave X alone if c
3915 * is NULL.
3916 */
3917#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003918 do { \
3919 if (c != NULL) { \
3920 if (l_divmod(X, c, NULL, &temp) < 0) \
3921 goto Error; \
3922 Py_XDECREF(X); \
3923 X = temp; \
3924 temp = NULL; \
3925 } \
3926 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 /* Multiply two values, then reduce the result:
3929 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003930#define MULT(X, Y, result) \
3931 do { \
3932 temp = (PyLongObject *)long_mul(X, Y); \
3933 if (temp == NULL) \
3934 goto Error; \
3935 Py_XDECREF(result); \
3936 result = temp; \
3937 temp = NULL; \
3938 REDUCE(result); \
3939 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003941 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3942 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3943 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3944 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3945 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003947 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003948 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003950 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 }
3952 }
3953 }
3954 else {
3955 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3956 Py_INCREF(z); /* still holds 1L */
3957 table[0] = z;
3958 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003959 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003961 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3962 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3965 const int index = (bi >> j) & 0x1f;
3966 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003967 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003969 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 }
3971 }
3972 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 if (negativeOutput && (Py_SIZE(z) != 0)) {
3975 temp = (PyLongObject *)long_sub(z, c);
3976 if (temp == NULL)
3977 goto Error;
3978 Py_DECREF(z);
3979 z = temp;
3980 temp = NULL;
3981 }
3982 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003983
Mark Dickinson22b20182010-05-10 21:27:53 +00003984 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02003985 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003986 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003987 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003988 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3989 for (i = 0; i < 32; ++i)
3990 Py_XDECREF(table[i]);
3991 }
3992 Py_DECREF(a);
3993 Py_DECREF(b);
3994 Py_XDECREF(c);
3995 Py_XDECREF(temp);
3996 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003997}
3998
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003999static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004000long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004002 /* Implement ~x as -(x+1) */
4003 PyLongObject *x;
4004 PyLongObject *w;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004005 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004006 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4007 w = (PyLongObject *)PyLong_FromLong(1L);
4008 if (w == NULL)
4009 return NULL;
4010 x = (PyLongObject *) long_add(v, w);
4011 Py_DECREF(w);
4012 if (x == NULL)
4013 return NULL;
4014 Py_SIZE(x) = -(Py_SIZE(x));
4015 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004016}
4017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004018static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004019long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004021 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004022 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004023 return PyLong_FromLong(-MEDIUM_VALUE(v));
4024 z = (PyLongObject *)_PyLong_Copy(v);
4025 if (z != NULL)
4026 Py_SIZE(z) = -(Py_SIZE(v));
4027 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004028}
4029
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004030static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004031long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004033 if (Py_SIZE(v) < 0)
4034 return long_neg(v);
4035 else
4036 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004037}
4038
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004039static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004040long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004042 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004043}
4044
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004045static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004046long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004048 PyLongObject *z = NULL;
4049 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4050 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004054 if (Py_SIZE(a) < 0) {
4055 /* Right shifting negative numbers is harder */
4056 PyLongObject *a1, *a2;
4057 a1 = (PyLongObject *) long_invert(a);
4058 if (a1 == NULL)
4059 goto rshift_error;
4060 a2 = (PyLongObject *) long_rshift(a1, b);
4061 Py_DECREF(a1);
4062 if (a2 == NULL)
4063 goto rshift_error;
4064 z = (PyLongObject *) long_invert(a2);
4065 Py_DECREF(a2);
4066 }
4067 else {
4068 shiftby = PyLong_AsSsize_t((PyObject *)b);
4069 if (shiftby == -1L && PyErr_Occurred())
4070 goto rshift_error;
4071 if (shiftby < 0) {
4072 PyErr_SetString(PyExc_ValueError,
4073 "negative shift count");
4074 goto rshift_error;
4075 }
4076 wordshift = shiftby / PyLong_SHIFT;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004077 newsize = Py_ABS(Py_SIZE(a)) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 if (newsize <= 0)
4079 return PyLong_FromLong(0);
4080 loshift = shiftby % PyLong_SHIFT;
4081 hishift = PyLong_SHIFT - loshift;
4082 lomask = ((digit)1 << hishift) - 1;
4083 himask = PyLong_MASK ^ lomask;
4084 z = _PyLong_New(newsize);
4085 if (z == NULL)
4086 goto rshift_error;
4087 if (Py_SIZE(a) < 0)
4088 Py_SIZE(z) = -(Py_SIZE(z));
4089 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4090 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4091 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004092 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004093 }
4094 z = long_normalize(z);
4095 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004096 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004097 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004098
Guido van Rossumc6913e71991-11-19 20:26:46 +00004099}
4100
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004101static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004102long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004104 /* This version due to Tim Peters */
4105 PyLongObject *a = (PyLongObject*)v;
4106 PyLongObject *b = (PyLongObject*)w;
4107 PyLongObject *z = NULL;
4108 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4109 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004111 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004113 shiftby = PyLong_AsSsize_t((PyObject *)b);
4114 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004115 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004116 if (shiftby < 0) {
4117 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004118 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 }
4120 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4121 wordshift = shiftby / PyLong_SHIFT;
4122 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004123
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004124 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004125 newsize = oldsize + wordshift;
4126 if (remshift)
4127 ++newsize;
4128 z = _PyLong_New(newsize);
4129 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004130 return NULL;
4131 if (Py_SIZE(a) < 0) {
4132 assert(Py_REFCNT(z) == 1);
4133 Py_SIZE(z) = -Py_SIZE(z);
4134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 for (i = 0; i < wordshift; i++)
4136 z->ob_digit[i] = 0;
4137 accum = 0;
4138 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4139 accum |= (twodigits)a->ob_digit[j] << remshift;
4140 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4141 accum >>= PyLong_SHIFT;
4142 }
4143 if (remshift)
4144 z->ob_digit[newsize-1] = (digit)accum;
4145 else
4146 assert(!accum);
4147 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004148 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004149}
4150
Mark Dickinson27a87a22009-10-25 20:43:34 +00004151/* Compute two's complement of digit vector a[0:m], writing result to
4152 z[0:m]. The digit vector a need not be normalized, but should not
4153 be entirely zero. a and z may point to the same digit vector. */
4154
4155static void
4156v_complement(digit *z, digit *a, Py_ssize_t m)
4157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004158 Py_ssize_t i;
4159 digit carry = 1;
4160 for (i = 0; i < m; ++i) {
4161 carry += a[i] ^ PyLong_MASK;
4162 z[i] = carry & PyLong_MASK;
4163 carry >>= PyLong_SHIFT;
4164 }
4165 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004166}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004167
4168/* Bitwise and/xor/or operations */
4169
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004170static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004171long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004172 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004173 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004175 int nega, negb, negz;
4176 Py_ssize_t size_a, size_b, size_z, i;
4177 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004179 /* Bitwise operations for negative numbers operate as though
4180 on a two's complement representation. So convert arguments
4181 from sign-magnitude to two's complement, and convert the
4182 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004185 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 nega = Py_SIZE(a) < 0;
4187 if (nega) {
4188 z = _PyLong_New(size_a);
4189 if (z == NULL)
4190 return NULL;
4191 v_complement(z->ob_digit, a->ob_digit, size_a);
4192 a = z;
4193 }
4194 else
4195 /* Keep reference count consistent. */
4196 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004199 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004200 negb = Py_SIZE(b) < 0;
4201 if (negb) {
4202 z = _PyLong_New(size_b);
4203 if (z == NULL) {
4204 Py_DECREF(a);
4205 return NULL;
4206 }
4207 v_complement(z->ob_digit, b->ob_digit, size_b);
4208 b = z;
4209 }
4210 else
4211 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004213 /* Swap a and b if necessary to ensure size_a >= size_b. */
4214 if (size_a < size_b) {
4215 z = a; a = b; b = z;
4216 size_z = size_a; size_a = size_b; size_b = size_z;
4217 negz = nega; nega = negb; negb = negz;
4218 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004220 /* JRH: The original logic here was to allocate the result value (z)
4221 as the longer of the two operands. However, there are some cases
4222 where the result is guaranteed to be shorter than that: AND of two
4223 positives, OR of two negatives: use the shorter number. AND with
4224 mixed signs: use the positive number. OR with mixed signs: use the
4225 negative number.
4226 */
4227 switch (op) {
4228 case '^':
4229 negz = nega ^ negb;
4230 size_z = size_a;
4231 break;
4232 case '&':
4233 negz = nega & negb;
4234 size_z = negb ? size_a : size_b;
4235 break;
4236 case '|':
4237 negz = nega | negb;
4238 size_z = negb ? size_b : size_a;
4239 break;
4240 default:
4241 PyErr_BadArgument();
4242 return NULL;
4243 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004245 /* We allow an extra digit if z is negative, to make sure that
4246 the final two's complement of z doesn't overflow. */
4247 z = _PyLong_New(size_z + negz);
4248 if (z == NULL) {
4249 Py_DECREF(a);
4250 Py_DECREF(b);
4251 return NULL;
4252 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004254 /* Compute digits for overlap of a and b. */
4255 switch(op) {
4256 case '&':
4257 for (i = 0; i < size_b; ++i)
4258 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4259 break;
4260 case '|':
4261 for (i = 0; i < size_b; ++i)
4262 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4263 break;
4264 case '^':
4265 for (i = 0; i < size_b; ++i)
4266 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4267 break;
4268 default:
4269 PyErr_BadArgument();
4270 return NULL;
4271 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004273 /* Copy any remaining digits of a, inverting if necessary. */
4274 if (op == '^' && negb)
4275 for (; i < size_z; ++i)
4276 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4277 else if (i < size_z)
4278 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4279 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 /* Complement result if negative. */
4282 if (negz) {
4283 Py_SIZE(z) = -(Py_SIZE(z));
4284 z->ob_digit[size_z] = PyLong_MASK;
4285 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4286 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004288 Py_DECREF(a);
4289 Py_DECREF(b);
4290 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004291}
4292
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004293static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004294long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004296 PyObject *c;
4297 CHECK_BINOP(a, b);
4298 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4299 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004300}
4301
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004302static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004303long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004305 PyObject *c;
4306 CHECK_BINOP(a, b);
4307 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4308 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004309}
4310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004311static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004312long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004314 PyObject *c;
4315 CHECK_BINOP(a, b);
4316 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4317 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004318}
4319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004320static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004321long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004323 if (PyLong_CheckExact(v))
4324 Py_INCREF(v);
4325 else
4326 v = _PyLong_Copy((PyLongObject *)v);
4327 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004328}
4329
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004330static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004331long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 double result;
4334 result = PyLong_AsDouble(v);
4335 if (result == -1.0 && PyErr_Occurred())
4336 return NULL;
4337 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004338}
4339
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004340static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004341long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004342
Tim Peters6d6c1a32001-08-02 04:15:00 +00004343static PyObject *
4344long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4345{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004346 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004347 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004350 if (type != &PyLong_Type)
4351 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004352 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4353 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004354 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004355 if (x == NULL) {
4356 if (obase != NULL) {
4357 PyErr_SetString(PyExc_TypeError,
4358 "int() missing string argument");
4359 return NULL;
4360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004362 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004363 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004365
Gregory P. Smitha689e522012-12-25 22:38:32 -08004366 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004367 if (base == -1 && PyErr_Occurred())
4368 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004369 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004370 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004371 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004372 return NULL;
4373 }
4374
4375 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004376 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (PyByteArray_Check(x))
4380 string = PyByteArray_AS_STRING(x);
4381 else
4382 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004383 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004384 }
4385 else {
4386 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004387 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 return NULL;
4389 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004390}
4391
Serhiy Storchaka95949422013-08-27 19:40:23 +03004392/* Wimpy, slow approach to tp_new calls for subtypes of int:
4393 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004394 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004395 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004396*/
4397static PyObject *
4398long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004400 PyLongObject *tmp, *newobj;
4401 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 assert(PyType_IsSubtype(type, &PyLong_Type));
4404 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4405 if (tmp == NULL)
4406 return NULL;
4407 assert(PyLong_CheckExact(tmp));
4408 n = Py_SIZE(tmp);
4409 if (n < 0)
4410 n = -n;
4411 newobj = (PyLongObject *)type->tp_alloc(type, n);
4412 if (newobj == NULL) {
4413 Py_DECREF(tmp);
4414 return NULL;
4415 }
4416 assert(PyLong_Check(newobj));
4417 Py_SIZE(newobj) = Py_SIZE(tmp);
4418 for (i = 0; i < n; i++)
4419 newobj->ob_digit[i] = tmp->ob_digit[i];
4420 Py_DECREF(tmp);
4421 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004422}
4423
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004424static PyObject *
4425long_getnewargs(PyLongObject *v)
4426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004427 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004428}
4429
Guido van Rossumb43daf72007-08-01 18:08:08 +00004430static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004431long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004433}
4434
4435static PyObject *
4436long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004438}
4439
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004440static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004441long__format__(PyObject *self, PyObject *args)
4442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004443 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004444 _PyUnicodeWriter writer;
4445 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4448 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004449
Victor Stinner8f674cc2013-04-17 23:02:17 +02004450 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004451 ret = _PyLong_FormatAdvancedWriter(
4452 &writer,
4453 self,
4454 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4455 if (ret == -1) {
4456 _PyUnicodeWriter_Dealloc(&writer);
4457 return NULL;
4458 }
4459 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004460}
4461
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004462/* Return a pair (q, r) such that a = b * q + r, and
4463 abs(r) <= abs(b)/2, with equality possible only if q is even.
4464 In other words, q == a / b, rounded to the nearest integer using
4465 round-half-to-even. */
4466
4467PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004468_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004469{
4470 PyLongObject *quo = NULL, *rem = NULL;
4471 PyObject *one = NULL, *twice_rem, *result, *temp;
4472 int cmp, quo_is_odd, quo_is_neg;
4473
4474 /* Equivalent Python code:
4475
4476 def divmod_near(a, b):
4477 q, r = divmod(a, b)
4478 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4479 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4480 # positive, 2 * r < b if b negative.
4481 greater_than_half = 2*r > b if b > 0 else 2*r < b
4482 exactly_half = 2*r == b
4483 if greater_than_half or exactly_half and q % 2 == 1:
4484 q += 1
4485 r -= b
4486 return q, r
4487
4488 */
4489 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4490 PyErr_SetString(PyExc_TypeError,
4491 "non-integer arguments in division");
4492 return NULL;
4493 }
4494
4495 /* Do a and b have different signs? If so, quotient is negative. */
4496 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4497
4498 one = PyLong_FromLong(1L);
4499 if (one == NULL)
4500 return NULL;
4501
4502 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4503 goto error;
4504
4505 /* compare twice the remainder with the divisor, to see
4506 if we need to adjust the quotient and remainder */
4507 twice_rem = long_lshift((PyObject *)rem, one);
4508 if (twice_rem == NULL)
4509 goto error;
4510 if (quo_is_neg) {
4511 temp = long_neg((PyLongObject*)twice_rem);
4512 Py_DECREF(twice_rem);
4513 twice_rem = temp;
4514 if (twice_rem == NULL)
4515 goto error;
4516 }
4517 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4518 Py_DECREF(twice_rem);
4519
4520 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4521 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4522 /* fix up quotient */
4523 if (quo_is_neg)
4524 temp = long_sub(quo, (PyLongObject *)one);
4525 else
4526 temp = long_add(quo, (PyLongObject *)one);
4527 Py_DECREF(quo);
4528 quo = (PyLongObject *)temp;
4529 if (quo == NULL)
4530 goto error;
4531 /* and remainder */
4532 if (quo_is_neg)
4533 temp = long_add(rem, (PyLongObject *)b);
4534 else
4535 temp = long_sub(rem, (PyLongObject *)b);
4536 Py_DECREF(rem);
4537 rem = (PyLongObject *)temp;
4538 if (rem == NULL)
4539 goto error;
4540 }
4541
4542 result = PyTuple_New(2);
4543 if (result == NULL)
4544 goto error;
4545
4546 /* PyTuple_SET_ITEM steals references */
4547 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4548 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4549 Py_DECREF(one);
4550 return result;
4551
4552 error:
4553 Py_XDECREF(quo);
4554 Py_XDECREF(rem);
4555 Py_XDECREF(one);
4556 return NULL;
4557}
4558
Eric Smith8c663262007-08-25 02:26:07 +00004559static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004560long_round(PyObject *self, PyObject *args)
4561{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004562 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004563
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004564 /* To round an integer m to the nearest 10**n (n positive), we make use of
4565 * the divmod_near operation, defined by:
4566 *
4567 * divmod_near(a, b) = (q, r)
4568 *
4569 * where q is the nearest integer to the quotient a / b (the
4570 * nearest even integer in the case of a tie) and r == a - q * b.
4571 * Hence q * b = a - r is the nearest multiple of b to a,
4572 * preferring even multiples in the case of a tie.
4573 *
4574 * So the nearest multiple of 10**n to m is:
4575 *
4576 * m - divmod_near(m, 10**n)[1].
4577 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4579 return NULL;
4580 if (o_ndigits == NULL)
4581 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004582
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004583 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (ndigits == NULL)
4585 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004586
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004587 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 if (Py_SIZE(ndigits) >= 0) {
4589 Py_DECREF(ndigits);
4590 return long_long(self);
4591 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004592
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004593 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4594 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004595 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004596 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004597 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004598 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004599
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004600 result = PyLong_FromLong(10L);
4601 if (result == NULL) {
4602 Py_DECREF(ndigits);
4603 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004604 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004605
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004606 temp = long_pow(result, ndigits, Py_None);
4607 Py_DECREF(ndigits);
4608 Py_DECREF(result);
4609 result = temp;
4610 if (result == NULL)
4611 return NULL;
4612
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004613 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004614 Py_DECREF(result);
4615 result = temp;
4616 if (result == NULL)
4617 return NULL;
4618
4619 temp = long_sub((PyLongObject *)self,
4620 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4621 Py_DECREF(result);
4622 result = temp;
4623
4624 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004625}
4626
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004627static PyObject *
4628long_sizeof(PyLongObject *v)
4629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004631
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004632 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(v))*sizeof(digit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004633 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004634}
4635
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004636static PyObject *
4637long_bit_length(PyLongObject *v)
4638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 PyLongObject *result, *x, *y;
4640 Py_ssize_t ndigits, msd_bits = 0;
4641 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 assert(v != NULL);
4644 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004645
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004646 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 if (ndigits == 0)
4648 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 msd = v->ob_digit[ndigits-1];
4651 while (msd >= 32) {
4652 msd_bits += 6;
4653 msd >>= 6;
4654 }
4655 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4658 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 /* expression above may overflow; use Python integers instead */
4661 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4662 if (result == NULL)
4663 return NULL;
4664 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4665 if (x == NULL)
4666 goto error;
4667 y = (PyLongObject *)long_mul(result, x);
4668 Py_DECREF(x);
4669 if (y == NULL)
4670 goto error;
4671 Py_DECREF(result);
4672 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4675 if (x == NULL)
4676 goto error;
4677 y = (PyLongObject *)long_add(result, x);
4678 Py_DECREF(x);
4679 if (y == NULL)
4680 goto error;
4681 Py_DECREF(result);
4682 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004685
Mark Dickinson22b20182010-05-10 21:27:53 +00004686 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 Py_DECREF(result);
4688 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004689}
4690
4691PyDoc_STRVAR(long_bit_length_doc,
4692"int.bit_length() -> int\n\
4693\n\
4694Number of bits necessary to represent self in binary.\n\
4695>>> bin(37)\n\
4696'0b100101'\n\
4697>>> (37).bit_length()\n\
46986");
4699
Christian Heimes53876d92008-04-19 00:31:39 +00004700#if 0
4701static PyObject *
4702long_is_finite(PyObject *v)
4703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004704 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004705}
4706#endif
4707
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004708
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004709static PyObject *
4710long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 PyObject *byteorder_str;
4713 PyObject *is_signed_obj = NULL;
4714 Py_ssize_t length;
4715 int little_endian;
4716 int is_signed;
4717 PyObject *bytes;
4718 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4721 &length, &byteorder_str,
4722 &is_signed_obj))
4723 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 if (args != NULL && Py_SIZE(args) > 2) {
4726 PyErr_SetString(PyExc_TypeError,
4727 "'signed' is a keyword-only argument");
4728 return NULL;
4729 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4732 little_endian = 1;
4733 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4734 little_endian = 0;
4735 else {
4736 PyErr_SetString(PyExc_ValueError,
4737 "byteorder must be either 'little' or 'big'");
4738 return NULL;
4739 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 if (is_signed_obj != NULL) {
4742 int cmp = PyObject_IsTrue(is_signed_obj);
4743 if (cmp < 0)
4744 return NULL;
4745 is_signed = cmp ? 1 : 0;
4746 }
4747 else {
4748 /* If the signed argument was omitted, use False as the
4749 default. */
4750 is_signed = 0;
4751 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 if (length < 0) {
4754 PyErr_SetString(PyExc_ValueError,
4755 "length argument must be non-negative");
4756 return NULL;
4757 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 bytes = PyBytes_FromStringAndSize(NULL, length);
4760 if (bytes == NULL)
4761 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004763 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4764 length, little_endian, is_signed) < 0) {
4765 Py_DECREF(bytes);
4766 return NULL;
4767 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004769 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004770}
4771
Mark Dickinson078c2532010-01-30 18:06:17 +00004772PyDoc_STRVAR(long_to_bytes_doc,
4773"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004774\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004775Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004776\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004778raised if the integer is not representable with the given number of\n\
4779bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004780\n\
4781The byteorder argument determines the byte order used to represent the\n\
4782integer. If byteorder is 'big', the most significant byte is at the\n\
4783beginning of the byte array. If byteorder is 'little', the most\n\
4784significant byte is at the end of the byte array. To request the native\n\
4785byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4786\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004787The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004788used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004789is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004790
4791static PyObject *
4792long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004794 PyObject *byteorder_str;
4795 PyObject *is_signed_obj = NULL;
4796 int little_endian;
4797 int is_signed;
4798 PyObject *obj;
4799 PyObject *bytes;
4800 PyObject *long_obj;
4801 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004803 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4804 &obj, &byteorder_str,
4805 &is_signed_obj))
4806 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004808 if (args != NULL && Py_SIZE(args) > 2) {
4809 PyErr_SetString(PyExc_TypeError,
4810 "'signed' is a keyword-only argument");
4811 return NULL;
4812 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004814 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4815 little_endian = 1;
4816 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4817 little_endian = 0;
4818 else {
4819 PyErr_SetString(PyExc_ValueError,
4820 "byteorder must be either 'little' or 'big'");
4821 return NULL;
4822 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004824 if (is_signed_obj != NULL) {
4825 int cmp = PyObject_IsTrue(is_signed_obj);
4826 if (cmp < 0)
4827 return NULL;
4828 is_signed = cmp ? 1 : 0;
4829 }
4830 else {
4831 /* If the signed argument was omitted, use False as the
4832 default. */
4833 is_signed = 0;
4834 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 bytes = PyObject_Bytes(obj);
4837 if (bytes == NULL)
4838 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004840 long_obj = _PyLong_FromByteArray(
4841 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4842 little_endian, is_signed);
4843 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004845 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004846 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004847 */
4848 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4849 PyLongObject *newobj;
4850 int i;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004851 Py_ssize_t n = Py_ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004853 newobj = (PyLongObject *)type->tp_alloc(type, n);
4854 if (newobj == NULL) {
4855 Py_DECREF(long_obj);
4856 return NULL;
4857 }
4858 assert(PyLong_Check(newobj));
4859 Py_SIZE(newobj) = Py_SIZE(long_obj);
4860 for (i = 0; i < n; i++) {
4861 newobj->ob_digit[i] =
4862 ((PyLongObject *)long_obj)->ob_digit[i];
4863 }
4864 Py_DECREF(long_obj);
4865 return (PyObject *)newobj;
4866 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004868 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004869}
4870
Mark Dickinson078c2532010-01-30 18:06:17 +00004871PyDoc_STRVAR(long_from_bytes_doc,
4872"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4873\n\
4874Return the integer represented by the given array of bytes.\n\
4875\n\
R David Murray861470c2014-10-05 11:47:01 -04004876The bytes argument must be a bytes-like object (e.g. bytes or bytearray).\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004877\n\
4878The byteorder argument determines the byte order used to represent the\n\
4879integer. If byteorder is 'big', the most significant byte is at the\n\
4880beginning of the byte array. If byteorder is 'little', the most\n\
4881significant byte is at the end of the byte array. To request the native\n\
4882byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4883\n\
4884The signed keyword-only argument indicates whether two's complement is\n\
4885used to represent the integer.");
4886
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004887static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4889 "Returns self, the complex conjugate of any int."},
4890 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4891 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004892#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004893 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4894 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004895#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004896 {"to_bytes", (PyCFunction)long_to_bytes,
4897 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4898 {"from_bytes", (PyCFunction)long_from_bytes,
4899 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4900 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4901 "Truncating an Integral returns itself."},
4902 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4903 "Flooring an Integral returns itself."},
4904 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4905 "Ceiling of an Integral returns itself."},
4906 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4907 "Rounding an Integral returns itself.\n"
4908 "Rounding with an ndigits argument also returns an integer."},
4909 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4910 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4911 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4912 "Returns size in memory, in bytes"},
4913 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004914};
4915
Guido van Rossumb43daf72007-08-01 18:08:08 +00004916static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004917 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004918 (getter)long_long, (setter)NULL,
4919 "the real part of a complex number",
4920 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004921 {"imag",
4922 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004923 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004924 NULL},
4925 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004926 (getter)long_long, (setter)NULL,
4927 "the numerator of a rational number in lowest terms",
4928 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004929 {"denominator",
4930 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004931 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004932 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004933 {NULL} /* Sentinel */
4934};
4935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004936PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004937"int(x=0) -> integer\n\
4938int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004939\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004940Convert a number or string to an integer, or return 0 if no arguments\n\
4941are given. If x is a number, return x.__int__(). For floating point\n\
4942numbers, this truncates towards zero.\n\
4943\n\
4944If x is not a number or if base is given, then x must be a string,\n\
4945bytes, or bytearray instance representing an integer literal in the\n\
4946given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4947by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4948Base 0 means to interpret the base from the string as an integer literal.\n\
4949>>> int('0b100', base=0)\n\
49504");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004951
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004952static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004953 (binaryfunc)long_add, /*nb_add*/
4954 (binaryfunc)long_sub, /*nb_subtract*/
4955 (binaryfunc)long_mul, /*nb_multiply*/
4956 long_mod, /*nb_remainder*/
4957 long_divmod, /*nb_divmod*/
4958 long_pow, /*nb_power*/
4959 (unaryfunc)long_neg, /*nb_negative*/
4960 (unaryfunc)long_long, /*tp_positive*/
4961 (unaryfunc)long_abs, /*tp_absolute*/
4962 (inquiry)long_bool, /*tp_bool*/
4963 (unaryfunc)long_invert, /*nb_invert*/
4964 long_lshift, /*nb_lshift*/
4965 (binaryfunc)long_rshift, /*nb_rshift*/
4966 long_and, /*nb_and*/
4967 long_xor, /*nb_xor*/
4968 long_or, /*nb_or*/
4969 long_long, /*nb_int*/
4970 0, /*nb_reserved*/
4971 long_float, /*nb_float*/
4972 0, /* nb_inplace_add */
4973 0, /* nb_inplace_subtract */
4974 0, /* nb_inplace_multiply */
4975 0, /* nb_inplace_remainder */
4976 0, /* nb_inplace_power */
4977 0, /* nb_inplace_lshift */
4978 0, /* nb_inplace_rshift */
4979 0, /* nb_inplace_and */
4980 0, /* nb_inplace_xor */
4981 0, /* nb_inplace_or */
4982 long_div, /* nb_floor_divide */
4983 long_true_divide, /* nb_true_divide */
4984 0, /* nb_inplace_floor_divide */
4985 0, /* nb_inplace_true_divide */
4986 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004987};
4988
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004989PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004990 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4991 "int", /* tp_name */
4992 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4993 sizeof(digit), /* tp_itemsize */
4994 long_dealloc, /* tp_dealloc */
4995 0, /* tp_print */
4996 0, /* tp_getattr */
4997 0, /* tp_setattr */
4998 0, /* tp_reserved */
4999 long_to_decimal_string, /* tp_repr */
5000 &long_as_number, /* tp_as_number */
5001 0, /* tp_as_sequence */
5002 0, /* tp_as_mapping */
5003 (hashfunc)long_hash, /* tp_hash */
5004 0, /* tp_call */
5005 long_to_decimal_string, /* tp_str */
5006 PyObject_GenericGetAttr, /* tp_getattro */
5007 0, /* tp_setattro */
5008 0, /* tp_as_buffer */
5009 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5010 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5011 long_doc, /* tp_doc */
5012 0, /* tp_traverse */
5013 0, /* tp_clear */
5014 long_richcompare, /* tp_richcompare */
5015 0, /* tp_weaklistoffset */
5016 0, /* tp_iter */
5017 0, /* tp_iternext */
5018 long_methods, /* tp_methods */
5019 0, /* tp_members */
5020 long_getset, /* tp_getset */
5021 0, /* tp_base */
5022 0, /* tp_dict */
5023 0, /* tp_descr_get */
5024 0, /* tp_descr_set */
5025 0, /* tp_dictoffset */
5026 0, /* tp_init */
5027 0, /* tp_alloc */
5028 long_new, /* tp_new */
5029 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005030};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005031
Mark Dickinsonbd792642009-03-18 20:06:12 +00005032static PyTypeObject Int_InfoType;
5033
5034PyDoc_STRVAR(int_info__doc__,
5035"sys.int_info\n\
5036\n\
5037A struct sequence that holds information about Python's\n\
5038internal representation of integers. The attributes are read only.");
5039
5040static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005042 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005044};
5045
5046static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 "sys.int_info", /* name */
5048 int_info__doc__, /* doc */
5049 int_info_fields, /* fields */
5050 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005051};
5052
5053PyObject *
5054PyLong_GetInfo(void)
5055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005056 PyObject* int_info;
5057 int field = 0;
5058 int_info = PyStructSequence_New(&Int_InfoType);
5059 if (int_info == NULL)
5060 return NULL;
5061 PyStructSequence_SET_ITEM(int_info, field++,
5062 PyLong_FromLong(PyLong_SHIFT));
5063 PyStructSequence_SET_ITEM(int_info, field++,
5064 PyLong_FromLong(sizeof(digit)));
5065 if (PyErr_Occurred()) {
5066 Py_CLEAR(int_info);
5067 return NULL;
5068 }
5069 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005070}
5071
Guido van Rossumddefaf32007-01-14 03:31:43 +00005072int
5073_PyLong_Init(void)
5074{
5075#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 int ival, size;
5077 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5080 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5081 if (Py_TYPE(v) == &PyLong_Type) {
5082 /* The element is already initialized, most likely
5083 * the Python interpreter was initialized before.
5084 */
5085 Py_ssize_t refcnt;
5086 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5089 _Py_NewReference(op);
5090 /* _Py_NewReference sets the ref count to 1 but
5091 * the ref count might be larger. Set the refcnt
5092 * to the original refcnt + 1 */
5093 Py_REFCNT(op) = refcnt + 1;
5094 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005095 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 }
5097 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005098 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005099 }
5100 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005101 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005103#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005105 if (Int_InfoType.tp_name == NULL) {
5106 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5107 return 0;
5108 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005111}
5112
5113void
5114PyLong_Fini(void)
5115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 /* Integers are currently statically allocated. Py_DECREF is not
5117 needed, but Python must forget about the reference or multiple
5118 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005119#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 int i;
5121 PyLongObject *v = small_ints;
5122 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5123 _Py_DEC_REFTOTAL;
5124 _Py_ForgetReference((PyObject*)v);
5125 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005126#endif
5127}