blob: 9411216bcbebc10bbba20eef8adf60be890c2902 [file] [log] [blame]
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001/* Long (arbitrary precision) integer object implementation */
2
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003/* XXX The functional organization of this file is terrible */
4
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005#include "Python.h"
Guido van Rossumedcc38a1991-05-05 20:09:44 +00006#include "longintrepr.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00007
Mark Dickinsonc6300392009-04-20 21:38:00 +00008#include <float.h>
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00009#include <ctype.h>
Mark Dickinson5a74bf62009-02-15 11:04:38 +000010#include <stddef.h>
Guido van Rossumedcc38a1991-05-05 20:09:44 +000011
Guido van Rossumddefaf32007-01-14 03:31:43 +000012#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000013#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000014#endif
15#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000017#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000018
Mark Dickinsone4416742009-02-15 15:14:57 +000019/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020020#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
21 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 (Py_SIZE(x) == 0 ? (sdigit)0 : \
23 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024#define ABS(x) ((x) < 0 ? -(x) : (x))
25
Guido van Rossumddefaf32007-01-14 03:31:43 +000026#if NSMALLNEGINTS + NSMALLPOSINTS > 0
27/* Small integers are preallocated in this array so that they
28 can be shared.
29 The integers that are preallocated are those in the range
30 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
31*/
32static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
33#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010034Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000035#endif
36
Guido van Rossum7eaf8222007-06-18 17:58:50 +000037static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000038get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
41 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000042#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000043 if (ival >= 0)
44 quick_int_allocs++;
45 else
46 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000047#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000049}
50#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
52 return get_small_int((sdigit)ival); \
53 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000056maybe_small_long(PyLongObject *v)
57{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (v && ABS(Py_SIZE(v)) <= 1) {
59 sdigit ival = MEDIUM_VALUE(v);
60 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
61 Py_DECREF(v);
62 return (PyLongObject *)get_small_int(ival);
63 }
64 }
65 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000066}
Guido van Rossumddefaf32007-01-14 03:31:43 +000067#else
68#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000070#endif
71
Serhiy Storchaka95949422013-08-27 19:40:23 +030072/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000073 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020074Py_LOCAL_INLINE(void)
75_PyLong_Negate(PyLongObject **x_p)
76{
77 PyLongObject *x;
78
79 x = (PyLongObject *)*x_p;
80 if (Py_REFCNT(x) == 1) {
81 Py_SIZE(x) = -Py_SIZE(x);
82 return;
83 }
84
85 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
86 Py_DECREF(x);
87}
88
Serhiy Storchaka95949422013-08-27 19:40:23 +030089/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +000090 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +030091 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +000092 */
Tim Peters0973b992004-08-29 22:16:50 +000093#define KARATSUBA_CUTOFF 70
94#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +000095
Tim Peters47e52ee2004-08-30 02:44:38 +000096/* For exponentiation, use the binary left-to-right algorithm
97 * unless the exponent contains more than FIVEARY_CUTOFF digits.
98 * In that case, do 5 bits at a time. The potential drawback is that
99 * a table of 2**5 intermediate results is computed.
100 */
101#define FIVEARY_CUTOFF 8
102
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000103#define SIGCHECK(PyTryBlock) \
104 do { \
105 if (PyErr_CheckSignals()) PyTryBlock \
106 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000107
Serhiy Storchaka95949422013-08-27 19:40:23 +0300108/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000109 Doesn't attempt to free the storage--in most cases, due to the nature
110 of the algorithms used, this could save at most be one word anyway. */
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200113long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 Py_ssize_t j = ABS(Py_SIZE(v));
116 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 while (i > 0 && v->ob_digit[i-1] == 0)
119 --i;
120 if (i != j)
121 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
122 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000123}
124
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200125/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
126 using the nb_int slot, if available. Raise TypeError if either the
127 nb_int slot is not available or the result of the call to nb_int
128 returns something not of type int.
129*/
130PyLongObject *
131_PyLong_FromNbInt(PyObject *integral)
132{
133 PyNumberMethods *nb;
134 PyObject *result;
135
136 /* Fast path for the case that we already have an int. */
137 if (PyLong_CheckExact(integral)) {
138 Py_INCREF(integral);
139 return (PyLongObject *)integral;
140 }
141
142 nb = Py_TYPE(integral)->tp_as_number;
143 if (nb == NULL || nb->nb_int == NULL) {
144 PyErr_Format(PyExc_TypeError,
145 "an integer is required (got type %.200s)",
146 Py_TYPE(integral)->tp_name);
147 return NULL;
148 }
149
150 /* Convert using the nb_int slot, which should return something
151 of exact type int. */
152 result = nb->nb_int(integral);
153 if (!result || PyLong_CheckExact(result))
154 return (PyLongObject *)result;
155 if (!PyLong_Check(result)) {
156 PyErr_Format(PyExc_TypeError,
157 "__int__ returned non-int (type %.200s)",
158 result->ob_type->tp_name);
159 Py_DECREF(result);
160 return NULL;
161 }
162 /* Issue #17576: warn if 'result' not of exact type int. */
163 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
164 "__int__ returned non-int (type %.200s). "
165 "The ability to return an instance of a strict subclass of int "
166 "is deprecated, and may be removed in a future version of Python.",
167 result->ob_type->tp_name)) {
168 Py_DECREF(result);
169 return NULL;
170 }
171 return (PyLongObject *)result;
172}
173
174
Serhiy Storchaka95949422013-08-27 19:40:23 +0300175/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000176 Return NULL and set exception if we run out of memory. */
177
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000178#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000180
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000182_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyLongObject *result;
185 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
186 sizeof(digit)*size. Previous incarnations of this code used
187 sizeof(PyVarObject) instead of the offsetof, but this risks being
188 incorrect in the presence of padding between the PyVarObject header
189 and the digits. */
190 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
191 PyErr_SetString(PyExc_OverflowError,
192 "too many digits in integer");
193 return NULL;
194 }
195 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
196 size*sizeof(digit));
197 if (!result) {
198 PyErr_NoMemory();
199 return NULL;
200 }
201 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000202}
203
Tim Peters64b5ce32001-09-10 20:52:51 +0000204PyObject *
205_PyLong_Copy(PyLongObject *src)
206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 PyLongObject *result;
208 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 assert(src != NULL);
211 i = Py_SIZE(src);
212 if (i < 0)
213 i = -(i);
214 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100215 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 CHECK_SMALL_INT(ival);
217 }
218 result = _PyLong_New(i);
219 if (result != NULL) {
220 Py_SIZE(result) = Py_SIZE(src);
221 while (--i >= 0)
222 result->ob_digit[i] = src->ob_digit[i];
223 }
224 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000225}
226
Serhiy Storchaka95949422013-08-27 19:40:23 +0300227/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000228
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000229PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000230PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 PyLongObject *v;
233 unsigned long abs_ival;
234 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
235 int ndigits = 0;
236 int sign = 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (ival < 0) {
241 /* negate: can't write this as abs_ival = -ival since that
242 invokes undefined behaviour when ival is LONG_MIN */
243 abs_ival = 0U-(unsigned long)ival;
244 sign = -1;
245 }
246 else {
247 abs_ival = (unsigned long)ival;
248 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 /* Fast path for single-digit ints */
251 if (!(abs_ival >> PyLong_SHIFT)) {
252 v = _PyLong_New(1);
253 if (v) {
254 Py_SIZE(v) = sign;
255 v->ob_digit[0] = Py_SAFE_DOWNCAST(
256 abs_ival, unsigned long, digit);
257 }
258 return (PyObject*)v;
259 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000260
Mark Dickinson249b8982009-04-27 19:41:00 +0000261#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* 2 digits */
263 if (!(abs_ival >> 2*PyLong_SHIFT)) {
264 v = _PyLong_New(2);
265 if (v) {
266 Py_SIZE(v) = 2*sign;
267 v->ob_digit[0] = Py_SAFE_DOWNCAST(
268 abs_ival & PyLong_MASK, unsigned long, digit);
269 v->ob_digit[1] = Py_SAFE_DOWNCAST(
270 abs_ival >> PyLong_SHIFT, unsigned long, digit);
271 }
272 return (PyObject*)v;
273 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000274#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Larger numbers: loop to determine number of digits */
277 t = abs_ival;
278 while (t) {
279 ++ndigits;
280 t >>= PyLong_SHIFT;
281 }
282 v = _PyLong_New(ndigits);
283 if (v != NULL) {
284 digit *p = v->ob_digit;
285 Py_SIZE(v) = ndigits*sign;
286 t = abs_ival;
287 while (t) {
288 *p++ = Py_SAFE_DOWNCAST(
289 t & PyLong_MASK, unsigned long, digit);
290 t >>= PyLong_SHIFT;
291 }
292 }
293 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000294}
295
Serhiy Storchaka95949422013-08-27 19:40:23 +0300296/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000297
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000298PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000299PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 PyLongObject *v;
302 unsigned long t;
303 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (ival < PyLong_BASE)
306 return PyLong_FromLong(ival);
307 /* Count the number of Python digits. */
308 t = (unsigned long)ival;
309 while (t) {
310 ++ndigits;
311 t >>= PyLong_SHIFT;
312 }
313 v = _PyLong_New(ndigits);
314 if (v != NULL) {
315 digit *p = v->ob_digit;
316 Py_SIZE(v) = ndigits;
317 while (ival) {
318 *p++ = (digit)(ival & PyLong_MASK);
319 ival >>= PyLong_SHIFT;
320 }
321 }
322 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000323}
324
Serhiy Storchaka95949422013-08-27 19:40:23 +0300325/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000326
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000328PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyLongObject *v;
331 double frac;
332 int i, ndig, expo, neg;
333 neg = 0;
334 if (Py_IS_INFINITY(dval)) {
335 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000336 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 return NULL;
338 }
339 if (Py_IS_NAN(dval)) {
340 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000341 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return NULL;
343 }
344 if (dval < 0.0) {
345 neg = 1;
346 dval = -dval;
347 }
348 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
349 if (expo <= 0)
350 return PyLong_FromLong(0L);
351 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
352 v = _PyLong_New(ndig);
353 if (v == NULL)
354 return NULL;
355 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
356 for (i = ndig; --i >= 0; ) {
357 digit bits = (digit)frac;
358 v->ob_digit[i] = bits;
359 frac = frac - (double)bits;
360 frac = ldexp(frac, PyLong_SHIFT);
361 }
362 if (neg)
363 Py_SIZE(v) = -(Py_SIZE(v));
364 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000365}
366
Thomas Wouters89f507f2006-12-13 04:49:30 +0000367/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
368 * anything about what happens when a signed integer operation overflows,
369 * and some compilers think they're doing you a favor by being "clever"
370 * then. The bit pattern for the largest postive signed long is
371 * (unsigned long)LONG_MAX, and for the smallest negative signed long
372 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
373 * However, some other compilers warn about applying unary minus to an
374 * unsigned operand. Hence the weird "0-".
375 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
377#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378
Serhiy Storchaka95949422013-08-27 19:40:23 +0300379/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100380 method.
381
382 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
383 the result. Otherwise *overflow is 0.
384
385 For other errors (e.g., TypeError), return -1 and set an error condition.
386 In this case *overflow will be 0.
387*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000388
389long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000390PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200393 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 unsigned long x, prev;
395 long res;
396 Py_ssize_t i;
397 int sign;
398 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 *overflow = 0;
401 if (vv == NULL) {
402 PyErr_BadInternalCall();
403 return -1;
404 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000405
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200406 if (PyLong_Check(vv)) {
407 v = (PyLongObject *)vv;
408 }
409 else {
410 v = _PyLong_FromNbInt(vv);
411 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 return -1;
413 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 switch (i) {
420 case -1:
421 res = -(sdigit)v->ob_digit[0];
422 break;
423 case 0:
424 res = 0;
425 break;
426 case 1:
427 res = v->ob_digit[0];
428 break;
429 default:
430 sign = 1;
431 x = 0;
432 if (i < 0) {
433 sign = -1;
434 i = -(i);
435 }
436 while (--i >= 0) {
437 prev = x;
438 x = (x << PyLong_SHIFT) | v->ob_digit[i];
439 if ((x >> PyLong_SHIFT) != prev) {
440 *overflow = sign;
441 goto exit;
442 }
443 }
444 /* Haven't lost any bits, but casting to long requires extra
445 * care (see comment above).
446 */
447 if (x <= (unsigned long)LONG_MAX) {
448 res = (long)x * sign;
449 }
450 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
451 res = LONG_MIN;
452 }
453 else {
454 *overflow = sign;
455 /* res is already set to -1 */
456 }
457 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000458 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200460 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 }
462 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000463}
464
Serhiy Storchaka95949422013-08-27 19:40:23 +0300465/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100466 method. Return -1 and set an error if overflow occurs. */
467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000469PyLong_AsLong(PyObject *obj)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 int overflow;
472 long result = PyLong_AsLongAndOverflow(obj, &overflow);
473 if (overflow) {
474 /* XXX: could be cute and give a different
475 message for overflow == -1 */
476 PyErr_SetString(PyExc_OverflowError,
477 "Python int too large to convert to C long");
478 }
479 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000480}
481
Serhiy Storchaka95949422013-08-27 19:40:23 +0300482/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200483 method. Return -1 and set an error if overflow occurs. */
484
485int
486_PyLong_AsInt(PyObject *obj)
487{
488 int overflow;
489 long result = PyLong_AsLongAndOverflow(obj, &overflow);
490 if (overflow || result > INT_MAX || result < INT_MIN) {
491 /* XXX: could be cute and give a different
492 message for overflow == -1 */
493 PyErr_SetString(PyExc_OverflowError,
494 "Python int too large to convert to C int");
495 return -1;
496 }
497 return (int)result;
498}
499
Serhiy Storchaka95949422013-08-27 19:40:23 +0300500/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000501 Returns -1 and sets an error condition if overflow occurs. */
502
503Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000504PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200505 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 size_t x, prev;
507 Py_ssize_t i;
508 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (vv == NULL) {
511 PyErr_BadInternalCall();
512 return -1;
513 }
514 if (!PyLong_Check(vv)) {
515 PyErr_SetString(PyExc_TypeError, "an integer is required");
516 return -1;
517 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 v = (PyLongObject *)vv;
520 i = Py_SIZE(v);
521 switch (i) {
522 case -1: return -(sdigit)v->ob_digit[0];
523 case 0: return 0;
524 case 1: return v->ob_digit[0];
525 }
526 sign = 1;
527 x = 0;
528 if (i < 0) {
529 sign = -1;
530 i = -(i);
531 }
532 while (--i >= 0) {
533 prev = x;
534 x = (x << PyLong_SHIFT) | v->ob_digit[i];
535 if ((x >> PyLong_SHIFT) != prev)
536 goto overflow;
537 }
538 /* Haven't lost any bits, but casting to a signed type requires
539 * extra care (see comment above).
540 */
541 if (x <= (size_t)PY_SSIZE_T_MAX) {
542 return (Py_ssize_t)x * sign;
543 }
544 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
545 return PY_SSIZE_T_MIN;
546 }
547 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000548
Mark Dickinson22b20182010-05-10 21:27:53 +0000549 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 PyErr_SetString(PyExc_OverflowError,
551 "Python int too large to convert to C ssize_t");
552 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000553}
554
Serhiy Storchaka95949422013-08-27 19:40:23 +0300555/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000556 Returns -1 and sets an error condition if overflow occurs. */
557
558unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000559PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000560{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200561 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 unsigned long x, prev;
563 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (vv == NULL) {
566 PyErr_BadInternalCall();
567 return (unsigned long)-1;
568 }
569 if (!PyLong_Check(vv)) {
570 PyErr_SetString(PyExc_TypeError, "an integer is required");
571 return (unsigned long)-1;
572 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 v = (PyLongObject *)vv;
575 i = Py_SIZE(v);
576 x = 0;
577 if (i < 0) {
578 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000579 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return (unsigned long) -1;
581 }
582 switch (i) {
583 case 0: return 0;
584 case 1: return v->ob_digit[0];
585 }
586 while (--i >= 0) {
587 prev = x;
588 x = (x << PyLong_SHIFT) | v->ob_digit[i];
589 if ((x >> PyLong_SHIFT) != prev) {
590 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100591 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000592 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return (unsigned long) -1;
594 }
595 }
596 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000597}
598
Serhiy Storchaka95949422013-08-27 19:40:23 +0300599/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200600 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000601
602size_t
603PyLong_AsSize_t(PyObject *vv)
604{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200605 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 size_t x, prev;
607 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (vv == NULL) {
610 PyErr_BadInternalCall();
611 return (size_t) -1;
612 }
613 if (!PyLong_Check(vv)) {
614 PyErr_SetString(PyExc_TypeError, "an integer is required");
615 return (size_t)-1;
616 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 v = (PyLongObject *)vv;
619 i = Py_SIZE(v);
620 x = 0;
621 if (i < 0) {
622 PyErr_SetString(PyExc_OverflowError,
623 "can't convert negative value to size_t");
624 return (size_t) -1;
625 }
626 switch (i) {
627 case 0: return 0;
628 case 1: return v->ob_digit[0];
629 }
630 while (--i >= 0) {
631 prev = x;
632 x = (x << PyLong_SHIFT) | v->ob_digit[i];
633 if ((x >> PyLong_SHIFT) != prev) {
634 PyErr_SetString(PyExc_OverflowError,
635 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200636 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 }
638 }
639 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000640}
641
Serhiy Storchaka95949422013-08-27 19:40:23 +0300642/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000643 Returns -1 and sets an error condition if an error occurs. */
644
Guido van Rossumddefaf32007-01-14 03:31:43 +0000645static unsigned long
646_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000647{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200648 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 unsigned long x;
650 Py_ssize_t i;
651 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (vv == NULL || !PyLong_Check(vv)) {
654 PyErr_BadInternalCall();
655 return (unsigned long) -1;
656 }
657 v = (PyLongObject *)vv;
658 i = Py_SIZE(v);
659 switch (i) {
660 case 0: return 0;
661 case 1: return v->ob_digit[0];
662 }
663 sign = 1;
664 x = 0;
665 if (i < 0) {
666 sign = -1;
667 i = -i;
668 }
669 while (--i >= 0) {
670 x = (x << PyLong_SHIFT) | v->ob_digit[i];
671 }
672 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000673}
674
Guido van Rossumddefaf32007-01-14 03:31:43 +0000675unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200676PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyLongObject *lo;
679 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000680
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200681 if (op == NULL) {
682 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return (unsigned long)-1;
684 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000685
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200686 if (PyLong_Check(op)) {
687 return _PyLong_AsUnsignedLongMask(op);
688 }
689
690 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (lo == NULL)
692 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200693
694 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
695 Py_DECREF(lo);
696 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000697}
698
Tim Peters5b8132f2003-01-31 15:52:05 +0000699int
700_PyLong_Sign(PyObject *vv)
701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 assert(v != NULL);
705 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000708}
709
Tim Petersbaefd9e2003-01-28 20:37:45 +0000710size_t
711_PyLong_NumBits(PyObject *vv)
712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyLongObject *v = (PyLongObject *)vv;
714 size_t result = 0;
715 Py_ssize_t ndigits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 assert(v != NULL);
718 assert(PyLong_Check(v));
719 ndigits = ABS(Py_SIZE(v));
720 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
721 if (ndigits > 0) {
722 digit msd = v->ob_digit[ndigits - 1];
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100723 if ((size_t)(ndigits - 1) > PY_SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100725 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 do {
727 ++result;
728 if (result == 0)
729 goto Overflow;
730 msd >>= 1;
731 } while (msd);
732 }
733 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000734
Mark Dickinson22b20182010-05-10 21:27:53 +0000735 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
737 "to express in a platform size_t");
738 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000739}
740
Tim Peters2a9b3672001-06-11 21:23:58 +0000741PyObject *
742_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000744{
Mark Dickinson22b20182010-05-10 21:27:53 +0000745 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 int incr; /* direction to move pstartbyte */
747 const unsigned char* pendbyte; /* MSB of bytes */
748 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300749 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyLongObject* v; /* result */
751 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (n == 0)
754 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (little_endian) {
757 pstartbyte = bytes;
758 pendbyte = bytes + n - 1;
759 incr = 1;
760 }
761 else {
762 pstartbyte = bytes + n - 1;
763 pendbyte = bytes;
764 incr = -1;
765 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 if (is_signed)
768 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200771 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 is positive, and leading 0xff bytes if negative. */
773 {
774 size_t i;
775 const unsigned char* p = pendbyte;
776 const int pincr = -incr; /* search MSB to LSB */
777 const unsigned char insignficant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 for (i = 0; i < n; ++i, p += pincr) {
780 if (*p != insignficant)
781 break;
782 }
783 numsignificantbytes = n - i;
784 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
785 actually has 2 significant bytes. OTOH, 0xff0001 ==
786 -0x00ffff, so we wouldn't *need* to bump it there; but we
787 do for 0xffff = -0x0001. To be safe without bothering to
788 check every case, bump it regardless. */
789 if (is_signed && numsignificantbytes < n)
790 ++numsignificantbytes;
791 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000792
Serhiy Storchaka95949422013-08-27 19:40:23 +0300793 /* How many Python int digits do we need? We have
794 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
796 /* catch overflow before it happens */
797 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
798 PyErr_SetString(PyExc_OverflowError,
799 "byte array too long to convert to int");
800 return NULL;
801 }
802 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
803 v = _PyLong_New(ndigits);
804 if (v == NULL)
805 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 /* Copy the bits over. The tricky parts are computing 2's-comp on
808 the fly for signed numbers, and dealing with the mismatch between
809 8-bit bytes and (probably) 15-bit Python digits.*/
810 {
811 size_t i;
812 twodigits carry = 1; /* for 2's-comp calculation */
813 twodigits accum = 0; /* sliding register */
814 unsigned int accumbits = 0; /* number of bits in accum */
815 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
818 twodigits thisbyte = *p;
819 /* Compute correction for 2's comp, if needed. */
820 if (is_signed) {
821 thisbyte = (0xff ^ thisbyte) + carry;
822 carry = thisbyte >> 8;
823 thisbyte &= 0xff;
824 }
825 /* Because we're going LSB to MSB, thisbyte is
826 more significant than what's already in accum,
827 so needs to be prepended to accum. */
828 accum |= (twodigits)thisbyte << accumbits;
829 accumbits += 8;
830 if (accumbits >= PyLong_SHIFT) {
831 /* There's enough to fill a Python digit. */
832 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000833 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 ++idigit;
835 accum >>= PyLong_SHIFT;
836 accumbits -= PyLong_SHIFT;
837 assert(accumbits < PyLong_SHIFT);
838 }
839 }
840 assert(accumbits < PyLong_SHIFT);
841 if (accumbits) {
842 assert(idigit < ndigits);
843 v->ob_digit[idigit] = (digit)accum;
844 ++idigit;
845 }
846 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_SIZE(v) = is_signed ? -idigit : idigit;
849 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000850}
851
852int
853_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 unsigned char* bytes, size_t n,
855 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000858 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000860 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
862 digit carry; /* for computing 2's-comp */
863 size_t j; /* # bytes filled */
864 unsigned char* p; /* pointer to next byte in bytes */
865 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (Py_SIZE(v) < 0) {
870 ndigits = -(Py_SIZE(v));
871 if (!is_signed) {
872 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000873 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 return -1;
875 }
876 do_twos_comp = 1;
877 }
878 else {
879 ndigits = Py_SIZE(v);
880 do_twos_comp = 0;
881 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (little_endian) {
884 p = bytes;
885 pincr = 1;
886 }
887 else {
888 p = bytes + n - 1;
889 pincr = -1;
890 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* Copy over all the Python digits.
893 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300894 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 normalized. */
896 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
897 j = 0;
898 accum = 0;
899 accumbits = 0;
900 carry = do_twos_comp ? 1 : 0;
901 for (i = 0; i < ndigits; ++i) {
902 digit thisdigit = v->ob_digit[i];
903 if (do_twos_comp) {
904 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
905 carry = thisdigit >> PyLong_SHIFT;
906 thisdigit &= PyLong_MASK;
907 }
908 /* Because we're going LSB to MSB, thisdigit is more
909 significant than what's already in accum, so needs to be
910 prepended to accum. */
911 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* The most-significant digit may be (probably is) at least
914 partly empty. */
915 if (i == ndigits - 1) {
916 /* Count # of sign bits -- they needn't be stored,
917 * although for signed conversion we need later to
918 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000919 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 while (s != 0) {
921 s >>= 1;
922 accumbits++;
923 }
924 }
925 else
926 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Store as many bytes as possible. */
929 while (accumbits >= 8) {
930 if (j >= n)
931 goto Overflow;
932 ++j;
933 *p = (unsigned char)(accum & 0xff);
934 p += pincr;
935 accumbits -= 8;
936 accum >>= 8;
937 }
938 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* Store the straggler (if any). */
941 assert(accumbits < 8);
942 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
943 if (accumbits > 0) {
944 if (j >= n)
945 goto Overflow;
946 ++j;
947 if (do_twos_comp) {
948 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300949 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 infinite supply of sign bits). */
951 accum |= (~(twodigits)0) << accumbits;
952 }
953 *p = (unsigned char)(accum & 0xff);
954 p += pincr;
955 }
956 else if (j == n && n > 0 && is_signed) {
957 /* The main loop filled the byte array exactly, so the code
958 just above didn't get to ensure there's a sign bit, and the
959 loop below wouldn't add one either. Make sure a sign bit
960 exists. */
961 unsigned char msb = *(p - pincr);
962 int sign_bit_set = msb >= 0x80;
963 assert(accumbits == 0);
964 if (sign_bit_set == do_twos_comp)
965 return 0;
966 else
967 goto Overflow;
968 }
Tim Peters05607ad2001-06-13 21:01:27 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Fill remaining bytes with copies of the sign bit. */
971 {
972 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
973 for ( ; j < n; ++j, p += pincr)
974 *p = signbyte;
975 }
Tim Peters05607ad2001-06-13 21:01:27 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +0000978
Mark Dickinson22b20182010-05-10 21:27:53 +0000979 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
981 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000982
Tim Peters2a9b3672001-06-11 21:23:58 +0000983}
984
Serhiy Storchaka95949422013-08-27 19:40:23 +0300985/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +0000986
987PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000988PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +0000989{
Mark Dickinson91044792012-10-18 19:21:43 +0100990#if SIZEOF_VOID_P <= SIZEOF_LONG
Mark Dickinson91044792012-10-18 19:21:43 +0100991 return PyLong_FromUnsignedLong((unsigned long)(Py_uintptr_t)p);
992#else
993
Tim Peters70128a12001-06-16 08:48:40 +0000994#ifndef HAVE_LONG_LONG
995# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
996#endif
997#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +0000998# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +0000999#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001001#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001002
Guido van Rossum78694d91998-09-18 14:14:13 +00001003}
1004
Serhiy Storchaka95949422013-08-27 19:40:23 +03001005/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001006
1007void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001008PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001009{
Tim Peters70128a12001-06-16 08:48:40 +00001010#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1014 x = PyLong_AsLong(vv);
1015 else
1016 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001017#else
Tim Peters70128a12001-06-16 08:48:40 +00001018
1019#ifndef HAVE_LONG_LONG
1020# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
1021#endif
1022#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001023# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001024#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PY_LONG_LONG x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1028 x = PyLong_AsLongLong(vv);
1029 else
1030 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001031
1032#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 if (x == -1 && PyErr_Occurred())
1035 return NULL;
1036 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001037}
1038
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001039#ifdef HAVE_LONG_LONG
Tim Petersd1a7da62001-06-13 00:35:57 +00001040
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001041/* Initial PY_LONG_LONG support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001042 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001043 */
1044
Mark Dickinson22b20182010-05-10 21:27:53 +00001045#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001046
Serhiy Storchaka95949422013-08-27 19:40:23 +03001047/* Create a new int object from a C PY_LONG_LONG int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001048
1049PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001050PyLong_FromLongLong(PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyLongObject *v;
1053 unsigned PY_LONG_LONG abs_ival;
1054 unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
1055 int ndigits = 0;
1056 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 CHECK_SMALL_INT(ival);
1059 if (ival < 0) {
1060 /* avoid signed overflow on negation; see comments
1061 in PyLong_FromLong above. */
1062 abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
1063 negative = 1;
1064 }
1065 else {
1066 abs_ival = (unsigned PY_LONG_LONG)ival;
1067 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 /* Count the number of Python digits.
1070 We used to pick 5 ("big enough for anything"), but that's a
1071 waste of time and space given that 5*15 = 75 bits are rarely
1072 needed. */
1073 t = abs_ival;
1074 while (t) {
1075 ++ndigits;
1076 t >>= PyLong_SHIFT;
1077 }
1078 v = _PyLong_New(ndigits);
1079 if (v != NULL) {
1080 digit *p = v->ob_digit;
1081 Py_SIZE(v) = negative ? -ndigits : ndigits;
1082 t = abs_ival;
1083 while (t) {
1084 *p++ = (digit)(t & PyLong_MASK);
1085 t >>= PyLong_SHIFT;
1086 }
1087 }
1088 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001089}
1090
Serhiy Storchaka95949422013-08-27 19:40:23 +03001091/* Create a new int object from a C unsigned PY_LONG_LONG int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001092
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001093PyObject *
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001094PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyLongObject *v;
1097 unsigned PY_LONG_LONG t;
1098 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (ival < PyLong_BASE)
1101 return PyLong_FromLong((long)ival);
1102 /* Count the number of Python digits. */
1103 t = (unsigned PY_LONG_LONG)ival;
1104 while (t) {
1105 ++ndigits;
1106 t >>= PyLong_SHIFT;
1107 }
1108 v = _PyLong_New(ndigits);
1109 if (v != NULL) {
1110 digit *p = v->ob_digit;
1111 Py_SIZE(v) = ndigits;
1112 while (ival) {
1113 *p++ = (digit)(ival & PyLong_MASK);
1114 ival >>= PyLong_SHIFT;
1115 }
1116 }
1117 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001118}
1119
Serhiy Storchaka95949422013-08-27 19:40:23 +03001120/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001121
1122PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001123PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 PyLongObject *v;
1126 size_t abs_ival;
1127 size_t t; /* unsigned so >> doesn't propagate sign bit */
1128 int ndigits = 0;
1129 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 CHECK_SMALL_INT(ival);
1132 if (ival < 0) {
1133 /* avoid signed overflow when ival = SIZE_T_MIN */
1134 abs_ival = (size_t)(-1-ival)+1;
1135 negative = 1;
1136 }
1137 else {
1138 abs_ival = (size_t)ival;
1139 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 /* Count the number of Python digits. */
1142 t = abs_ival;
1143 while (t) {
1144 ++ndigits;
1145 t >>= PyLong_SHIFT;
1146 }
1147 v = _PyLong_New(ndigits);
1148 if (v != NULL) {
1149 digit *p = v->ob_digit;
1150 Py_SIZE(v) = negative ? -ndigits : ndigits;
1151 t = abs_ival;
1152 while (t) {
1153 *p++ = (digit)(t & PyLong_MASK);
1154 t >>= PyLong_SHIFT;
1155 }
1156 }
1157 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001158}
1159
Serhiy Storchaka95949422013-08-27 19:40:23 +03001160/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001161
1162PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001163PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 PyLongObject *v;
1166 size_t t;
1167 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 if (ival < PyLong_BASE)
1170 return PyLong_FromLong((long)ival);
1171 /* Count the number of Python digits. */
1172 t = ival;
1173 while (t) {
1174 ++ndigits;
1175 t >>= PyLong_SHIFT;
1176 }
1177 v = _PyLong_New(ndigits);
1178 if (v != NULL) {
1179 digit *p = v->ob_digit;
1180 Py_SIZE(v) = ndigits;
1181 while (ival) {
1182 *p++ = (digit)(ival & PyLong_MASK);
1183 ival >>= PyLong_SHIFT;
1184 }
1185 }
1186 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001187}
1188
Serhiy Storchaka95949422013-08-27 19:40:23 +03001189/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001190 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001191
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001192PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001193PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyLongObject *v;
1196 PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001198 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (vv == NULL) {
1201 PyErr_BadInternalCall();
1202 return -1;
1203 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001204
1205 if (PyLong_Check(vv)) {
1206 v = (PyLongObject *)vv;
1207 }
1208 else {
1209 v = _PyLong_FromNbInt(vv);
1210 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001212 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001214
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001215 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001217 case -1:
1218 bytes = -(sdigit)v->ob_digit[0];
1219 break;
1220 case 0:
1221 bytes = 0;
1222 break;
1223 case 1:
1224 bytes = v->ob_digit[0];
1225 break;
1226 default:
1227 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001228 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001230 if (do_decref) {
1231 Py_DECREF(v);
1232 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1235 if (res < 0)
1236 return (PY_LONG_LONG)-1;
1237 else
1238 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001239}
1240
Serhiy Storchaka95949422013-08-27 19:40:23 +03001241/* Get a C unsigned PY_LONG_LONG int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001242 Return -1 and set an error if overflow occurs. */
1243
Martin v. Löwisb9a0f912003-03-29 10:06:18 +00001244unsigned PY_LONG_LONG
Tim Peters9f688bf2000-07-07 15:53:28 +00001245PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 PyLongObject *v;
1248 unsigned PY_LONG_LONG bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001250
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001251 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyErr_BadInternalCall();
1253 return (unsigned PY_LONG_LONG)-1;
1254 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001255 if (!PyLong_Check(vv)) {
1256 PyErr_SetString(PyExc_TypeError, "an integer is required");
1257 return (unsigned PY_LONG_LONG)-1;
1258 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 v = (PyLongObject*)vv;
1261 switch(Py_SIZE(v)) {
1262 case 0: return 0;
1263 case 1: return v->ob_digit[0];
1264 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001265
Mark Dickinson22b20182010-05-10 21:27:53 +00001266 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001267 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
1270 if (res < 0)
1271 return (unsigned PY_LONG_LONG)res;
1272 else
1273 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001274}
Tim Petersd1a7da62001-06-13 00:35:57 +00001275
Serhiy Storchaka95949422013-08-27 19:40:23 +03001276/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001277 Returns -1 and sets an error condition if an error occurs. */
1278
Guido van Rossumddefaf32007-01-14 03:31:43 +00001279static unsigned PY_LONG_LONG
1280_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001281{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001282 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 unsigned PY_LONG_LONG x;
1284 Py_ssize_t i;
1285 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (vv == NULL || !PyLong_Check(vv)) {
1288 PyErr_BadInternalCall();
1289 return (unsigned long) -1;
1290 }
1291 v = (PyLongObject *)vv;
1292 switch(Py_SIZE(v)) {
1293 case 0: return 0;
1294 case 1: return v->ob_digit[0];
1295 }
1296 i = Py_SIZE(v);
1297 sign = 1;
1298 x = 0;
1299 if (i < 0) {
1300 sign = -1;
1301 i = -i;
1302 }
1303 while (--i >= 0) {
1304 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1305 }
1306 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001307}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001308
1309unsigned PY_LONG_LONG
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001310PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 PyLongObject *lo;
1313 unsigned PY_LONG_LONG val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001314
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001315 if (op == NULL) {
1316 PyErr_BadInternalCall();
1317 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001319
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001320 if (PyLong_Check(op)) {
1321 return _PyLong_AsUnsignedLongLongMask(op);
1322 }
1323
1324 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (lo == NULL)
1326 return (unsigned PY_LONG_LONG)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001327
1328 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1329 Py_DECREF(lo);
1330 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001331}
Tim Petersd1a7da62001-06-13 00:35:57 +00001332
Serhiy Storchaka95949422013-08-27 19:40:23 +03001333/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001334 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001335
Mark Dickinson8d48b432011-10-23 20:47:14 +01001336 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1337 the result. Otherwise *overflow is 0.
1338
1339 For other errors (e.g., TypeError), return -1 and set an error condition.
1340 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001341*/
1342
1343PY_LONG_LONG
1344PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001347 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 unsigned PY_LONG_LONG x, prev;
1349 PY_LONG_LONG res;
1350 Py_ssize_t i;
1351 int sign;
1352 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 *overflow = 0;
1355 if (vv == NULL) {
1356 PyErr_BadInternalCall();
1357 return -1;
1358 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001359
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001360 if (PyLong_Check(vv)) {
1361 v = (PyLongObject *)vv;
1362 }
1363 else {
1364 v = _PyLong_FromNbInt(vv);
1365 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 return -1;
1367 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 switch (i) {
1374 case -1:
1375 res = -(sdigit)v->ob_digit[0];
1376 break;
1377 case 0:
1378 res = 0;
1379 break;
1380 case 1:
1381 res = v->ob_digit[0];
1382 break;
1383 default:
1384 sign = 1;
1385 x = 0;
1386 if (i < 0) {
1387 sign = -1;
1388 i = -(i);
1389 }
1390 while (--i >= 0) {
1391 prev = x;
1392 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1393 if ((x >> PyLong_SHIFT) != prev) {
1394 *overflow = sign;
1395 goto exit;
1396 }
1397 }
1398 /* Haven't lost any bits, but casting to long requires extra
1399 * care (see comment above).
1400 */
1401 if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
1402 res = (PY_LONG_LONG)x * sign;
1403 }
1404 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1405 res = PY_LLONG_MIN;
1406 }
1407 else {
1408 *overflow = sign;
1409 /* res is already set to -1 */
1410 }
1411 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001412 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001414 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 }
1416 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001417}
1418
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001419#endif /* HAVE_LONG_LONG */
1420
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001421#define CHECK_BINOP(v,w) \
1422 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001423 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1424 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001425 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001426
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001427/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
1428 2**k if d is nonzero, else 0. */
1429
1430static const unsigned char BitLengthTable[32] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
1432 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001433};
1434
1435static int
1436bits_in_digit(digit d)
1437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 int d_bits = 0;
1439 while (d >= 32) {
1440 d_bits += 6;
1441 d >>= 6;
1442 }
1443 d_bits += (int)BitLengthTable[d];
1444 return d_bits;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001445}
1446
Tim Peters877a2122002-08-12 05:09:36 +00001447/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1448 * is modified in place, by adding y to it. Carries are propagated as far as
1449 * x[m-1], and the remaining carry (0 or 1) is returned.
1450 */
1451static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001452v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 Py_ssize_t i;
1455 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 assert(m >= n);
1458 for (i = 0; i < n; ++i) {
1459 carry += x[i] + y[i];
1460 x[i] = carry & PyLong_MASK;
1461 carry >>= PyLong_SHIFT;
1462 assert((carry & 1) == carry);
1463 }
1464 for (; carry && i < m; ++i) {
1465 carry += x[i];
1466 x[i] = carry & PyLong_MASK;
1467 carry >>= PyLong_SHIFT;
1468 assert((carry & 1) == carry);
1469 }
1470 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001471}
1472
1473/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1474 * is modified in place, by subtracting y from it. Borrows are propagated as
1475 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1476 */
1477static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001478v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 Py_ssize_t i;
1481 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 assert(m >= n);
1484 for (i = 0; i < n; ++i) {
1485 borrow = x[i] - y[i] - borrow;
1486 x[i] = borrow & PyLong_MASK;
1487 borrow >>= PyLong_SHIFT;
1488 borrow &= 1; /* keep only 1 sign bit */
1489 }
1490 for (; borrow && i < m; ++i) {
1491 borrow = x[i] - borrow;
1492 x[i] = borrow & PyLong_MASK;
1493 borrow >>= PyLong_SHIFT;
1494 borrow &= 1;
1495 }
1496 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001497}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001498
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001499/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1500 * result in z[0:m], and return the d bits shifted out of the top.
1501 */
1502static digit
1503v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_ssize_t i;
1506 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 assert(0 <= d && d < PyLong_SHIFT);
1509 for (i=0; i < m; i++) {
1510 twodigits acc = (twodigits)a[i] << d | carry;
1511 z[i] = (digit)acc & PyLong_MASK;
1512 carry = (digit)(acc >> PyLong_SHIFT);
1513 }
1514 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001515}
1516
1517/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1518 * result in z[0:m], and return the d bits shifted out of the bottom.
1519 */
1520static digit
1521v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 Py_ssize_t i;
1524 digit carry = 0;
1525 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 assert(0 <= d && d < PyLong_SHIFT);
1528 for (i=m; i-- > 0;) {
1529 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1530 carry = (digit)acc & mask;
1531 z[i] = (digit)(acc >> d);
1532 }
1533 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001534}
1535
Tim Peters212e6142001-07-14 12:23:19 +00001536/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1537 in pout, and returning the remainder. pin and pout point at the LSD.
1538 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001539 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001540 immutable. */
1541
1542static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001543inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001544{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 assert(n > 0 && n <= PyLong_MASK);
1548 pin += size;
1549 pout += size;
1550 while (--size >= 0) {
1551 digit hi;
1552 rem = (rem << PyLong_SHIFT) | *--pin;
1553 *--pout = hi = (digit)(rem / n);
1554 rem -= (twodigits)hi * n;
1555 }
1556 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001557}
1558
Serhiy Storchaka95949422013-08-27 19:40:23 +03001559/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001560 (as function result) and the remainder (through *prem).
1561 The sign of a is ignored; n should not be zero. */
1562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001563static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001564divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 const Py_ssize_t size = ABS(Py_SIZE(a));
1567 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 assert(n > 0 && n <= PyLong_MASK);
1570 z = _PyLong_New(size);
1571 if (z == NULL)
1572 return NULL;
1573 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1574 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001575}
1576
Serhiy Storchaka95949422013-08-27 19:40:23 +03001577/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001578 string. (Return value is non-shared so that callers can modify the
1579 returned value if necessary.) */
1580
Victor Stinnerd3f08822012-05-29 12:57:52 +02001581static int
1582long_to_decimal_string_internal(PyObject *aa,
1583 PyObject **p_output,
1584 _PyUnicodeWriter *writer)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyLongObject *scratch, *a;
1587 PyObject *str;
1588 Py_ssize_t size, strlen, size_a, i, j;
1589 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 int negative;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001591 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 a = (PyLongObject *)aa;
1594 if (a == NULL || !PyLong_Check(a)) {
1595 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001596 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 }
1598 size_a = ABS(Py_SIZE(a));
1599 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* quick and dirty upper bound for the number of digits
1602 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 But log2(a) < size_a * PyLong_SHIFT, and
1607 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
1608 > 3 * _PyLong_DECIMAL_SHIFT
1609 */
1610 if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
1611 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001612 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001613 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 }
1615 /* the expression size_a * PyLong_SHIFT is now safe from overflow */
1616 size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
1617 scratch = _PyLong_New(size);
1618 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001619 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* convert array of base _PyLong_BASE digits in pin to an array of
1622 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1623 Volume 2 (3rd edn), section 4.4, Method 1b). */
1624 pin = a->ob_digit;
1625 pout = scratch->ob_digit;
1626 size = 0;
1627 for (i = size_a; --i >= 0; ) {
1628 digit hi = pin[i];
1629 for (j = 0; j < size; j++) {
1630 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1631 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1632 pout[j] = (digit)(z - (twodigits)hi *
1633 _PyLong_DECIMAL_BASE);
1634 }
1635 while (hi) {
1636 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1637 hi /= _PyLong_DECIMAL_BASE;
1638 }
1639 /* check for keyboard interrupt */
1640 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001641 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001642 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001643 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 }
1645 /* pout should have at least one digit, so that the case when a = 0
1646 works correctly */
1647 if (size == 0)
1648 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* calculate exact length of output string, and allocate */
1651 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1652 tenpow = 10;
1653 rem = pout[size-1];
1654 while (rem >= tenpow) {
1655 tenpow *= 10;
1656 strlen++;
1657 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001658 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001659 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1660 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001661 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001662 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001663 kind = writer->kind;
1664 str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001666 else {
1667 str = PyUnicode_New(strlen, '9');
1668 if (str == NULL) {
1669 Py_DECREF(scratch);
1670 return -1;
1671 }
1672 kind = PyUnicode_KIND(str);
1673 }
1674
1675#define WRITE_DIGITS(TYPE) \
1676 do { \
1677 if (writer) \
1678 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1679 else \
1680 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1681 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001682 /* pout[0] through pout[size-2] contribute exactly \
1683 _PyLong_DECIMAL_SHIFT digits each */ \
1684 for (i=0; i < size - 1; i++) { \
1685 rem = pout[i]; \
1686 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1687 *--p = '0' + rem % 10; \
1688 rem /= 10; \
1689 } \
1690 } \
1691 /* pout[size-1]: always produce at least one decimal digit */ \
1692 rem = pout[i]; \
1693 do { \
1694 *--p = '0' + rem % 10; \
1695 rem /= 10; \
1696 } while (rem != 0); \
1697 \
1698 /* and sign */ \
1699 if (negative) \
1700 *--p = '-'; \
1701 \
1702 /* check we've counted correctly */ \
1703 if (writer) \
1704 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1705 else \
1706 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1707 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 /* fill the string right-to-left */
Victor Stinnerd3f08822012-05-29 12:57:52 +02001710 if (kind == PyUnicode_1BYTE_KIND) {
1711 Py_UCS1 *p;
1712 WRITE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001714 else if (kind == PyUnicode_2BYTE_KIND) {
1715 Py_UCS2 *p;
1716 WRITE_DIGITS(Py_UCS2);
1717 }
1718 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001719 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001720 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001721 WRITE_DIGITS(Py_UCS4);
1722 }
1723#undef WRITE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001726 if (writer) {
1727 writer->pos += strlen;
1728 }
1729 else {
1730 assert(_PyUnicode_CheckConsistency(str, 1));
1731 *p_output = (PyObject *)str;
1732 }
1733 return 0;
1734}
1735
1736static PyObject *
1737long_to_decimal_string(PyObject *aa)
1738{
1739 PyObject *v;
1740 if (long_to_decimal_string_internal(aa, &v, NULL) == -1)
1741 return NULL;
1742 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001743}
1744
Serhiy Storchaka95949422013-08-27 19:40:23 +03001745/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001746 which should be one of 2, 8 or 16. Return a string object.
1747 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1748 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001749
Victor Stinnerd3f08822012-05-29 12:57:52 +02001750static int
1751long_format_binary(PyObject *aa, int base, int alternate,
1752 PyObject **p_output, _PyUnicodeWriter *writer)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001753{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001754 PyLongObject *a = (PyLongObject *)aa;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 PyObject *v;
Mark Dickinsone2846542012-04-20 21:21:24 +01001756 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001758 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001759 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001761
Victor Stinnerd3f08822012-05-29 12:57:52 +02001762 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (a == NULL || !PyLong_Check(a)) {
1764 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001765 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 }
1767 size_a = ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001768 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Compute a rough upper bound for the length of the string */
1771 switch (base) {
1772 case 16:
1773 bits = 4;
1774 break;
1775 case 8:
1776 bits = 3;
1777 break;
1778 case 2:
1779 bits = 1;
1780 break;
1781 default:
1782 assert(0); /* shouldn't ever get here */
1783 bits = 0; /* to silence gcc warning */
1784 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001785
Mark Dickinsone2846542012-04-20 21:21:24 +01001786 /* Compute exact length 'sz' of output string. */
1787 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001788 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001789 }
1790 else {
1791 Py_ssize_t size_a_in_bits;
1792 /* Ensure overflow doesn't occur during computation of sz. */
1793 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1794 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001795 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001796 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001797 }
1798 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1799 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001800 /* Allow 1 character for a '-' sign. */
1801 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1802 }
1803 if (alternate) {
1804 /* 2 characters for prefix */
1805 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001806 }
1807
Victor Stinnerd3f08822012-05-29 12:57:52 +02001808 if (writer) {
1809 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1810 return -1;
1811 kind = writer->kind;
1812 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 }
1814 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001815 v = PyUnicode_New(sz, 'x');
1816 if (v == NULL)
1817 return -1;
1818 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001820
Victor Stinnerd3f08822012-05-29 12:57:52 +02001821#define WRITE_DIGITS(TYPE) \
1822 do { \
1823 if (writer) \
1824 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1825 else \
1826 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1827 \
1828 if (size_a == 0) { \
1829 *--p = '0'; \
1830 } \
1831 else { \
1832 /* JRH: special case for power-of-2 bases */ \
1833 twodigits accum = 0; \
1834 int accumbits = 0; /* # of bits in accum */ \
1835 Py_ssize_t i; \
1836 for (i = 0; i < size_a; ++i) { \
1837 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1838 accumbits += PyLong_SHIFT; \
1839 assert(accumbits >= bits); \
1840 do { \
1841 char cdigit; \
1842 cdigit = (char)(accum & (base - 1)); \
1843 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1844 *--p = cdigit; \
1845 accumbits -= bits; \
1846 accum >>= bits; \
1847 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1848 } \
1849 } \
1850 \
1851 if (alternate) { \
1852 if (base == 16) \
1853 *--p = 'x'; \
1854 else if (base == 8) \
1855 *--p = 'o'; \
1856 else /* (base == 2) */ \
1857 *--p = 'b'; \
1858 *--p = '0'; \
1859 } \
1860 if (negative) \
1861 *--p = '-'; \
1862 if (writer) \
1863 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1864 else \
1865 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1866 } while (0)
1867
1868 if (kind == PyUnicode_1BYTE_KIND) {
1869 Py_UCS1 *p;
1870 WRITE_DIGITS(Py_UCS1);
1871 }
1872 else if (kind == PyUnicode_2BYTE_KIND) {
1873 Py_UCS2 *p;
1874 WRITE_DIGITS(Py_UCS2);
1875 }
1876 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001877 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001878 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001879 WRITE_DIGITS(Py_UCS4);
1880 }
1881#undef WRITE_DIGITS
1882
1883 if (writer) {
1884 writer->pos += sz;
1885 }
1886 else {
1887 assert(_PyUnicode_CheckConsistency(v, 1));
1888 *p_output = v;
1889 }
1890 return 0;
1891}
1892
1893PyObject *
1894_PyLong_Format(PyObject *obj, int base)
1895{
1896 PyObject *str;
1897 int err;
1898 if (base == 10)
1899 err = long_to_decimal_string_internal(obj, &str, NULL);
1900 else
1901 err = long_format_binary(obj, base, 1, &str, NULL);
1902 if (err == -1)
1903 return NULL;
1904 return str;
1905}
1906
1907int
1908_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1909 PyObject *obj,
1910 int base, int alternate)
1911{
1912 if (base == 10)
1913 return long_to_decimal_string_internal(obj, NULL, writer);
1914 else
1915 return long_format_binary(obj, base, alternate, NULL, writer);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001916}
1917
Thomas Wouters477c8d52006-05-27 19:21:47 +00001918/* Table of digit values for 8-bit string -> integer conversion.
1919 * '0' maps to 0, ..., '9' maps to 9.
1920 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1921 * All other indices map to 37.
1922 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001923 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001924 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001925unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1927 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 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1930 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1931 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1932 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1933 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1934 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1935 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1936 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1937 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1938 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1939 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
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,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001942};
1943
1944/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00001945 * 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 +03001946 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00001947 * The point to this routine is that it takes time linear in the number of
1948 * string characters.
1949 */
1950static PyLongObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03001951long_from_binary_base(const char **str, int base)
Tim Petersbf2674b2003-02-02 07:51:32 +00001952{
Serhiy Storchakac6792272013-10-19 21:03:34 +03001953 const char *p = *str;
1954 const char *start = p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 int bits_per_char;
1956 Py_ssize_t n;
1957 PyLongObject *z;
1958 twodigits accum;
1959 int bits_in_accum;
1960 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
1963 n = base;
1964 for (bits_per_char = -1; n; ++bits_per_char)
1965 n >>= 1;
1966 /* n <- total # of bits needed, while setting p to end-of-string */
1967 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
1968 ++p;
1969 *str = p;
1970 /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
1971 n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
1972 if (n / bits_per_char < p - start) {
1973 PyErr_SetString(PyExc_ValueError,
1974 "int string too large to convert");
1975 return NULL;
1976 }
1977 n = n / PyLong_SHIFT;
1978 z = _PyLong_New(n);
1979 if (z == NULL)
1980 return NULL;
Serhiy Storchaka95949422013-08-27 19:40:23 +03001981 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 * from least to most significant in both.
1983 */
1984 accum = 0;
1985 bits_in_accum = 0;
1986 pdigit = z->ob_digit;
1987 while (--p >= start) {
1988 int k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
1989 assert(k >= 0 && k < base);
1990 accum |= (twodigits)k << bits_in_accum;
1991 bits_in_accum += bits_per_char;
1992 if (bits_in_accum >= PyLong_SHIFT) {
1993 *pdigit++ = (digit)(accum & PyLong_MASK);
1994 assert(pdigit - z->ob_digit <= n);
1995 accum >>= PyLong_SHIFT;
1996 bits_in_accum -= PyLong_SHIFT;
1997 assert(bits_in_accum < PyLong_SHIFT);
1998 }
1999 }
2000 if (bits_in_accum) {
2001 assert(bits_in_accum <= PyLong_SHIFT);
2002 *pdigit++ = (digit)accum;
2003 assert(pdigit - z->ob_digit <= n);
2004 }
2005 while (pdigit - z->ob_digit < n)
2006 *pdigit++ = 0;
2007 return long_normalize(z);
Tim Petersbf2674b2003-02-02 07:51:32 +00002008}
2009
Serhiy Storchaka95949422013-08-27 19:40:23 +03002010/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002011 * ignored.
2012 *
2013 * If successful, a PyLong object will be returned and 'pend' will be pointing
2014 * to the first unused byte unless it's NULL.
2015 *
2016 * If unsuccessful, NULL will be returned.
2017 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002018PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002019PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002022 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 PyLongObject *z = NULL;
2024 PyObject *strobj;
2025 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if ((base != 0 && base < 2) || base > 36) {
2028 PyErr_SetString(PyExc_ValueError,
2029 "int() arg 2 must be >= 2 and <= 36");
2030 return NULL;
2031 }
Antoine Pitrou4de74572013-02-09 23:11:27 +01002032 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 str++;
2034 if (*str == '+')
2035 ++str;
2036 else if (*str == '-') {
2037 ++str;
2038 sign = -1;
2039 }
2040 if (base == 0) {
2041 if (str[0] != '0')
2042 base = 10;
2043 else if (str[1] == 'x' || str[1] == 'X')
2044 base = 16;
2045 else if (str[1] == 'o' || str[1] == 'O')
2046 base = 8;
2047 else if (str[1] == 'b' || str[1] == 'B')
2048 base = 2;
2049 else {
2050 /* "old" (C-style) octal literal, now invalid.
2051 it might still be zero though */
2052 error_if_nonzero = 1;
2053 base = 10;
2054 }
2055 }
2056 if (str[0] == '0' &&
2057 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2058 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
2059 (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
2060 str += 2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 start = str;
2063 if ((base & (base - 1)) == 0)
2064 z = long_from_binary_base(&str, base);
2065 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002066/***
2067Binary bases can be converted in time linear in the number of digits, because
2068Python's representation base is binary. Other bases (including decimal!) use
2069the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002070
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071First some math: the largest integer that can be expressed in N base-B digits
2072is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2073case number of Python digits needed to hold it is the smallest integer n s.t.
2074
2075 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2076 BASE**n >= B**N [taking logs to base BASE]
2077 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2078
2079The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002080this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002081and the result is computed into it.
2082
2083The input string is actually treated as being in base base**i (i.e., i digits
2084are processed at a time), where two more static arrays hold:
2085
2086 convwidth_base[base] = the largest integer i such that base**i <= BASE
2087 convmultmax_base[base] = base ** convwidth_base[base]
2088
2089The first of these is the largest i such that i consecutive input digits
2090must fit in a single Python digit. The second is effectively the input
2091base we're really using.
2092
2093Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2094convmultmax_base[base], the result is "simply"
2095
2096 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2097
2098where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002099
2100Error analysis: as above, the number of Python digits `n` needed is worst-
2101case
2102
2103 n >= N * log(B)/log(BASE)
2104
2105where `N` is the number of input digits in base `B`. This is computed via
2106
2107 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2108
2109below. Two numeric concerns are how much space this can waste, and whether
2110the computed result can be too small. To be concrete, assume BASE = 2**15,
2111which is the default (and it's unlikely anyone changes that).
2112
2113Waste isn't a problem: provided the first input digit isn't 0, the difference
2114between the worst-case input with N digits and the smallest input with N
2115digits is about a factor of B, but B is small compared to BASE so at most
2116one allocated Python digit can remain unused on that count. If
2117N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2118and adding 1 returns a result 1 larger than necessary. However, that can't
2119happen: whenever B is a power of 2, long_from_binary_base() is called
2120instead, and it's impossible for B**i to be an integer power of 2**15 when
2121B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2122an exact integer when B is not a power of 2, since B**i has a prime factor
2123other than 2 in that case, but (2**15)**j's only prime factor is 2).
2124
2125The computed result can be too small if the true value of N*log(B)/log(BASE)
2126is a little bit larger than an exact integer, but due to roundoff errors (in
2127computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2128yields a numeric result a little less than that integer. Unfortunately, "how
2129close can a transcendental function get to an integer over some range?"
2130questions are generally theoretically intractable. Computer analysis via
2131continued fractions is practical: expand log(B)/log(BASE) via continued
2132fractions, giving a sequence i/j of "the best" rational approximations. Then
2133j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2134we can get very close to being in trouble, but very rarely. For example,
213576573 is a denominator in one of the continued-fraction approximations to
2136log(10)/log(2**15), and indeed:
2137
2138 >>> log(10)/log(2**15)*76573
2139 16958.000000654003
2140
2141is very close to an integer. If we were working with IEEE single-precision,
2142rounding errors could kill us. Finding worst cases in IEEE double-precision
2143requires better-than-double-precision log() functions, and Tim didn't bother.
2144Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002145new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002146This should happen extremely rarely, and in fact I don't have a test case
2147that triggers it(!). Instead the code was tested by artificially allocating
2148just 1 digit at the start, so that the copying code was exercised for every
2149digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002150***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002151 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 Py_ssize_t size_z;
2153 int i;
2154 int convwidth;
2155 twodigits convmultmax, convmult;
2156 digit *pz, *pzstop;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002157 const char* scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 static double log_base_BASE[37] = {0.0e0,};
2160 static int convwidth_base[37] = {0,};
2161 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (log_base_BASE[base] == 0.0) {
2164 twodigits convmax = base;
2165 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002166
Mark Dickinson22b20182010-05-10 21:27:53 +00002167 log_base_BASE[base] = (log((double)base) /
2168 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 for (;;) {
2170 twodigits next = convmax * base;
2171 if (next > PyLong_BASE)
2172 break;
2173 convmax = next;
2174 ++i;
2175 }
2176 convmultmax_base[base] = convmax;
2177 assert(i > 0);
2178 convwidth_base[base] = i;
2179 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* Find length of the string of numeric characters. */
2182 scan = str;
2183 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
2184 ++scan;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002185
Serhiy Storchaka95949422013-08-27 19:40:23 +03002186 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 * integer with this base and length. Note that there's no
2188 * need to initialize z->ob_digit -- no slot is read up before
2189 * being stored into.
2190 */
2191 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2192 /* Uncomment next line to test exceedingly rare copy code */
2193 /* size_z = 1; */
2194 assert(size_z > 0);
2195 z = _PyLong_New(size_z);
2196 if (z == NULL)
2197 return NULL;
2198 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* `convwidth` consecutive input digits are treated as a single
2201 * digit in base `convmultmax`.
2202 */
2203 convwidth = convwidth_base[base];
2204 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* Work ;-) */
2207 while (str < scan) {
2208 /* grab up to convwidth digits from the input string */
2209 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
2210 for (i = 1; i < convwidth && str != scan; ++i, ++str) {
2211 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002212 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 assert(c < PyLong_BASE);
2214 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 convmult = convmultmax;
2217 /* Calculate the shift only if we couldn't get
2218 * convwidth digits.
2219 */
2220 if (i != convwidth) {
2221 convmult = base;
2222 for ( ; i > 1; --i)
2223 convmult *= base;
2224 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Multiply z by convmult, and add c. */
2227 pz = z->ob_digit;
2228 pzstop = pz + Py_SIZE(z);
2229 for (; pz < pzstop; ++pz) {
2230 c += (twodigits)*pz * convmult;
2231 *pz = (digit)(c & PyLong_MASK);
2232 c >>= PyLong_SHIFT;
2233 }
2234 /* carry off the current end? */
2235 if (c) {
2236 assert(c < PyLong_BASE);
2237 if (Py_SIZE(z) < size_z) {
2238 *pz = (digit)c;
2239 ++Py_SIZE(z);
2240 }
2241 else {
2242 PyLongObject *tmp;
2243 /* Extremely rare. Get more space. */
2244 assert(Py_SIZE(z) == size_z);
2245 tmp = _PyLong_New(size_z + 1);
2246 if (tmp == NULL) {
2247 Py_DECREF(z);
2248 return NULL;
2249 }
2250 memcpy(tmp->ob_digit,
2251 z->ob_digit,
2252 sizeof(digit) * size_z);
2253 Py_DECREF(z);
2254 z = tmp;
2255 z->ob_digit[size_z] = (digit)c;
2256 ++size_z;
2257 }
2258 }
2259 }
2260 }
2261 if (z == NULL)
2262 return NULL;
2263 if (error_if_nonzero) {
2264 /* reset the base to 0, else the exception message
2265 doesn't make too much sense */
2266 base = 0;
2267 if (Py_SIZE(z) != 0)
2268 goto onError;
2269 /* there might still be other problems, therefore base
2270 remains zero here for the same reason */
2271 }
2272 if (str == start)
2273 goto onError;
2274 if (sign < 0)
2275 Py_SIZE(z) = -(Py_SIZE(z));
Antoine Pitrou4de74572013-02-09 23:11:27 +01002276 while (*str && Py_ISSPACE(Py_CHARMASK(*str)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 str++;
2278 if (*str != '\0')
2279 goto onError;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002281 z = maybe_small_long(z);
2282 if (z == NULL)
2283 return NULL;
2284 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002285 *pend = (char *)str;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002286 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002287
Mark Dickinson22b20182010-05-10 21:27:53 +00002288 onError:
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002289 if (pend != NULL)
Serhiy Storchakac6792272013-10-19 21:03:34 +03002290 *pend = (char *)str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 Py_XDECREF(z);
2292 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2293 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
2294 if (strobj == NULL)
2295 return NULL;
2296 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002297 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 base, strobj);
2299 Py_DECREF(strobj);
2300 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002301}
2302
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002303/* Since PyLong_FromString doesn't have a length parameter,
2304 * check here for possible NULs in the string.
2305 *
2306 * Reports an invalid literal as a bytes object.
2307 */
2308PyObject *
2309_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2310{
2311 PyObject *result, *strobj;
2312 char *end = NULL;
2313
2314 result = PyLong_FromString((char*)s, &end, base);
2315 if (end == NULL || (result != NULL && end == s + len))
2316 return result;
2317 Py_XDECREF(result);
2318 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2319 if (strobj != NULL) {
2320 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002321 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002322 base, strobj);
2323 Py_DECREF(strobj);
2324 }
2325 return NULL;
2326}
2327
Guido van Rossum9e896b32000-04-05 20:11:21 +00002328PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002329PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002330{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002331 PyObject *v, *unicode = PyUnicode_FromUnicode(u, length);
2332 if (unicode == NULL)
2333 return NULL;
2334 v = PyLong_FromUnicodeObject(unicode, base);
2335 Py_DECREF(unicode);
2336 return v;
2337}
2338
2339PyObject *
2340PyLong_FromUnicodeObject(PyObject *u, int base)
2341{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002342 PyObject *result, *asciidig;
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002343 char *buffer, *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002344 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002345
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002346 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002347 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002349 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002350 if (buffer == NULL) {
2351 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002352 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2353 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002355 else {
2356 result = PyLong_FromString(buffer, &end, base);
2357 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2358 Py_DECREF(asciidig);
2359 return result;
2360 }
2361 Py_DECREF(asciidig);
2362 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002363 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002364 PyErr_Format(PyExc_ValueError,
2365 "invalid literal for int() with base %d: %.200R",
2366 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002367 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002368}
2369
Tim Peters9f688bf2000-07-07 15:53:28 +00002370/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002371static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002373static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002374
Serhiy Storchaka95949422013-08-27 19:40:23 +03002375/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002376
Guido van Rossume32e0141992-01-19 16:31:05 +00002377static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002378long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2382 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (size_b == 0) {
2385 PyErr_SetString(PyExc_ZeroDivisionError,
2386 "integer division or modulo by zero");
2387 return -1;
2388 }
2389 if (size_a < size_b ||
2390 (size_a == size_b &&
2391 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2392 /* |a| < |b|. */
2393 *pdiv = (PyLongObject*)PyLong_FromLong(0);
2394 if (*pdiv == NULL)
2395 return -1;
2396 Py_INCREF(a);
2397 *prem = (PyLongObject *) a;
2398 return 0;
2399 }
2400 if (size_b == 1) {
2401 digit rem = 0;
2402 z = divrem1(a, b->ob_digit[0], &rem);
2403 if (z == NULL)
2404 return -1;
2405 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2406 if (*prem == NULL) {
2407 Py_DECREF(z);
2408 return -1;
2409 }
2410 }
2411 else {
2412 z = x_divrem(a, b, prem);
2413 if (z == NULL)
2414 return -1;
2415 }
2416 /* Set the signs.
2417 The quotient z has the sign of a*b;
2418 the remainder r has the sign of a,
2419 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002420 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2421 _PyLong_Negate(&z);
2422 if (z == NULL) {
2423 Py_CLEAR(*prem);
2424 return -1;
2425 }
2426 }
2427 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2428 _PyLong_Negate(prem);
2429 if (*prem == NULL) {
2430 Py_DECREF(z);
2431 Py_CLEAR(*prem);
2432 return -1;
2433 }
2434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 *pdiv = maybe_small_long(z);
2436 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002437}
2438
Serhiy Storchaka95949422013-08-27 19:40:23 +03002439/* Unsigned int division with remainder -- the algorithm. The arguments v1
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002440 and w1 should satisfy 2 <= ABS(Py_SIZE(w1)) <= ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002441
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002442static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002443x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 PyLongObject *v, *w, *a;
2446 Py_ssize_t i, k, size_v, size_w;
2447 int d;
2448 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2449 twodigits vv;
2450 sdigit zhi;
2451 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2454 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2455 handle the special case when the initial estimate q for a quotient
2456 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2457 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 /* allocate space; w will also be used to hold the final remainder */
2460 size_v = ABS(Py_SIZE(v1));
2461 size_w = ABS(Py_SIZE(w1));
2462 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2463 v = _PyLong_New(size_v+1);
2464 if (v == NULL) {
2465 *prem = NULL;
2466 return NULL;
2467 }
2468 w = _PyLong_New(size_w);
2469 if (w == NULL) {
2470 Py_DECREF(v);
2471 *prem = NULL;
2472 return NULL;
2473 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2476 shift v1 left by the same amount. Results go into w and v. */
2477 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2478 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2479 assert(carry == 0);
2480 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2481 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2482 v->ob_digit[size_v] = carry;
2483 size_v++;
2484 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2487 at most (and usually exactly) k = size_v - size_w digits. */
2488 k = size_v - size_w;
2489 assert(k >= 0);
2490 a = _PyLong_New(k);
2491 if (a == NULL) {
2492 Py_DECREF(w);
2493 Py_DECREF(v);
2494 *prem = NULL;
2495 return NULL;
2496 }
2497 v0 = v->ob_digit;
2498 w0 = w->ob_digit;
2499 wm1 = w0[size_w-1];
2500 wm2 = w0[size_w-2];
2501 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2502 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2503 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002506 Py_DECREF(a);
2507 Py_DECREF(w);
2508 Py_DECREF(v);
2509 *prem = NULL;
2510 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002511 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 /* estimate quotient digit q; may overestimate by 1 (rare) */
2514 vtop = vk[size_w];
2515 assert(vtop <= wm1);
2516 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2517 q = (digit)(vv / wm1);
2518 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2519 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2520 | vk[size_w-2])) {
2521 --q;
2522 r += wm1;
2523 if (r >= PyLong_BASE)
2524 break;
2525 }
2526 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2529 zhi = 0;
2530 for (i = 0; i < size_w; ++i) {
2531 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2532 -PyLong_BASE * q <= z < PyLong_BASE */
2533 z = (sdigit)vk[i] + zhi -
2534 (stwodigits)q * (stwodigits)w0[i];
2535 vk[i] = (digit)z & PyLong_MASK;
2536 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002537 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 /* add w back if q was too large (this branch taken rarely) */
2541 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2542 if ((sdigit)vtop + zhi < 0) {
2543 carry = 0;
2544 for (i = 0; i < size_w; ++i) {
2545 carry += vk[i] + w0[i];
2546 vk[i] = carry & PyLong_MASK;
2547 carry >>= PyLong_SHIFT;
2548 }
2549 --q;
2550 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 /* store quotient digit */
2553 assert(q < PyLong_BASE);
2554 *--ak = q;
2555 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 /* unshift remainder; we reuse w to store the result */
2558 carry = v_rshift(w0, v0, size_w, d);
2559 assert(carry==0);
2560 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 *prem = long_normalize(w);
2563 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002564}
2565
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002566/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2567 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2568 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2569 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2570 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2571 -1.0. */
2572
2573/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2574#if DBL_MANT_DIG == 53
2575#define EXP2_DBL_MANT_DIG 9007199254740992.0
2576#else
2577#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2578#endif
2579
2580double
2581_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2584 /* See below for why x_digits is always large enough. */
2585 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2586 double dx;
2587 /* Correction term for round-half-to-even rounding. For a digit x,
2588 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2589 multiple of 4, rounding ties to a multiple of 8. */
2590 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 a_size = ABS(Py_SIZE(a));
2593 if (a_size == 0) {
2594 /* Special case for 0: significand 0.0, exponent 0. */
2595 *e = 0;
2596 return 0.0;
2597 }
2598 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2599 /* The following is an overflow-free version of the check
2600 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2601 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2602 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2603 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002604 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2608 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 Number of digits needed for result: write // for floor division.
2611 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2620 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2623 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2624 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 in both cases.
2631 */
2632 if (a_bits <= DBL_MANT_DIG + 2) {
2633 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2634 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2635 x_size = 0;
2636 while (x_size < shift_digits)
2637 x_digits[x_size++] = 0;
2638 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2639 (int)shift_bits);
2640 x_size += a_size;
2641 x_digits[x_size++] = rem;
2642 }
2643 else {
2644 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2645 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2646 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2647 a_size - shift_digits, (int)shift_bits);
2648 x_size = a_size - shift_digits;
2649 /* For correct rounding below, we need the least significant
2650 bit of x to be 'sticky' for this shift: if any of the bits
2651 shifted out was nonzero, we set the least significant bit
2652 of x. */
2653 if (rem)
2654 x_digits[0] |= 1;
2655 else
2656 while (shift_digits > 0)
2657 if (a->ob_digit[--shift_digits]) {
2658 x_digits[0] |= 1;
2659 break;
2660 }
2661 }
Victor Stinner63941882011-09-29 00:42:28 +02002662 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 /* Round, and convert to double. */
2665 x_digits[0] += half_even_correction[x_digits[0] & 7];
2666 dx = x_digits[--x_size];
2667 while (x_size > 0)
2668 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* Rescale; make correction if result is 1.0. */
2671 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2672 if (dx == 1.0) {
2673 if (a_bits == PY_SSIZE_T_MAX)
2674 goto overflow;
2675 dx = 0.5;
2676 a_bits += 1;
2677 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 *e = a_bits;
2680 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002681
2682 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 /* exponent > PY_SSIZE_T_MAX */
2684 PyErr_SetString(PyExc_OverflowError,
2685 "huge integer: number of bits overflows a Py_ssize_t");
2686 *e = 0;
2687 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002688}
2689
Serhiy Storchaka95949422013-08-27 19:40:23 +03002690/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002691 using the round-half-to-even rule in the case of a tie. */
2692
2693double
2694PyLong_AsDouble(PyObject *v)
2695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_ssize_t exponent;
2697 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002698
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002699 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 PyErr_BadInternalCall();
2701 return -1.0;
2702 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002703 if (!PyLong_Check(v)) {
2704 PyErr_SetString(PyExc_TypeError, "an integer is required");
2705 return -1.0;
2706 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2708 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2709 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002710 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 return -1.0;
2712 }
2713 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002714}
2715
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002716/* Methods */
2717
2718static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002719long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002722}
2723
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002724static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002725long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002729 if (Py_SIZE(a) != Py_SIZE(b)) {
2730 sign = Py_SIZE(a) - Py_SIZE(b);
2731 }
2732 else {
2733 Py_ssize_t i = ABS(Py_SIZE(a));
2734 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2735 ;
2736 if (i < 0)
2737 sign = 0;
2738 else {
2739 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2740 if (Py_SIZE(a) < 0)
2741 sign = -sign;
2742 }
2743 }
2744 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002745}
2746
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002747#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002749
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002750static PyObject *
2751long_richcompare(PyObject *self, PyObject *other, int op)
2752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 int result;
2754 PyObject *v;
2755 CHECK_BINOP(self, other);
2756 if (self == other)
2757 result = 0;
2758 else
2759 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2760 /* Convert the return value to a Boolean */
2761 switch (op) {
2762 case Py_EQ:
2763 v = TEST_COND(result == 0);
2764 break;
2765 case Py_NE:
2766 v = TEST_COND(result != 0);
2767 break;
2768 case Py_LE:
2769 v = TEST_COND(result <= 0);
2770 break;
2771 case Py_GE:
2772 v = TEST_COND(result >= 0);
2773 break;
2774 case Py_LT:
2775 v = TEST_COND(result == -1);
2776 break;
2777 case Py_GT:
2778 v = TEST_COND(result == 1);
2779 break;
2780 default:
2781 PyErr_BadArgument();
2782 return NULL;
2783 }
2784 Py_INCREF(v);
2785 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002786}
2787
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002788static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002789long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002790{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002791 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 Py_ssize_t i;
2793 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 i = Py_SIZE(v);
2796 switch(i) {
2797 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2798 case 0: return 0;
2799 case 1: return v->ob_digit[0];
2800 }
2801 sign = 1;
2802 x = 0;
2803 if (i < 0) {
2804 sign = -1;
2805 i = -(i);
2806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002808 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2809 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2810 _PyHASH_MODULUS.
2811
2812 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2813 amounts to a rotation of the bits of x. To see this, write
2814
2815 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2816
2817 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2818 PyLong_SHIFT bits of x (those that are shifted out of the
2819 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2820 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2821 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2822 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2823 congruent to y modulo _PyHASH_MODULUS. So
2824
2825 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2826
2827 The right-hand side is just the result of rotating the
2828 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
2829 not all _PyHASH_BITS bits of x are 1s, the same is true
2830 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
2831 the reduction of x*2**PyLong_SHIFT modulo
2832 _PyHASH_MODULUS. */
2833 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
2834 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00002836 if (x >= _PyHASH_MODULUS)
2837 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 }
2839 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002840 if (x == (Py_uhash_t)-1)
2841 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002842 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002843}
2844
2845
Serhiy Storchaka95949422013-08-27 19:40:23 +03002846/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002847
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002848static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002849x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2852 PyLongObject *z;
2853 Py_ssize_t i;
2854 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 /* Ensure a is the larger of the two: */
2857 if (size_a < size_b) {
2858 { PyLongObject *temp = a; a = b; b = temp; }
2859 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002860 size_a = size_b;
2861 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 }
2863 z = _PyLong_New(size_a+1);
2864 if (z == NULL)
2865 return NULL;
2866 for (i = 0; i < size_b; ++i) {
2867 carry += a->ob_digit[i] + b->ob_digit[i];
2868 z->ob_digit[i] = carry & PyLong_MASK;
2869 carry >>= PyLong_SHIFT;
2870 }
2871 for (; i < size_a; ++i) {
2872 carry += a->ob_digit[i];
2873 z->ob_digit[i] = carry & PyLong_MASK;
2874 carry >>= PyLong_SHIFT;
2875 }
2876 z->ob_digit[i] = carry;
2877 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002878}
2879
2880/* Subtract the absolute values of two integers. */
2881
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002882static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002883x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
2886 PyLongObject *z;
2887 Py_ssize_t i;
2888 int sign = 1;
2889 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 /* Ensure a is the larger of the two: */
2892 if (size_a < size_b) {
2893 sign = -1;
2894 { PyLongObject *temp = a; a = b; b = temp; }
2895 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00002896 size_a = size_b;
2897 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 }
2899 else if (size_a == size_b) {
2900 /* Find highest digit where a and b differ: */
2901 i = size_a;
2902 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2903 ;
2904 if (i < 0)
2905 return (PyLongObject *)PyLong_FromLong(0);
2906 if (a->ob_digit[i] < b->ob_digit[i]) {
2907 sign = -1;
2908 { PyLongObject *temp = a; a = b; b = temp; }
2909 }
2910 size_a = size_b = i+1;
2911 }
2912 z = _PyLong_New(size_a);
2913 if (z == NULL)
2914 return NULL;
2915 for (i = 0; i < size_b; ++i) {
2916 /* The following assumes unsigned arithmetic
2917 works module 2**N for some N>PyLong_SHIFT. */
2918 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
2919 z->ob_digit[i] = borrow & PyLong_MASK;
2920 borrow >>= PyLong_SHIFT;
2921 borrow &= 1; /* Keep only one sign bit */
2922 }
2923 for (; i < size_a; ++i) {
2924 borrow = a->ob_digit[i] - borrow;
2925 z->ob_digit[i] = borrow & PyLong_MASK;
2926 borrow >>= PyLong_SHIFT;
2927 borrow &= 1; /* Keep only one sign bit */
2928 }
2929 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02002930 if (sign < 0) {
2931 _PyLong_Negate(&z);
2932 if (z == NULL)
2933 return NULL;
2934 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002936}
2937
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002938static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002939long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00002942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2946 PyObject *result = PyLong_FromLong(MEDIUM_VALUE(a) +
2947 MEDIUM_VALUE(b));
2948 return result;
2949 }
2950 if (Py_SIZE(a) < 0) {
2951 if (Py_SIZE(b) < 0) {
2952 z = x_add(a, b);
2953 if (z != NULL && Py_SIZE(z) != 0)
2954 Py_SIZE(z) = -(Py_SIZE(z));
2955 }
2956 else
2957 z = x_sub(b, a);
2958 }
2959 else {
2960 if (Py_SIZE(b) < 0)
2961 z = x_sub(a, b);
2962 else
2963 z = x_add(a, b);
2964 }
2965 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002966}
2967
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002968static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00002969long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00002970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00002974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
2976 PyObject* r;
2977 r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
2978 return r;
2979 }
2980 if (Py_SIZE(a) < 0) {
2981 if (Py_SIZE(b) < 0)
2982 z = x_sub(a, b);
2983 else
2984 z = x_add(a, b);
2985 if (z != NULL && Py_SIZE(z) != 0)
2986 Py_SIZE(z) = -(Py_SIZE(z));
2987 }
2988 else {
2989 if (Py_SIZE(b) < 0)
2990 z = x_add(a, b);
2991 else
2992 z = x_sub(a, b);
2993 }
2994 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002995}
2996
Tim Peters5af4e6c2002-08-12 02:31:19 +00002997/* Grade school multiplication, ignoring the signs.
2998 * Returns the absolute value of the product, or NULL if error.
2999 */
3000static PyLongObject *
3001x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003003 PyLongObject *z;
3004 Py_ssize_t size_a = ABS(Py_SIZE(a));
3005 Py_ssize_t size_b = ABS(Py_SIZE(b));
3006 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 z = _PyLong_New(size_a + size_b);
3009 if (z == NULL)
3010 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3013 if (a == b) {
3014 /* Efficient squaring per HAC, Algorithm 14.16:
3015 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3016 * Gives slightly less than a 2x speedup when a == b,
3017 * via exploiting that each entry in the multiplication
3018 * pyramid appears twice (except for the size_a squares).
3019 */
3020 for (i = 0; i < size_a; ++i) {
3021 twodigits carry;
3022 twodigits f = a->ob_digit[i];
3023 digit *pz = z->ob_digit + (i << 1);
3024 digit *pa = a->ob_digit + i + 1;
3025 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003028 Py_DECREF(z);
3029 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003030 });
Tim Peters0973b992004-08-29 22:16:50 +00003031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 carry = *pz + f * f;
3033 *pz++ = (digit)(carry & PyLong_MASK);
3034 carry >>= PyLong_SHIFT;
3035 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 /* Now f is added in twice in each column of the
3038 * pyramid it appears. Same as adding f<<1 once.
3039 */
3040 f <<= 1;
3041 while (pa < paend) {
3042 carry += *pz + *pa++ * f;
3043 *pz++ = (digit)(carry & PyLong_MASK);
3044 carry >>= PyLong_SHIFT;
3045 assert(carry <= (PyLong_MASK << 1));
3046 }
3047 if (carry) {
3048 carry += *pz;
3049 *pz++ = (digit)(carry & PyLong_MASK);
3050 carry >>= PyLong_SHIFT;
3051 }
3052 if (carry)
3053 *pz += (digit)(carry & PyLong_MASK);
3054 assert((carry >> PyLong_SHIFT) == 0);
3055 }
3056 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003057 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 for (i = 0; i < size_a; ++i) {
3059 twodigits carry = 0;
3060 twodigits f = a->ob_digit[i];
3061 digit *pz = z->ob_digit + i;
3062 digit *pb = b->ob_digit;
3063 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003066 Py_DECREF(z);
3067 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003068 });
Tim Peters0973b992004-08-29 22:16:50 +00003069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 while (pb < pbend) {
3071 carry += *pz + *pb++ * f;
3072 *pz++ = (digit)(carry & PyLong_MASK);
3073 carry >>= PyLong_SHIFT;
3074 assert(carry <= PyLong_MASK);
3075 }
3076 if (carry)
3077 *pz += (digit)(carry & PyLong_MASK);
3078 assert((carry >> PyLong_SHIFT) == 0);
3079 }
3080 }
3081 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003082}
3083
3084/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003085 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003086 split, and sets low and high such that abs(n) == (high << size) + low,
3087 viewing the shift as being by digits. The sign bit is ignored, and
3088 the return values are >= 0.
3089 Returns 0 on success, -1 on failure.
3090*/
3091static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003092kmul_split(PyLongObject *n,
3093 Py_ssize_t size,
3094 PyLongObject **high,
3095 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 PyLongObject *hi, *lo;
3098 Py_ssize_t size_lo, size_hi;
3099 const Py_ssize_t size_n = ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003100
Victor Stinner640c35c2013-06-04 23:14:37 +02003101 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 if ((hi = _PyLong_New(size_hi)) == NULL)
3105 return -1;
3106 if ((lo = _PyLong_New(size_lo)) == NULL) {
3107 Py_DECREF(hi);
3108 return -1;
3109 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3112 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 *high = long_normalize(hi);
3115 *low = long_normalize(lo);
3116 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003117}
3118
Tim Peters60004642002-08-12 22:01:34 +00003119static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3120
Tim Peters5af4e6c2002-08-12 02:31:19 +00003121/* Karatsuba multiplication. Ignores the input signs, and returns the
3122 * absolute value of the product (or NULL if error).
3123 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3124 */
3125static PyLongObject *
3126k_mul(PyLongObject *a, PyLongObject *b)
3127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 Py_ssize_t asize = ABS(Py_SIZE(a));
3129 Py_ssize_t bsize = ABS(Py_SIZE(b));
3130 PyLongObject *ah = NULL;
3131 PyLongObject *al = NULL;
3132 PyLongObject *bh = NULL;
3133 PyLongObject *bl = NULL;
3134 PyLongObject *ret = NULL;
3135 PyLongObject *t1, *t2, *t3;
3136 Py_ssize_t shift; /* the number of digits we split off */
3137 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3140 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3141 * Then the original product is
3142 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3143 * By picking X to be a power of 2, "*X" is just shifting, and it's
3144 * been reduced to 3 multiplies on numbers half the size.
3145 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 /* We want to split based on the larger number; fiddle so that b
3148 * is largest.
3149 */
3150 if (asize > bsize) {
3151 t1 = a;
3152 a = b;
3153 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 i = asize;
3156 asize = bsize;
3157 bsize = i;
3158 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 /* Use gradeschool math when either number is too small. */
3161 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3162 if (asize <= i) {
3163 if (asize == 0)
3164 return (PyLongObject *)PyLong_FromLong(0);
3165 else
3166 return x_mul(a, b);
3167 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 /* If a is small compared to b, splitting on b gives a degenerate
3170 * case with ah==0, and Karatsuba may be (even much) less efficient
3171 * than "grade school" then. However, we can still win, by viewing
3172 * b as a string of "big digits", each of width a->ob_size. That
3173 * leads to a sequence of balanced calls to k_mul.
3174 */
3175 if (2 * asize <= bsize)
3176 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 /* Split a & b into hi & lo pieces. */
3179 shift = bsize >> 1;
3180 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3181 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 if (a == b) {
3184 bh = ah;
3185 bl = al;
3186 Py_INCREF(bh);
3187 Py_INCREF(bl);
3188 }
3189 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 /* The plan:
3192 * 1. Allocate result space (asize + bsize digits: that's always
3193 * enough).
3194 * 2. Compute ah*bh, and copy into result at 2*shift.
3195 * 3. Compute al*bl, and copy into result at 0. Note that this
3196 * can't overlap with #2.
3197 * 4. Subtract al*bl from the result, starting at shift. This may
3198 * underflow (borrow out of the high digit), but we don't care:
3199 * we're effectively doing unsigned arithmetic mod
3200 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3201 * borrows and carries out of the high digit can be ignored.
3202 * 5. Subtract ah*bh from the result, starting at shift.
3203 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3204 * at shift.
3205 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 /* 1. Allocate result space. */
3208 ret = _PyLong_New(asize + bsize);
3209 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003210#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 /* Fill with trash, to catch reference to uninitialized digits. */
3212 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003213#endif
Tim Peters44121a62002-08-12 06:17:58 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3216 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3217 assert(Py_SIZE(t1) >= 0);
3218 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3219 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3220 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 /* Zero-out the digits higher than the ah*bh copy. */
3223 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3224 if (i)
3225 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3226 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 /* 3. t2 <- al*bl, and copy into the low digits. */
3229 if ((t2 = k_mul(al, bl)) == NULL) {
3230 Py_DECREF(t1);
3231 goto fail;
3232 }
3233 assert(Py_SIZE(t2) >= 0);
3234 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3235 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 /* Zero out remaining digits. */
3238 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3239 if (i)
3240 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3243 * because it's fresher in cache.
3244 */
3245 i = Py_SIZE(ret) - shift; /* # digits after shift */
3246 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3247 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3250 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3253 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3254 Py_DECREF(ah);
3255 Py_DECREF(al);
3256 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 if (a == b) {
3259 t2 = t1;
3260 Py_INCREF(t2);
3261 }
3262 else if ((t2 = x_add(bh, bl)) == NULL) {
3263 Py_DECREF(t1);
3264 goto fail;
3265 }
3266 Py_DECREF(bh);
3267 Py_DECREF(bl);
3268 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 t3 = k_mul(t1, t2);
3271 Py_DECREF(t1);
3272 Py_DECREF(t2);
3273 if (t3 == NULL) goto fail;
3274 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 /* Add t3. It's not obvious why we can't run out of room here.
3277 * See the (*) comment after this function.
3278 */
3279 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3280 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003283
Mark Dickinson22b20182010-05-10 21:27:53 +00003284 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 Py_XDECREF(ret);
3286 Py_XDECREF(ah);
3287 Py_XDECREF(al);
3288 Py_XDECREF(bh);
3289 Py_XDECREF(bl);
3290 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003291}
3292
Tim Petersd6974a52002-08-13 20:37:51 +00003293/* (*) Why adding t3 can't "run out of room" above.
3294
Tim Petersab86c2b2002-08-15 20:06:00 +00003295Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3296to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003297
Tim Petersab86c2b2002-08-15 20:06:00 +000032981. For any integer i, i = c(i/2) + f(i/2). In particular,
3299 bsize = c(bsize/2) + f(bsize/2).
33002. shift = f(bsize/2)
33013. asize <= bsize
33024. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3303 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003304
Tim Petersab86c2b2002-08-15 20:06:00 +00003305We allocated asize + bsize result digits, and add t3 into them at an offset
3306of shift. This leaves asize+bsize-shift allocated digit positions for t3
3307to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3308asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003309
Tim Petersab86c2b2002-08-15 20:06:00 +00003310bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3311at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003312
Tim Petersab86c2b2002-08-15 20:06:00 +00003313If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3314digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3315most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003316
Tim Petersab86c2b2002-08-15 20:06:00 +00003317The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003318
Tim Petersab86c2b2002-08-15 20:06:00 +00003319 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003320
Tim Petersab86c2b2002-08-15 20:06:00 +00003321and we have asize + c(bsize/2) available digit positions. We need to show
3322this is always enough. An instance of c(bsize/2) cancels out in both, so
3323the question reduces to whether asize digits is enough to hold
3324(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3325then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3326asize 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 +00003327digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003328asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003329c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3330is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3331bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003332
Tim Peters48d52c02002-08-14 17:07:32 +00003333Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3334clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3335ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003336*/
3337
Tim Peters60004642002-08-12 22:01:34 +00003338/* b has at least twice the digits of a, and a is big enough that Karatsuba
3339 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3340 * of slices, each with a->ob_size digits, and multiply the slices by a,
3341 * one at a time. This gives k_mul balanced inputs to work with, and is
3342 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003343 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003344 * single-width slice overlap between successive partial sums).
3345 */
3346static PyLongObject *
3347k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 const Py_ssize_t asize = ABS(Py_SIZE(a));
3350 Py_ssize_t bsize = ABS(Py_SIZE(b));
3351 Py_ssize_t nbdone; /* # of b digits already multiplied */
3352 PyLongObject *ret;
3353 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 assert(asize > KARATSUBA_CUTOFF);
3356 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 /* Allocate result space, and zero it out. */
3359 ret = _PyLong_New(asize + bsize);
3360 if (ret == NULL)
3361 return NULL;
3362 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* Successive slices of b are copied into bslice. */
3365 bslice = _PyLong_New(asize);
3366 if (bslice == NULL)
3367 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 nbdone = 0;
3370 while (bsize > 0) {
3371 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003372 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 /* Multiply the next slice of b by a. */
3375 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3376 nbtouse * sizeof(digit));
3377 Py_SIZE(bslice) = nbtouse;
3378 product = k_mul(a, bslice);
3379 if (product == NULL)
3380 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 /* Add into result. */
3383 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3384 product->ob_digit, Py_SIZE(product));
3385 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 bsize -= nbtouse;
3388 nbdone += nbtouse;
3389 }
Tim Peters60004642002-08-12 22:01:34 +00003390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003391 Py_DECREF(bslice);
3392 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003393
Mark Dickinson22b20182010-05-10 21:27:53 +00003394 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 Py_DECREF(ret);
3396 Py_XDECREF(bslice);
3397 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003398}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003399
3400static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003401long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 /* fast path for single-digit multiplication */
3408 if (ABS(Py_SIZE(a)) <= 1 && ABS(Py_SIZE(b)) <= 1) {
3409 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003410#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 return PyLong_FromLongLong((PY_LONG_LONG)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003412#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 /* if we don't have long long then we're almost certainly
3414 using 15-bit digits, so v will fit in a long. In the
3415 unlikely event that we're using 30-bit digits on a platform
3416 without long long, a large v will just cause us to fall
3417 through to the general multiplication code below. */
3418 if (v >= LONG_MIN && v <= LONG_MAX)
3419 return PyLong_FromLong((long)v);
Mark Dickinsonbd792642009-03-18 20:06:12 +00003420#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 z = k_mul(a, b);
3424 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003425 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3426 _PyLong_Negate(&z);
3427 if (z == NULL)
3428 return NULL;
3429 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003431}
3432
Guido van Rossume32e0141992-01-19 16:31:05 +00003433/* The / and % operators are now defined in terms of divmod().
3434 The expression a mod b has the value a - b*floor(a/b).
3435 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003436 |a| by |b|, with the sign of a. This is also expressed
3437 as a - b*trunc(a/b), if trunc truncates towards zero.
3438 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 a b a rem b a mod b
3440 13 10 3 3
3441 -13 10 -3 7
3442 13 -10 3 -7
3443 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003444 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003445 have different signs. We then subtract one from the 'div'
3446 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003447
Tim Peters47e52ee2004-08-30 02:44:38 +00003448/* Compute
3449 * *pdiv, *pmod = divmod(v, w)
3450 * NULL can be passed for pdiv or pmod, in which case that part of
3451 * the result is simply thrown away. The caller owns a reference to
3452 * each of these it requests (does not pass NULL for).
3453 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003454static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003455l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 if (long_divrem(v, w, &div, &mod) < 0)
3461 return -1;
3462 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3463 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3464 PyLongObject *temp;
3465 PyLongObject *one;
3466 temp = (PyLongObject *) long_add(mod, w);
3467 Py_DECREF(mod);
3468 mod = temp;
3469 if (mod == NULL) {
3470 Py_DECREF(div);
3471 return -1;
3472 }
3473 one = (PyLongObject *) PyLong_FromLong(1L);
3474 if (one == NULL ||
3475 (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
3476 Py_DECREF(mod);
3477 Py_DECREF(div);
3478 Py_XDECREF(one);
3479 return -1;
3480 }
3481 Py_DECREF(one);
3482 Py_DECREF(div);
3483 div = temp;
3484 }
3485 if (pdiv != NULL)
3486 *pdiv = div;
3487 else
3488 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003490 if (pmod != NULL)
3491 *pmod = mod;
3492 else
3493 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003496}
3497
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003498static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003499long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 CHECK_BINOP(a, b);
3504 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3505 div = NULL;
3506 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003507}
3508
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003509/* PyLong/PyLong -> float, with correctly rounded result. */
3510
3511#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3512#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3513
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003514static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003515long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003517 PyLongObject *a, *b, *x;
3518 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3519 digit mask, low;
3520 int inexact, negate, a_is_small, b_is_small;
3521 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 CHECK_BINOP(v, w);
3524 a = (PyLongObject *)v;
3525 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003527 /*
3528 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3531 1. choose a suitable integer 'shift'
3532 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3533 3. adjust x for correct rounding
3534 4. convert x to a double dx with the same value
3535 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3540 returns either 0.0 or -0.0, depending on the sign of b. For a and
3541 b both nonzero, ignore signs of a and b, and add the sign back in
3542 at the end. Now write a_bits and b_bits for the bit lengths of a
3543 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3544 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003546 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003548 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3549 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3550 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3551 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 1. The integer 'shift' is chosen so that x has the right number of
3556 bits for a double, plus two or three extra bits that will be used
3557 in the rounding decisions. Writing a_bits and b_bits for the
3558 number of significant bits in a and b respectively, a
3559 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 This is fine in the usual case, but if a/b is smaller than the
3564 smallest normal float then it can lead to double rounding on an
3565 IEEE 754 platform, giving incorrectly rounded results. So we
3566 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003570 2. The quantity x is computed by first shifting a (left -shift bits
3571 if shift <= 0, right shift bits if shift > 0) and then dividing by
3572 b. For both the shift and the division, we keep track of whether
3573 the result is inexact, in a flag 'inexact'; this information is
3574 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 With the choice of shift above, together with our assumption that
3577 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3578 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3581 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 For float representability, we need x/2**extra_bits <
3586 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3587 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003589 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 To round, we just modify the bottom digit of x in-place; this can
3592 end up giving a digit with value > PyLONG_MASK, but that's not a
3593 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 With the original choices for shift above, extra_bits will always
3596 be 2 or 3. Then rounding under the round-half-to-even rule, we
3597 round up iff the most significant of the extra bits is 1, and
3598 either: (a) the computation of x in step 2 had an inexact result,
3599 or (b) at least one other of the extra bits is 1, or (c) the least
3600 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 4. Conversion to a double is straightforward; all floating-point
3603 operations involved in the conversion are exact, so there's no
3604 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3607 The result will always be exactly representable as a double, except
3608 in the case that it overflows. To avoid dependence on the exact
3609 behaviour of ldexp on overflow, we check for overflow before
3610 applying ldexp. The result of ldexp is adjusted for sign before
3611 returning.
3612 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 /* Reduce to case where a and b are both positive. */
3615 a_size = ABS(Py_SIZE(a));
3616 b_size = ABS(Py_SIZE(b));
3617 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3618 if (b_size == 0) {
3619 PyErr_SetString(PyExc_ZeroDivisionError,
3620 "division by zero");
3621 goto error;
3622 }
3623 if (a_size == 0)
3624 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 /* Fast path for a and b small (exactly representable in a double).
3627 Relies on floating-point division being correctly rounded; results
3628 may be subject to double rounding on x86 machines that operate with
3629 the x87 FPU set to 64-bit precision. */
3630 a_is_small = a_size <= MANT_DIG_DIGITS ||
3631 (a_size == MANT_DIG_DIGITS+1 &&
3632 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3633 b_is_small = b_size <= MANT_DIG_DIGITS ||
3634 (b_size == MANT_DIG_DIGITS+1 &&
3635 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3636 if (a_is_small && b_is_small) {
3637 double da, db;
3638 da = a->ob_digit[--a_size];
3639 while (a_size > 0)
3640 da = da * PyLong_BASE + a->ob_digit[--a_size];
3641 db = b->ob_digit[--b_size];
3642 while (b_size > 0)
3643 db = db * PyLong_BASE + b->ob_digit[--b_size];
3644 result = da / db;
3645 goto success;
3646 }
Tim Peterse2a60002001-09-04 06:17:36 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 /* Catch obvious cases of underflow and overflow */
3649 diff = a_size - b_size;
3650 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3651 /* Extreme overflow */
3652 goto overflow;
3653 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3654 /* Extreme underflow */
3655 goto underflow_or_zero;
3656 /* Next line is now safe from overflowing a Py_ssize_t */
3657 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3658 bits_in_digit(b->ob_digit[b_size - 1]);
3659 /* Now diff = a_bits - b_bits. */
3660 if (diff > DBL_MAX_EXP)
3661 goto overflow;
3662 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3663 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003666 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003668 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003670 /* x = abs(a * 2**-shift) */
3671 if (shift <= 0) {
3672 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3673 digit rem;
3674 /* x = a << -shift */
3675 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3676 /* In practice, it's probably impossible to end up
3677 here. Both a and b would have to be enormous,
3678 using close to SIZE_T_MAX bytes of memory each. */
3679 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003680 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003681 goto error;
3682 }
3683 x = _PyLong_New(a_size + shift_digits + 1);
3684 if (x == NULL)
3685 goto error;
3686 for (i = 0; i < shift_digits; i++)
3687 x->ob_digit[i] = 0;
3688 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3689 a_size, -shift % PyLong_SHIFT);
3690 x->ob_digit[a_size + shift_digits] = rem;
3691 }
3692 else {
3693 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3694 digit rem;
3695 /* x = a >> shift */
3696 assert(a_size >= shift_digits);
3697 x = _PyLong_New(a_size - shift_digits);
3698 if (x == NULL)
3699 goto error;
3700 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3701 a_size - shift_digits, shift % PyLong_SHIFT);
3702 /* set inexact if any of the bits shifted out is nonzero */
3703 if (rem)
3704 inexact = 1;
3705 while (!inexact && shift_digits > 0)
3706 if (a->ob_digit[--shift_digits])
3707 inexact = 1;
3708 }
3709 long_normalize(x);
3710 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003712 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3713 reference to x, so it's safe to modify it in-place. */
3714 if (b_size == 1) {
3715 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3716 b->ob_digit[0]);
3717 long_normalize(x);
3718 if (rem)
3719 inexact = 1;
3720 }
3721 else {
3722 PyLongObject *div, *rem;
3723 div = x_divrem(x, b, &rem);
3724 Py_DECREF(x);
3725 x = div;
3726 if (x == NULL)
3727 goto error;
3728 if (Py_SIZE(rem))
3729 inexact = 1;
3730 Py_DECREF(rem);
3731 }
3732 x_size = ABS(Py_SIZE(x));
3733 assert(x_size > 0); /* result of division is never zero */
3734 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003737 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003740 /* Round by directly modifying the low digit of x. */
3741 mask = (digit)1 << (extra_bits - 1);
3742 low = x->ob_digit[0] | inexact;
3743 if (low & mask && low & (3*mask-1))
3744 low += mask;
3745 x->ob_digit[0] = low & ~(mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003747 /* Convert x to a double dx; the conversion is exact. */
3748 dx = x->ob_digit[--x_size];
3749 while (x_size > 0)
3750 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3751 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003753 /* Check whether ldexp result will overflow a double. */
3754 if (shift + x_bits >= DBL_MAX_EXP &&
3755 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3756 goto overflow;
3757 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003758
3759 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003760 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003761
3762 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003763 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003764
3765 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 PyErr_SetString(PyExc_OverflowError,
3767 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003768 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003769 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00003770}
3771
3772static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003773long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003775 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 CHECK_BINOP(a, b);
3778
3779 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
3780 mod = NULL;
3781 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00003782}
3783
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003784static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003785long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 PyLongObject *div, *mod;
3788 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003792 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
3793 return NULL;
3794 }
3795 z = PyTuple_New(2);
3796 if (z != NULL) {
3797 PyTuple_SetItem(z, 0, (PyObject *) div);
3798 PyTuple_SetItem(z, 1, (PyObject *) mod);
3799 }
3800 else {
3801 Py_DECREF(div);
3802 Py_DECREF(mod);
3803 }
3804 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003805}
3806
Tim Peters47e52ee2004-08-30 02:44:38 +00003807/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003808static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00003809long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
3812 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 PyLongObject *z = NULL; /* accumulated result */
3815 Py_ssize_t i, j, k; /* counters */
3816 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00003817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003818 /* 5-ary values. If the exponent is large enough, table is
3819 * precomputed so that table[i] == a**i % c for i in range(32).
3820 */
3821 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
3822 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00003823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003824 /* a, b, c = v, w, x */
3825 CHECK_BINOP(v, w);
3826 a = (PyLongObject*)v; Py_INCREF(a);
3827 b = (PyLongObject*)w; Py_INCREF(b);
3828 if (PyLong_Check(x)) {
3829 c = (PyLongObject *)x;
3830 Py_INCREF(x);
3831 }
3832 else if (x == Py_None)
3833 c = NULL;
3834 else {
3835 Py_DECREF(a);
3836 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05003837 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003838 }
Tim Peters4c483c42001-09-05 06:24:58 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 if (Py_SIZE(b) < 0) { /* if exponent is negative */
3841 if (c) {
3842 PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00003843 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003844 goto Error;
3845 }
3846 else {
3847 /* else return a float. This works because we know
3848 that this calls float_pow() which converts its
3849 arguments to double. */
3850 Py_DECREF(a);
3851 Py_DECREF(b);
3852 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
3853 }
3854 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003856 if (c) {
3857 /* if modulus == 0:
3858 raise ValueError() */
3859 if (Py_SIZE(c) == 0) {
3860 PyErr_SetString(PyExc_ValueError,
3861 "pow() 3rd argument cannot be 0");
3862 goto Error;
3863 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003865 /* if modulus < 0:
3866 negativeOutput = True
3867 modulus = -modulus */
3868 if (Py_SIZE(c) < 0) {
3869 negativeOutput = 1;
3870 temp = (PyLongObject *)_PyLong_Copy(c);
3871 if (temp == NULL)
3872 goto Error;
3873 Py_DECREF(c);
3874 c = temp;
3875 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02003876 _PyLong_Negate(&c);
3877 if (c == NULL)
3878 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003879 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003881 /* if modulus == 1:
3882 return 0 */
3883 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
3884 z = (PyLongObject *)PyLong_FromLong(0L);
3885 goto Done;
3886 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003887
Tim Peters81a93152013-10-05 16:53:52 -05003888 /* Reduce base by modulus in some cases:
3889 1. If base < 0. Forcing the base non-negative makes things easier.
3890 2. If base is obviously larger than the modulus. The "small
3891 exponent" case later can multiply directly by base repeatedly,
3892 while the "large exponent" case multiplies directly by base 31
3893 times. It can be unboundedly faster to multiply by
3894 base % modulus instead.
3895 We could _always_ do this reduction, but l_divmod() isn't cheap,
3896 so we only do it when it buys something. */
3897 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003898 if (l_divmod(a, c, NULL, &temp) < 0)
3899 goto Error;
3900 Py_DECREF(a);
3901 a = temp;
3902 temp = NULL;
3903 }
3904 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 /* At this point a, b, and c are guaranteed non-negative UNLESS
3907 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00003908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003909 z = (PyLongObject *)PyLong_FromLong(1L);
3910 if (z == NULL)
3911 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00003912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003913 /* Perform a modular reduction, X = X % c, but leave X alone if c
3914 * is NULL.
3915 */
3916#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003917 do { \
3918 if (c != NULL) { \
3919 if (l_divmod(X, c, NULL, &temp) < 0) \
3920 goto Error; \
3921 Py_XDECREF(X); \
3922 X = temp; \
3923 temp = NULL; \
3924 } \
3925 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 /* Multiply two values, then reduce the result:
3928 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003929#define MULT(X, Y, result) \
3930 do { \
3931 temp = (PyLongObject *)long_mul(X, Y); \
3932 if (temp == NULL) \
3933 goto Error; \
3934 Py_XDECREF(result); \
3935 result = temp; \
3936 temp = NULL; \
3937 REDUCE(result); \
3938 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00003939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
3941 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
3942 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
3943 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3944 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003947 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003949 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 }
3951 }
3952 }
3953 else {
3954 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
3955 Py_INCREF(z); /* still holds 1L */
3956 table[0] = z;
3957 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003958 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00003959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
3961 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00003962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003963 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
3964 const int index = (bi >> j) & 0x1f;
3965 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003966 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003968 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 }
3970 }
3971 }
Tim Peters47e52ee2004-08-30 02:44:38 +00003972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003973 if (negativeOutput && (Py_SIZE(z) != 0)) {
3974 temp = (PyLongObject *)long_sub(z, c);
3975 if (temp == NULL)
3976 goto Error;
3977 Py_DECREF(z);
3978 z = temp;
3979 temp = NULL;
3980 }
3981 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00003982
Mark Dickinson22b20182010-05-10 21:27:53 +00003983 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02003984 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003985 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00003986 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
3988 for (i = 0; i < 32; ++i)
3989 Py_XDECREF(table[i]);
3990 }
3991 Py_DECREF(a);
3992 Py_DECREF(b);
3993 Py_XDECREF(c);
3994 Py_XDECREF(temp);
3995 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003996}
3997
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003998static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003999long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004001 /* Implement ~x as -(x+1) */
4002 PyLongObject *x;
4003 PyLongObject *w;
4004 if (ABS(Py_SIZE(v)) <=1)
4005 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
4006 w = (PyLongObject *)PyLong_FromLong(1L);
4007 if (w == NULL)
4008 return NULL;
4009 x = (PyLongObject *) long_add(v, w);
4010 Py_DECREF(w);
4011 if (x == NULL)
4012 return NULL;
4013 Py_SIZE(x) = -(Py_SIZE(x));
4014 return (PyObject *)maybe_small_long(x);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004015}
4016
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004017static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004018long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004020 PyLongObject *z;
4021 if (ABS(Py_SIZE(v)) <= 1)
4022 return PyLong_FromLong(-MEDIUM_VALUE(v));
4023 z = (PyLongObject *)_PyLong_Copy(v);
4024 if (z != NULL)
4025 Py_SIZE(z) = -(Py_SIZE(v));
4026 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004027}
4028
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004029static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004030long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004032 if (Py_SIZE(v) < 0)
4033 return long_neg(v);
4034 else
4035 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004036}
4037
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004038static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004039long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004041 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004042}
4043
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004044static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004045long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004047 PyLongObject *z = NULL;
4048 Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
4049 digit lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004051 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004053 if (Py_SIZE(a) < 0) {
4054 /* Right shifting negative numbers is harder */
4055 PyLongObject *a1, *a2;
4056 a1 = (PyLongObject *) long_invert(a);
4057 if (a1 == NULL)
4058 goto rshift_error;
4059 a2 = (PyLongObject *) long_rshift(a1, b);
4060 Py_DECREF(a1);
4061 if (a2 == NULL)
4062 goto rshift_error;
4063 z = (PyLongObject *) long_invert(a2);
4064 Py_DECREF(a2);
4065 }
4066 else {
4067 shiftby = PyLong_AsSsize_t((PyObject *)b);
4068 if (shiftby == -1L && PyErr_Occurred())
4069 goto rshift_error;
4070 if (shiftby < 0) {
4071 PyErr_SetString(PyExc_ValueError,
4072 "negative shift count");
4073 goto rshift_error;
4074 }
4075 wordshift = shiftby / PyLong_SHIFT;
4076 newsize = ABS(Py_SIZE(a)) - wordshift;
4077 if (newsize <= 0)
4078 return PyLong_FromLong(0);
4079 loshift = shiftby % PyLong_SHIFT;
4080 hishift = PyLong_SHIFT - loshift;
4081 lomask = ((digit)1 << hishift) - 1;
4082 himask = PyLong_MASK ^ lomask;
4083 z = _PyLong_New(newsize);
4084 if (z == NULL)
4085 goto rshift_error;
4086 if (Py_SIZE(a) < 0)
4087 Py_SIZE(z) = -(Py_SIZE(z));
4088 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4089 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4090 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004091 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004092 }
4093 z = long_normalize(z);
4094 }
Mark Dickinson22b20182010-05-10 21:27:53 +00004095 rshift_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 return (PyObject *) maybe_small_long(z);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004097
Guido van Rossumc6913e71991-11-19 20:26:46 +00004098}
4099
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004100static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004101long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 /* This version due to Tim Peters */
4104 PyLongObject *a = (PyLongObject*)v;
4105 PyLongObject *b = (PyLongObject*)w;
4106 PyLongObject *z = NULL;
4107 Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
4108 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004110 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004112 shiftby = PyLong_AsSsize_t((PyObject *)b);
4113 if (shiftby == -1L && PyErr_Occurred())
Victor Stinner8aed6f12013-07-17 22:31:17 +02004114 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004115 if (shiftby < 0) {
4116 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004117 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004118 }
4119 /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4120 wordshift = shiftby / PyLong_SHIFT;
4121 remshift = shiftby - wordshift * PyLong_SHIFT;
Guido van Rossumf2e499b1997-03-16 00:37:59 +00004122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004123 oldsize = ABS(Py_SIZE(a));
4124 newsize = oldsize + wordshift;
4125 if (remshift)
4126 ++newsize;
4127 z = _PyLong_New(newsize);
4128 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004129 return NULL;
4130 if (Py_SIZE(a) < 0) {
4131 assert(Py_REFCNT(z) == 1);
4132 Py_SIZE(z) = -Py_SIZE(z);
4133 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004134 for (i = 0; i < wordshift; i++)
4135 z->ob_digit[i] = 0;
4136 accum = 0;
4137 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4138 accum |= (twodigits)a->ob_digit[j] << remshift;
4139 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4140 accum >>= PyLong_SHIFT;
4141 }
4142 if (remshift)
4143 z->ob_digit[newsize-1] = (digit)accum;
4144 else
4145 assert(!accum);
4146 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004148}
4149
Mark Dickinson27a87a22009-10-25 20:43:34 +00004150/* Compute two's complement of digit vector a[0:m], writing result to
4151 z[0:m]. The digit vector a need not be normalized, but should not
4152 be entirely zero. a and z may point to the same digit vector. */
4153
4154static void
4155v_complement(digit *z, digit *a, Py_ssize_t m)
4156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 Py_ssize_t i;
4158 digit carry = 1;
4159 for (i = 0; i < m; ++i) {
4160 carry += a[i] ^ PyLong_MASK;
4161 z[i] = carry & PyLong_MASK;
4162 carry >>= PyLong_SHIFT;
4163 }
4164 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004165}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004166
4167/* Bitwise and/xor/or operations */
4168
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004169static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004170long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004171 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004172 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004174 int nega, negb, negz;
4175 Py_ssize_t size_a, size_b, size_z, i;
4176 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 /* Bitwise operations for negative numbers operate as though
4179 on a two's complement representation. So convert arguments
4180 from sign-magnitude to two's complement, and convert the
4181 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004183 /* If a is negative, replace it by its two's complement. */
4184 size_a = ABS(Py_SIZE(a));
4185 nega = Py_SIZE(a) < 0;
4186 if (nega) {
4187 z = _PyLong_New(size_a);
4188 if (z == NULL)
4189 return NULL;
4190 v_complement(z->ob_digit, a->ob_digit, size_a);
4191 a = z;
4192 }
4193 else
4194 /* Keep reference count consistent. */
4195 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004197 /* Same for b. */
4198 size_b = ABS(Py_SIZE(b));
4199 negb = Py_SIZE(b) < 0;
4200 if (negb) {
4201 z = _PyLong_New(size_b);
4202 if (z == NULL) {
4203 Py_DECREF(a);
4204 return NULL;
4205 }
4206 v_complement(z->ob_digit, b->ob_digit, size_b);
4207 b = z;
4208 }
4209 else
4210 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004212 /* Swap a and b if necessary to ensure size_a >= size_b. */
4213 if (size_a < size_b) {
4214 z = a; a = b; b = z;
4215 size_z = size_a; size_a = size_b; size_b = size_z;
4216 negz = nega; nega = negb; negb = negz;
4217 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004219 /* JRH: The original logic here was to allocate the result value (z)
4220 as the longer of the two operands. However, there are some cases
4221 where the result is guaranteed to be shorter than that: AND of two
4222 positives, OR of two negatives: use the shorter number. AND with
4223 mixed signs: use the positive number. OR with mixed signs: use the
4224 negative number.
4225 */
4226 switch (op) {
4227 case '^':
4228 negz = nega ^ negb;
4229 size_z = size_a;
4230 break;
4231 case '&':
4232 negz = nega & negb;
4233 size_z = negb ? size_a : size_b;
4234 break;
4235 case '|':
4236 negz = nega | negb;
4237 size_z = negb ? size_b : size_a;
4238 break;
4239 default:
4240 PyErr_BadArgument();
4241 return NULL;
4242 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 /* We allow an extra digit if z is negative, to make sure that
4245 the final two's complement of z doesn't overflow. */
4246 z = _PyLong_New(size_z + negz);
4247 if (z == NULL) {
4248 Py_DECREF(a);
4249 Py_DECREF(b);
4250 return NULL;
4251 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004253 /* Compute digits for overlap of a and b. */
4254 switch(op) {
4255 case '&':
4256 for (i = 0; i < size_b; ++i)
4257 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4258 break;
4259 case '|':
4260 for (i = 0; i < size_b; ++i)
4261 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4262 break;
4263 case '^':
4264 for (i = 0; i < size_b; ++i)
4265 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4266 break;
4267 default:
4268 PyErr_BadArgument();
4269 return NULL;
4270 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004272 /* Copy any remaining digits of a, inverting if necessary. */
4273 if (op == '^' && negb)
4274 for (; i < size_z; ++i)
4275 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4276 else if (i < size_z)
4277 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4278 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004280 /* Complement result if negative. */
4281 if (negz) {
4282 Py_SIZE(z) = -(Py_SIZE(z));
4283 z->ob_digit[size_z] = PyLong_MASK;
4284 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4285 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004287 Py_DECREF(a);
4288 Py_DECREF(b);
4289 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004290}
4291
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004292static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004293long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004295 PyObject *c;
4296 CHECK_BINOP(a, b);
4297 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4298 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004299}
4300
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004301static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004302long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004304 PyObject *c;
4305 CHECK_BINOP(a, b);
4306 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4307 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004308}
4309
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004310static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004311long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004313 PyObject *c;
4314 CHECK_BINOP(a, b);
4315 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4316 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004317}
4318
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004319static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004320long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004322 if (PyLong_CheckExact(v))
4323 Py_INCREF(v);
4324 else
4325 v = _PyLong_Copy((PyLongObject *)v);
4326 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004327}
4328
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004329static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004330long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004332 double result;
4333 result = PyLong_AsDouble(v);
4334 if (result == -1.0 && PyErr_Occurred())
4335 return NULL;
4336 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004337}
4338
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004339static PyObject *
Guido van Rossumbef14172001-08-29 15:47:46 +00004340long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004341
Tim Peters6d6c1a32001-08-02 04:15:00 +00004342static PyObject *
4343long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4344{
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004345 PyObject *obase = NULL, *x = NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004346 Py_ssize_t base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004347 static char *kwlist[] = {"x", "base", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00004348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004349 if (type != &PyLong_Type)
4350 return long_subtype_new(type, args, kwds); /* Wimp out */
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004351 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:int", kwlist,
4352 &x, &obase))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004353 return NULL;
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004354 if (x == NULL) {
4355 if (obase != NULL) {
4356 PyErr_SetString(PyExc_TypeError,
4357 "int() missing string argument");
4358 return NULL;
4359 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004361 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004362 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004364
Gregory P. Smitha689e522012-12-25 22:38:32 -08004365 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004366 if (base == -1 && PyErr_Occurred())
4367 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004368 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004369 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004370 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004371 return NULL;
4372 }
4373
4374 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004375 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004377 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 if (PyByteArray_Check(x))
4379 string = PyByteArray_AS_STRING(x);
4380 else
4381 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004382 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 }
4384 else {
4385 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004386 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004387 return NULL;
4388 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004389}
4390
Serhiy Storchaka95949422013-08-27 19:40:23 +03004391/* Wimpy, slow approach to tp_new calls for subtypes of int:
4392 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004393 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004394 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004395*/
4396static PyObject *
4397long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
4398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 PyLongObject *tmp, *newobj;
4400 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004402 assert(PyType_IsSubtype(type, &PyLong_Type));
4403 tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
4404 if (tmp == NULL)
4405 return NULL;
4406 assert(PyLong_CheckExact(tmp));
4407 n = Py_SIZE(tmp);
4408 if (n < 0)
4409 n = -n;
4410 newobj = (PyLongObject *)type->tp_alloc(type, n);
4411 if (newobj == NULL) {
4412 Py_DECREF(tmp);
4413 return NULL;
4414 }
4415 assert(PyLong_Check(newobj));
4416 Py_SIZE(newobj) = Py_SIZE(tmp);
4417 for (i = 0; i < n; i++)
4418 newobj->ob_digit[i] = tmp->ob_digit[i];
4419 Py_DECREF(tmp);
4420 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004421}
4422
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004423static PyObject *
4424long_getnewargs(PyLongObject *v)
4425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 return Py_BuildValue("(N)", _PyLong_Copy(v));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004427}
4428
Guido van Rossumb43daf72007-08-01 18:08:08 +00004429static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004430long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004432}
4433
4434static PyObject *
4435long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004437}
4438
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004439static PyObject *
Eric Smith8c663262007-08-25 02:26:07 +00004440long__format__(PyObject *self, PyObject *args)
4441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 PyObject *format_spec;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004443 _PyUnicodeWriter writer;
4444 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
4447 return NULL;
Victor Stinnerd3f08822012-05-29 12:57:52 +02004448
Victor Stinner8f674cc2013-04-17 23:02:17 +02004449 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004450 ret = _PyLong_FormatAdvancedWriter(
4451 &writer,
4452 self,
4453 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4454 if (ret == -1) {
4455 _PyUnicodeWriter_Dealloc(&writer);
4456 return NULL;
4457 }
4458 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004459}
4460
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004461/* Return a pair (q, r) such that a = b * q + r, and
4462 abs(r) <= abs(b)/2, with equality possible only if q is even.
4463 In other words, q == a / b, rounded to the nearest integer using
4464 round-half-to-even. */
4465
4466PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004467_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004468{
4469 PyLongObject *quo = NULL, *rem = NULL;
4470 PyObject *one = NULL, *twice_rem, *result, *temp;
4471 int cmp, quo_is_odd, quo_is_neg;
4472
4473 /* Equivalent Python code:
4474
4475 def divmod_near(a, b):
4476 q, r = divmod(a, b)
4477 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4478 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4479 # positive, 2 * r < b if b negative.
4480 greater_than_half = 2*r > b if b > 0 else 2*r < b
4481 exactly_half = 2*r == b
4482 if greater_than_half or exactly_half and q % 2 == 1:
4483 q += 1
4484 r -= b
4485 return q, r
4486
4487 */
4488 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4489 PyErr_SetString(PyExc_TypeError,
4490 "non-integer arguments in division");
4491 return NULL;
4492 }
4493
4494 /* Do a and b have different signs? If so, quotient is negative. */
4495 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4496
4497 one = PyLong_FromLong(1L);
4498 if (one == NULL)
4499 return NULL;
4500
4501 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4502 goto error;
4503
4504 /* compare twice the remainder with the divisor, to see
4505 if we need to adjust the quotient and remainder */
4506 twice_rem = long_lshift((PyObject *)rem, one);
4507 if (twice_rem == NULL)
4508 goto error;
4509 if (quo_is_neg) {
4510 temp = long_neg((PyLongObject*)twice_rem);
4511 Py_DECREF(twice_rem);
4512 twice_rem = temp;
4513 if (twice_rem == NULL)
4514 goto error;
4515 }
4516 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4517 Py_DECREF(twice_rem);
4518
4519 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4520 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4521 /* fix up quotient */
4522 if (quo_is_neg)
4523 temp = long_sub(quo, (PyLongObject *)one);
4524 else
4525 temp = long_add(quo, (PyLongObject *)one);
4526 Py_DECREF(quo);
4527 quo = (PyLongObject *)temp;
4528 if (quo == NULL)
4529 goto error;
4530 /* and remainder */
4531 if (quo_is_neg)
4532 temp = long_add(rem, (PyLongObject *)b);
4533 else
4534 temp = long_sub(rem, (PyLongObject *)b);
4535 Py_DECREF(rem);
4536 rem = (PyLongObject *)temp;
4537 if (rem == NULL)
4538 goto error;
4539 }
4540
4541 result = PyTuple_New(2);
4542 if (result == NULL)
4543 goto error;
4544
4545 /* PyTuple_SET_ITEM steals references */
4546 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
4547 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
4548 Py_DECREF(one);
4549 return result;
4550
4551 error:
4552 Py_XDECREF(quo);
4553 Py_XDECREF(rem);
4554 Py_XDECREF(one);
4555 return NULL;
4556}
4557
Eric Smith8c663262007-08-25 02:26:07 +00004558static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004559long_round(PyObject *self, PyObject *args)
4560{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004561 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004562
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004563 /* To round an integer m to the nearest 10**n (n positive), we make use of
4564 * the divmod_near operation, defined by:
4565 *
4566 * divmod_near(a, b) = (q, r)
4567 *
4568 * where q is the nearest integer to the quotient a / b (the
4569 * nearest even integer in the case of a tie) and r == a - q * b.
4570 * Hence q * b = a - r is the nearest multiple of b to a,
4571 * preferring even multiples in the case of a tie.
4572 *
4573 * So the nearest multiple of 10**n to m is:
4574 *
4575 * m - divmod_near(m, 10**n)[1].
4576 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004577 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
4578 return NULL;
4579 if (o_ndigits == NULL)
4580 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004581
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004582 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (ndigits == NULL)
4584 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004585
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004586 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 if (Py_SIZE(ndigits) >= 0) {
4588 Py_DECREF(ndigits);
4589 return long_long(self);
4590 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004591
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004592 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
4593 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004595 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004596 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004597 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00004598
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004599 result = PyLong_FromLong(10L);
4600 if (result == NULL) {
4601 Py_DECREF(ndigits);
4602 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004603 }
Mark Dickinson1124e712009-01-28 21:25:58 +00004604
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004605 temp = long_pow(result, ndigits, Py_None);
4606 Py_DECREF(ndigits);
4607 Py_DECREF(result);
4608 result = temp;
4609 if (result == NULL)
4610 return NULL;
4611
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004612 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004613 Py_DECREF(result);
4614 result = temp;
4615 if (result == NULL)
4616 return NULL;
4617
4618 temp = long_sub((PyLongObject *)self,
4619 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
4620 Py_DECREF(result);
4621 result = temp;
4622
4623 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004624}
4625
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004626static PyObject *
4627long_sizeof(PyLongObject *v)
4628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004631 res = offsetof(PyLongObject, ob_digit) + ABS(Py_SIZE(v))*sizeof(digit);
4632 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00004633}
4634
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004635static PyObject *
4636long_bit_length(PyLongObject *v)
4637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 PyLongObject *result, *x, *y;
4639 Py_ssize_t ndigits, msd_bits = 0;
4640 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 assert(v != NULL);
4643 assert(PyLong_Check(v));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 ndigits = ABS(Py_SIZE(v));
4646 if (ndigits == 0)
4647 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 msd = v->ob_digit[ndigits-1];
4650 while (msd >= 32) {
4651 msd_bits += 6;
4652 msd >>= 6;
4653 }
4654 msd_bits += (long)(BitLengthTable[msd]);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
4657 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 /* expression above may overflow; use Python integers instead */
4660 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
4661 if (result == NULL)
4662 return NULL;
4663 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
4664 if (x == NULL)
4665 goto error;
4666 y = (PyLongObject *)long_mul(result, x);
4667 Py_DECREF(x);
4668 if (y == NULL)
4669 goto error;
4670 Py_DECREF(result);
4671 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
4674 if (x == NULL)
4675 goto error;
4676 y = (PyLongObject *)long_add(result, x);
4677 Py_DECREF(x);
4678 if (y == NULL)
4679 goto error;
4680 Py_DECREF(result);
4681 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004684
Mark Dickinson22b20182010-05-10 21:27:53 +00004685 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 Py_DECREF(result);
4687 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00004688}
4689
4690PyDoc_STRVAR(long_bit_length_doc,
4691"int.bit_length() -> int\n\
4692\n\
4693Number of bits necessary to represent self in binary.\n\
4694>>> bin(37)\n\
4695'0b100101'\n\
4696>>> (37).bit_length()\n\
46976");
4698
Christian Heimes53876d92008-04-19 00:31:39 +00004699#if 0
4700static PyObject *
4701long_is_finite(PyObject *v)
4702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00004704}
4705#endif
4706
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004707
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004708static PyObject *
4709long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
4710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 PyObject *byteorder_str;
4712 PyObject *is_signed_obj = NULL;
4713 Py_ssize_t length;
4714 int little_endian;
4715 int is_signed;
4716 PyObject *bytes;
4717 static char *kwlist[] = {"length", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004719 if (!PyArg_ParseTupleAndKeywords(args, kwds, "nU|O:to_bytes", kwlist,
4720 &length, &byteorder_str,
4721 &is_signed_obj))
4722 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 if (args != NULL && Py_SIZE(args) > 2) {
4725 PyErr_SetString(PyExc_TypeError,
4726 "'signed' is a keyword-only argument");
4727 return NULL;
4728 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4731 little_endian = 1;
4732 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4733 little_endian = 0;
4734 else {
4735 PyErr_SetString(PyExc_ValueError,
4736 "byteorder must be either 'little' or 'big'");
4737 return NULL;
4738 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 if (is_signed_obj != NULL) {
4741 int cmp = PyObject_IsTrue(is_signed_obj);
4742 if (cmp < 0)
4743 return NULL;
4744 is_signed = cmp ? 1 : 0;
4745 }
4746 else {
4747 /* If the signed argument was omitted, use False as the
4748 default. */
4749 is_signed = 0;
4750 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 if (length < 0) {
4753 PyErr_SetString(PyExc_ValueError,
4754 "length argument must be non-negative");
4755 return NULL;
4756 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004758 bytes = PyBytes_FromStringAndSize(NULL, length);
4759 if (bytes == NULL)
4760 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 if (_PyLong_AsByteArray(v, (unsigned char *)PyBytes_AS_STRING(bytes),
4763 length, little_endian, is_signed) < 0) {
4764 Py_DECREF(bytes);
4765 return NULL;
4766 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004769}
4770
Mark Dickinson078c2532010-01-30 18:06:17 +00004771PyDoc_STRVAR(long_to_bytes_doc,
4772"int.to_bytes(length, byteorder, *, signed=False) -> bytes\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004773\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004774Return an array of bytes representing an integer.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004775\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776The integer is represented using length bytes. An OverflowError is\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004777raised if the integer is not representable with the given number of\n\
4778bytes.\n\
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004779\n\
4780The byteorder argument determines the byte order used to represent the\n\
4781integer. If byteorder is 'big', the most significant byte is at the\n\
4782beginning of the byte array. If byteorder is 'little', the most\n\
4783significant byte is at the end of the byte array. To request the native\n\
4784byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4785\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004786The signed keyword-only argument determines whether two's complement is\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787used to represent the integer. If signed is False and a negative integer\n\
Mark Dickinson078c2532010-01-30 18:06:17 +00004788is given, an OverflowError is raised.");
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004789
4790static PyObject *
4791long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
4792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 PyObject *byteorder_str;
4794 PyObject *is_signed_obj = NULL;
4795 int little_endian;
4796 int is_signed;
4797 PyObject *obj;
4798 PyObject *bytes;
4799 PyObject *long_obj;
4800 static char *kwlist[] = {"bytes", "byteorder", "signed", NULL};
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004802 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OU|O:from_bytes", kwlist,
4803 &obj, &byteorder_str,
4804 &is_signed_obj))
4805 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004807 if (args != NULL && Py_SIZE(args) > 2) {
4808 PyErr_SetString(PyExc_TypeError,
4809 "'signed' is a keyword-only argument");
4810 return NULL;
4811 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813 if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
4814 little_endian = 1;
4815 else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
4816 little_endian = 0;
4817 else {
4818 PyErr_SetString(PyExc_ValueError,
4819 "byteorder must be either 'little' or 'big'");
4820 return NULL;
4821 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004823 if (is_signed_obj != NULL) {
4824 int cmp = PyObject_IsTrue(is_signed_obj);
4825 if (cmp < 0)
4826 return NULL;
4827 is_signed = cmp ? 1 : 0;
4828 }
4829 else {
4830 /* If the signed argument was omitted, use False as the
4831 default. */
4832 is_signed = 0;
4833 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004835 bytes = PyObject_Bytes(obj);
4836 if (bytes == NULL)
4837 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004839 long_obj = _PyLong_FromByteArray(
4840 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
4841 little_endian, is_signed);
4842 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 /* If from_bytes() was used on subclass, allocate new subclass
Serhiy Storchaka95949422013-08-27 19:40:23 +03004845 * instance, initialize it with decoded int value and return it.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004846 */
4847 if (type != &PyLong_Type && PyType_IsSubtype(type, &PyLong_Type)) {
4848 PyLongObject *newobj;
4849 int i;
4850 Py_ssize_t n = ABS(Py_SIZE(long_obj));
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 newobj = (PyLongObject *)type->tp_alloc(type, n);
4853 if (newobj == NULL) {
4854 Py_DECREF(long_obj);
4855 return NULL;
4856 }
4857 assert(PyLong_Check(newobj));
4858 Py_SIZE(newobj) = Py_SIZE(long_obj);
4859 for (i = 0; i < n; i++) {
4860 newobj->ob_digit[i] =
4861 ((PyLongObject *)long_obj)->ob_digit[i];
4862 }
4863 Py_DECREF(long_obj);
4864 return (PyObject *)newobj;
4865 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004867 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00004868}
4869
Mark Dickinson078c2532010-01-30 18:06:17 +00004870PyDoc_STRVAR(long_from_bytes_doc,
4871"int.from_bytes(bytes, byteorder, *, signed=False) -> int\n\
4872\n\
4873Return the integer represented by the given array of bytes.\n\
4874\n\
4875The bytes argument must either support the buffer protocol or be an\n\
4876iterable object producing bytes. Bytes and bytearray are examples of\n\
4877built-in objects that support the buffer protocol.\n\
4878\n\
4879The byteorder argument determines the byte order used to represent the\n\
4880integer. If byteorder is 'big', the most significant byte is at the\n\
4881beginning of the byte array. If byteorder is 'little', the most\n\
4882significant byte is at the end of the byte array. To request the native\n\
4883byte order of the host system, use `sys.byteorder' as the byte order value.\n\
4884\n\
4885The signed keyword-only argument indicates whether two's complement is\n\
4886used to represent the integer.");
4887
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004888static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004889 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
4890 "Returns self, the complex conjugate of any int."},
4891 {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
4892 long_bit_length_doc},
Christian Heimes53876d92008-04-19 00:31:39 +00004893#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004894 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
4895 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00004896#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004897 {"to_bytes", (PyCFunction)long_to_bytes,
4898 METH_VARARGS|METH_KEYWORDS, long_to_bytes_doc},
4899 {"from_bytes", (PyCFunction)long_from_bytes,
4900 METH_VARARGS|METH_KEYWORDS|METH_CLASS, long_from_bytes_doc},
4901 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
4902 "Truncating an Integral returns itself."},
4903 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
4904 "Flooring an Integral returns itself."},
4905 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
4906 "Ceiling of an Integral returns itself."},
4907 {"__round__", (PyCFunction)long_round, METH_VARARGS,
4908 "Rounding an Integral returns itself.\n"
4909 "Rounding with an ndigits argument also returns an integer."},
4910 {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
4911 {"__format__", (PyCFunction)long__format__, METH_VARARGS},
4912 {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
4913 "Returns size in memory, in bytes"},
4914 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004915};
4916
Guido van Rossumb43daf72007-08-01 18:08:08 +00004917static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00004918 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004919 (getter)long_long, (setter)NULL,
4920 "the real part of a complex number",
4921 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004922 {"imag",
4923 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004924 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004925 NULL},
4926 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00004927 (getter)long_long, (setter)NULL,
4928 "the numerator of a rational number in lowest terms",
4929 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00004930 {"denominator",
4931 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00004932 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00004933 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00004934 {NULL} /* Sentinel */
4935};
4936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004937PyDoc_STRVAR(long_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004938"int(x=0) -> integer\n\
4939int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00004940\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07004941Convert a number or string to an integer, or return 0 if no arguments\n\
4942are given. If x is a number, return x.__int__(). For floating point\n\
4943numbers, this truncates towards zero.\n\
4944\n\
4945If x is not a number or if base is given, then x must be a string,\n\
4946bytes, or bytearray instance representing an integer literal in the\n\
4947given base. The literal can be preceded by '+' or '-' and be surrounded\n\
4948by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
4949Base 0 means to interpret the base from the string as an integer literal.\n\
4950>>> int('0b100', base=0)\n\
49514");
Tim Peters6d6c1a32001-08-02 04:15:00 +00004952
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004953static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00004954 (binaryfunc)long_add, /*nb_add*/
4955 (binaryfunc)long_sub, /*nb_subtract*/
4956 (binaryfunc)long_mul, /*nb_multiply*/
4957 long_mod, /*nb_remainder*/
4958 long_divmod, /*nb_divmod*/
4959 long_pow, /*nb_power*/
4960 (unaryfunc)long_neg, /*nb_negative*/
4961 (unaryfunc)long_long, /*tp_positive*/
4962 (unaryfunc)long_abs, /*tp_absolute*/
4963 (inquiry)long_bool, /*tp_bool*/
4964 (unaryfunc)long_invert, /*nb_invert*/
4965 long_lshift, /*nb_lshift*/
4966 (binaryfunc)long_rshift, /*nb_rshift*/
4967 long_and, /*nb_and*/
4968 long_xor, /*nb_xor*/
4969 long_or, /*nb_or*/
4970 long_long, /*nb_int*/
4971 0, /*nb_reserved*/
4972 long_float, /*nb_float*/
4973 0, /* nb_inplace_add */
4974 0, /* nb_inplace_subtract */
4975 0, /* nb_inplace_multiply */
4976 0, /* nb_inplace_remainder */
4977 0, /* nb_inplace_power */
4978 0, /* nb_inplace_lshift */
4979 0, /* nb_inplace_rshift */
4980 0, /* nb_inplace_and */
4981 0, /* nb_inplace_xor */
4982 0, /* nb_inplace_or */
4983 long_div, /* nb_floor_divide */
4984 long_true_divide, /* nb_true_divide */
4985 0, /* nb_inplace_floor_divide */
4986 0, /* nb_inplace_true_divide */
4987 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004988};
4989
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004990PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 PyVarObject_HEAD_INIT(&PyType_Type, 0)
4992 "int", /* tp_name */
4993 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
4994 sizeof(digit), /* tp_itemsize */
4995 long_dealloc, /* tp_dealloc */
4996 0, /* tp_print */
4997 0, /* tp_getattr */
4998 0, /* tp_setattr */
4999 0, /* tp_reserved */
5000 long_to_decimal_string, /* tp_repr */
5001 &long_as_number, /* tp_as_number */
5002 0, /* tp_as_sequence */
5003 0, /* tp_as_mapping */
5004 (hashfunc)long_hash, /* tp_hash */
5005 0, /* tp_call */
5006 long_to_decimal_string, /* tp_str */
5007 PyObject_GenericGetAttr, /* tp_getattro */
5008 0, /* tp_setattro */
5009 0, /* tp_as_buffer */
5010 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5011 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5012 long_doc, /* tp_doc */
5013 0, /* tp_traverse */
5014 0, /* tp_clear */
5015 long_richcompare, /* tp_richcompare */
5016 0, /* tp_weaklistoffset */
5017 0, /* tp_iter */
5018 0, /* tp_iternext */
5019 long_methods, /* tp_methods */
5020 0, /* tp_members */
5021 long_getset, /* tp_getset */
5022 0, /* tp_base */
5023 0, /* tp_dict */
5024 0, /* tp_descr_get */
5025 0, /* tp_descr_set */
5026 0, /* tp_dictoffset */
5027 0, /* tp_init */
5028 0, /* tp_alloc */
5029 long_new, /* tp_new */
5030 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005031};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005032
Mark Dickinsonbd792642009-03-18 20:06:12 +00005033static PyTypeObject Int_InfoType;
5034
5035PyDoc_STRVAR(int_info__doc__,
5036"sys.int_info\n\
5037\n\
5038A struct sequence that holds information about Python's\n\
5039internal representation of integers. The attributes are read only.");
5040
5041static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005043 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005045};
5046
5047static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 "sys.int_info", /* name */
5049 int_info__doc__, /* doc */
5050 int_info_fields, /* fields */
5051 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005052};
5053
5054PyObject *
5055PyLong_GetInfo(void)
5056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 PyObject* int_info;
5058 int field = 0;
5059 int_info = PyStructSequence_New(&Int_InfoType);
5060 if (int_info == NULL)
5061 return NULL;
5062 PyStructSequence_SET_ITEM(int_info, field++,
5063 PyLong_FromLong(PyLong_SHIFT));
5064 PyStructSequence_SET_ITEM(int_info, field++,
5065 PyLong_FromLong(sizeof(digit)));
5066 if (PyErr_Occurred()) {
5067 Py_CLEAR(int_info);
5068 return NULL;
5069 }
5070 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005071}
5072
Guido van Rossumddefaf32007-01-14 03:31:43 +00005073int
5074_PyLong_Init(void)
5075{
5076#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005077 int ival, size;
5078 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005080 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5081 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5082 if (Py_TYPE(v) == &PyLong_Type) {
5083 /* The element is already initialized, most likely
5084 * the Python interpreter was initialized before.
5085 */
5086 Py_ssize_t refcnt;
5087 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5090 _Py_NewReference(op);
5091 /* _Py_NewReference sets the ref count to 1 but
5092 * the ref count might be larger. Set the refcnt
5093 * to the original refcnt + 1 */
5094 Py_REFCNT(op) = refcnt + 1;
5095 assert(Py_SIZE(op) == size);
5096 assert(v->ob_digit[0] == abs(ival));
5097 }
5098 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005099 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 }
5101 Py_SIZE(v) = size;
5102 v->ob_digit[0] = abs(ival);
5103 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005104#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005106 if (Int_InfoType.tp_name == NULL) {
5107 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5108 return 0;
5109 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005112}
5113
5114void
5115PyLong_Fini(void)
5116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 /* Integers are currently statically allocated. Py_DECREF is not
5118 needed, but Python must forget about the reference or multiple
5119 reinitializations will fail. */
Guido van Rossumddefaf32007-01-14 03:31:43 +00005120#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 int i;
5122 PyLongObject *v = small_ints;
5123 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5124 _Py_DEC_REFTOTAL;
5125 _Py_ForgetReference((PyObject*)v);
5126 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005127#endif
5128}