blob: c71b783cc03c35a79c60c2453775eaaa9d222597 [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
Serhiy Storchaka495e8802017-02-01 23:12:20 +020012#include "clinic/longobject.c.h"
13/*[clinic input]
14class int "PyObject *" "&PyLong_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
17
Guido van Rossumddefaf32007-01-14 03:31:43 +000018#ifndef NSMALLPOSINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000019#define NSMALLPOSINTS 257
Guido van Rossumddefaf32007-01-14 03:31:43 +000020#endif
21#ifndef NSMALLNEGINTS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022#define NSMALLNEGINTS 5
Guido van Rossumddefaf32007-01-14 03:31:43 +000023#endif
Facundo Batista6e6f59b2008-07-24 18:57:11 +000024
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +020025_Py_IDENTIFIER(little);
26_Py_IDENTIFIER(big);
27
Mark Dickinsone4416742009-02-15 15:14:57 +000028/* convert a PyLong of size 1, 0 or -1 to an sdigit */
Victor Stinner08a80b12013-07-17 22:33:42 +020029#define MEDIUM_VALUE(x) (assert(-1 <= Py_SIZE(x) && Py_SIZE(x) <= 1), \
30 Py_SIZE(x) < 0 ? -(sdigit)(x)->ob_digit[0] : \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 (Py_SIZE(x) == 0 ? (sdigit)0 : \
32 (sdigit)(x)->ob_digit[0]))
Facundo Batista6e6f59b2008-07-24 18:57:11 +000033
Serhiy Storchakaba85d692017-03-30 09:09:41 +030034PyObject *_PyLong_Zero = NULL;
35PyObject *_PyLong_One = NULL;
36
Guido van Rossumddefaf32007-01-14 03:31:43 +000037#if NSMALLNEGINTS + NSMALLPOSINTS > 0
38/* Small integers are preallocated in this array so that they
39 can be shared.
40 The integers that are preallocated are those in the range
41 -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
42*/
43static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
44#ifdef COUNT_ALLOCS
Mark Dickinsonc286e582012-09-20 21:29:28 +010045Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
Guido van Rossumddefaf32007-01-14 03:31:43 +000046#endif
47
Guido van Rossum7eaf8222007-06-18 17:58:50 +000048static PyObject *
Mark Dickinsone4416742009-02-15 15:14:57 +000049get_small_int(sdigit ival)
Guido van Rossumddefaf32007-01-14 03:31:43 +000050{
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050051 PyObject *v;
Benjamin Peterson041c38a2014-03-14 21:47:23 -050052 assert(-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS);
Benjamin Peterson45c9dce2014-03-14 21:53:51 -050053 v = (PyObject *)&small_ints[ival + NSMALLNEGINTS];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000054 Py_INCREF(v);
Guido van Rossumddefaf32007-01-14 03:31:43 +000055#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 if (ival >= 0)
57 quick_int_allocs++;
58 else
59 quick_neg_int_allocs++;
Guido van Rossumddefaf32007-01-14 03:31:43 +000060#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 return v;
Guido van Rossumddefaf32007-01-14 03:31:43 +000062}
63#define CHECK_SMALL_INT(ival) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
65 return get_small_int((sdigit)ival); \
66 } while(0)
Guido van Rossumddefaf32007-01-14 03:31:43 +000067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068static PyLongObject *
Facundo Batista6e6f59b2008-07-24 18:57:11 +000069maybe_small_long(PyLongObject *v)
70{
Victor Stinner45e8e2f2014-05-14 17:24:35 +020071 if (v && Py_ABS(Py_SIZE(v)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 sdigit ival = MEDIUM_VALUE(v);
73 if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
74 Py_DECREF(v);
75 return (PyLongObject *)get_small_int(ival);
76 }
77 }
78 return v;
Facundo Batista6e6f59b2008-07-24 18:57:11 +000079}
Guido van Rossumddefaf32007-01-14 03:31:43 +000080#else
81#define CHECK_SMALL_INT(ival)
Facundo Batista6e6f59b2008-07-24 18:57:11 +000082#define maybe_small_long(val) (val)
Guido van Rossumddefaf32007-01-14 03:31:43 +000083#endif
84
Serhiy Storchaka95949422013-08-27 19:40:23 +030085/* If a freshly-allocated int is already shared, it must
Guido van Rossumddefaf32007-01-14 03:31:43 +000086 be a small integer, so negating it must go to PyLong_FromLong */
Victor Stinner8aed6f12013-07-17 22:31:17 +020087Py_LOCAL_INLINE(void)
88_PyLong_Negate(PyLongObject **x_p)
89{
90 PyLongObject *x;
91
92 x = (PyLongObject *)*x_p;
93 if (Py_REFCNT(x) == 1) {
94 Py_SIZE(x) = -Py_SIZE(x);
95 return;
96 }
97
98 *x_p = (PyLongObject *)PyLong_FromLong(-MEDIUM_VALUE(x));
99 Py_DECREF(x);
100}
101
Serhiy Storchaka95949422013-08-27 19:40:23 +0300102/* For int multiplication, use the O(N**2) school algorithm unless
Tim Peters5af4e6c2002-08-12 02:31:19 +0000103 * both operands contain more than KARATSUBA_CUTOFF digits (this
Serhiy Storchaka95949422013-08-27 19:40:23 +0300104 * being an internal Python int digit, in base BASE).
Tim Peters5af4e6c2002-08-12 02:31:19 +0000105 */
Tim Peters0973b992004-08-29 22:16:50 +0000106#define KARATSUBA_CUTOFF 70
107#define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
Tim Peters5af4e6c2002-08-12 02:31:19 +0000108
Tim Peters47e52ee2004-08-30 02:44:38 +0000109/* For exponentiation, use the binary left-to-right algorithm
110 * unless the exponent contains more than FIVEARY_CUTOFF digits.
111 * In that case, do 5 bits at a time. The potential drawback is that
112 * a table of 2**5 intermediate results is computed.
113 */
114#define FIVEARY_CUTOFF 8
115
Mark Dickinsoncdd01d22010-05-10 21:37:34 +0000116#define SIGCHECK(PyTryBlock) \
117 do { \
118 if (PyErr_CheckSignals()) PyTryBlock \
119 } while(0)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +0000120
Serhiy Storchaka95949422013-08-27 19:40:23 +0300121/* Normalize (remove leading zeros from) an int object.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000122 Doesn't attempt to free the storage--in most cases, due to the nature
123 of the algorithms used, this could save at most be one word anyway. */
124
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125static PyLongObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200126long_normalize(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000127{
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200128 Py_ssize_t j = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 Py_ssize_t i = j;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 while (i > 0 && v->ob_digit[i-1] == 0)
132 --i;
133 if (i != j)
134 Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
135 return v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000136}
137
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200138/* _PyLong_FromNbInt: Convert the given object to a PyLongObject
139 using the nb_int slot, if available. Raise TypeError if either the
140 nb_int slot is not available or the result of the call to nb_int
141 returns something not of type int.
142*/
143PyLongObject *
144_PyLong_FromNbInt(PyObject *integral)
145{
146 PyNumberMethods *nb;
147 PyObject *result;
148
149 /* Fast path for the case that we already have an int. */
150 if (PyLong_CheckExact(integral)) {
151 Py_INCREF(integral);
152 return (PyLongObject *)integral;
153 }
154
155 nb = Py_TYPE(integral)->tp_as_number;
156 if (nb == NULL || nb->nb_int == NULL) {
157 PyErr_Format(PyExc_TypeError,
158 "an integer is required (got type %.200s)",
159 Py_TYPE(integral)->tp_name);
160 return NULL;
161 }
162
163 /* Convert using the nb_int slot, which should return something
164 of exact type int. */
165 result = nb->nb_int(integral);
166 if (!result || PyLong_CheckExact(result))
167 return (PyLongObject *)result;
168 if (!PyLong_Check(result)) {
169 PyErr_Format(PyExc_TypeError,
170 "__int__ returned non-int (type %.200s)",
171 result->ob_type->tp_name);
172 Py_DECREF(result);
173 return NULL;
174 }
175 /* Issue #17576: warn if 'result' not of exact type int. */
176 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
177 "__int__ returned non-int (type %.200s). "
178 "The ability to return an instance of a strict subclass of int "
179 "is deprecated, and may be removed in a future version of Python.",
180 result->ob_type->tp_name)) {
181 Py_DECREF(result);
182 return NULL;
183 }
184 return (PyLongObject *)result;
185}
186
187
Serhiy Storchaka95949422013-08-27 19:40:23 +0300188/* Allocate a new int object with size digits.
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000189 Return NULL and set exception if we run out of memory. */
190
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000191#define MAX_LONG_DIGITS \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
Mark Dickinson5a74bf62009-02-15 11:04:38 +0000193
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000194PyLongObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000195_PyLong_New(Py_ssize_t size)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyLongObject *result;
198 /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
199 sizeof(digit)*size. Previous incarnations of this code used
200 sizeof(PyVarObject) instead of the offsetof, but this risks being
201 incorrect in the presence of padding between the PyVarObject header
202 and the digits. */
203 if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
204 PyErr_SetString(PyExc_OverflowError,
205 "too many digits in integer");
206 return NULL;
207 }
208 result = PyObject_MALLOC(offsetof(PyLongObject, ob_digit) +
209 size*sizeof(digit));
210 if (!result) {
211 PyErr_NoMemory();
212 return NULL;
213 }
214 return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000215}
216
Tim Peters64b5ce32001-09-10 20:52:51 +0000217PyObject *
218_PyLong_Copy(PyLongObject *src)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyLongObject *result;
221 Py_ssize_t i;
Tim Peters64b5ce32001-09-10 20:52:51 +0000222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 assert(src != NULL);
224 i = Py_SIZE(src);
225 if (i < 0)
226 i = -(i);
227 if (i < 2) {
Mark Dickinsonbcc17ee2012-04-20 21:42:49 +0100228 sdigit ival = MEDIUM_VALUE(src);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 CHECK_SMALL_INT(ival);
230 }
231 result = _PyLong_New(i);
232 if (result != NULL) {
233 Py_SIZE(result) = Py_SIZE(src);
234 while (--i >= 0)
235 result->ob_digit[i] = src->ob_digit[i];
236 }
237 return (PyObject *)result;
Tim Peters64b5ce32001-09-10 20:52:51 +0000238}
239
Serhiy Storchaka95949422013-08-27 19:40:23 +0300240/* Create a new int object from a C long int */
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000241
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000242PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000243PyLong_FromLong(long ival)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyLongObject *v;
246 unsigned long abs_ival;
247 unsigned long t; /* unsigned so >> doesn't propagate sign bit */
248 int ndigits = 0;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100249 int sign;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 CHECK_SMALL_INT(ival);
Tim Petersce9de2f2001-06-14 04:56:19 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (ival < 0) {
254 /* negate: can't write this as abs_ival = -ival since that
255 invokes undefined behaviour when ival is LONG_MIN */
256 abs_ival = 0U-(unsigned long)ival;
257 sign = -1;
258 }
259 else {
260 abs_ival = (unsigned long)ival;
Mark Dickinson36820dd2016-09-10 20:17:36 +0100261 sign = ival == 0 ? 0 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 }
Tim Petersce9de2f2001-06-14 04:56:19 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* Fast path for single-digit ints */
265 if (!(abs_ival >> PyLong_SHIFT)) {
266 v = _PyLong_New(1);
267 if (v) {
268 Py_SIZE(v) = sign;
269 v->ob_digit[0] = Py_SAFE_DOWNCAST(
270 abs_ival, unsigned long, digit);
271 }
272 return (PyObject*)v;
273 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000274
Mark Dickinson249b8982009-04-27 19:41:00 +0000275#if PyLong_SHIFT==15
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* 2 digits */
277 if (!(abs_ival >> 2*PyLong_SHIFT)) {
278 v = _PyLong_New(2);
279 if (v) {
280 Py_SIZE(v) = 2*sign;
281 v->ob_digit[0] = Py_SAFE_DOWNCAST(
282 abs_ival & PyLong_MASK, unsigned long, digit);
283 v->ob_digit[1] = Py_SAFE_DOWNCAST(
284 abs_ival >> PyLong_SHIFT, unsigned long, digit);
285 }
286 return (PyObject*)v;
287 }
Mark Dickinsonbd792642009-03-18 20:06:12 +0000288#endif
Guido van Rossumddefaf32007-01-14 03:31:43 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 /* Larger numbers: loop to determine number of digits */
291 t = abs_ival;
292 while (t) {
293 ++ndigits;
294 t >>= PyLong_SHIFT;
295 }
296 v = _PyLong_New(ndigits);
297 if (v != NULL) {
298 digit *p = v->ob_digit;
299 Py_SIZE(v) = ndigits*sign;
300 t = abs_ival;
301 while (t) {
302 *p++ = Py_SAFE_DOWNCAST(
303 t & PyLong_MASK, unsigned long, digit);
304 t >>= PyLong_SHIFT;
305 }
306 }
307 return (PyObject *)v;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000308}
309
Serhiy Storchaka95949422013-08-27 19:40:23 +0300310/* Create a new int object from a C unsigned long int */
Guido van Rossum53756b11997-01-03 17:14:46 +0000311
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000312PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +0000313PyLong_FromUnsignedLong(unsigned long ival)
Guido van Rossum53756b11997-01-03 17:14:46 +0000314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 PyLongObject *v;
316 unsigned long t;
317 int ndigits = 0;
Tim Petersce9de2f2001-06-14 04:56:19 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 if (ival < PyLong_BASE)
320 return PyLong_FromLong(ival);
321 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +0200322 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 while (t) {
324 ++ndigits;
325 t >>= PyLong_SHIFT;
326 }
327 v = _PyLong_New(ndigits);
328 if (v != NULL) {
329 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 while (ival) {
331 *p++ = (digit)(ival & PyLong_MASK);
332 ival >>= PyLong_SHIFT;
333 }
334 }
335 return (PyObject *)v;
Guido van Rossum53756b11997-01-03 17:14:46 +0000336}
337
Serhiy Storchaka95949422013-08-27 19:40:23 +0300338/* Create a new int object from a C double */
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000339
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340PyObject *
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341PyLong_FromDouble(double dval)
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 PyLongObject *v;
344 double frac;
345 int i, ndig, expo, neg;
346 neg = 0;
347 if (Py_IS_INFINITY(dval)) {
348 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000349 "cannot convert float infinity to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 return NULL;
351 }
352 if (Py_IS_NAN(dval)) {
353 PyErr_SetString(PyExc_ValueError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000354 "cannot convert float NaN to integer");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return NULL;
356 }
357 if (dval < 0.0) {
358 neg = 1;
359 dval = -dval;
360 }
361 frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
362 if (expo <= 0)
363 return PyLong_FromLong(0L);
364 ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
365 v = _PyLong_New(ndig);
366 if (v == NULL)
367 return NULL;
368 frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
369 for (i = ndig; --i >= 0; ) {
370 digit bits = (digit)frac;
371 v->ob_digit[i] = bits;
372 frac = frac - (double)bits;
373 frac = ldexp(frac, PyLong_SHIFT);
374 }
375 if (neg)
376 Py_SIZE(v) = -(Py_SIZE(v));
377 return (PyObject *)v;
Guido van Rossum149e9ea1991-06-03 10:58:24 +0000378}
379
Thomas Wouters89f507f2006-12-13 04:49:30 +0000380/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
381 * anything about what happens when a signed integer operation overflows,
382 * and some compilers think they're doing you a favor by being "clever"
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700383 * then. The bit pattern for the largest positive signed long is
Thomas Wouters89f507f2006-12-13 04:49:30 +0000384 * (unsigned long)LONG_MAX, and for the smallest negative signed long
385 * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
386 * However, some other compilers warn about applying unary minus to an
387 * unsigned operand. Hence the weird "0-".
388 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
390#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000391
Serhiy Storchaka95949422013-08-27 19:40:23 +0300392/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100393 method.
394
395 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
396 the result. Otherwise *overflow is 0.
397
398 For other errors (e.g., TypeError), return -1 and set an error condition.
399 In this case *overflow will be 0.
400*/
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000401
402long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000403PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200406 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 unsigned long x, prev;
408 long res;
409 Py_ssize_t i;
410 int sign;
411 int do_decref = 0; /* if nb_int was called */
Guido van Rossumf7531811998-05-26 14:33:37 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 *overflow = 0;
414 if (vv == NULL) {
415 PyErr_BadInternalCall();
416 return -1;
417 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000418
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200419 if (PyLong_Check(vv)) {
420 v = (PyLongObject *)vv;
421 }
422 else {
423 v = _PyLong_FromNbInt(vv);
424 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 return -1;
426 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 i = Py_SIZE(v);
Guido van Rossumf7531811998-05-26 14:33:37 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 switch (i) {
433 case -1:
434 res = -(sdigit)v->ob_digit[0];
435 break;
436 case 0:
437 res = 0;
438 break;
439 case 1:
440 res = v->ob_digit[0];
441 break;
442 default:
443 sign = 1;
444 x = 0;
445 if (i < 0) {
446 sign = -1;
447 i = -(i);
448 }
449 while (--i >= 0) {
450 prev = x;
451 x = (x << PyLong_SHIFT) | v->ob_digit[i];
452 if ((x >> PyLong_SHIFT) != prev) {
453 *overflow = sign;
454 goto exit;
455 }
456 }
457 /* Haven't lost any bits, but casting to long requires extra
458 * care (see comment above).
459 */
460 if (x <= (unsigned long)LONG_MAX) {
461 res = (long)x * sign;
462 }
463 else if (sign < 0 && x == PY_ABS_LONG_MIN) {
464 res = LONG_MIN;
465 }
466 else {
467 *overflow = sign;
468 /* res is already set to -1 */
469 }
470 }
Mark Dickinson22b20182010-05-10 21:27:53 +0000471 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200473 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 }
475 return res;
Guido van Rossumedcc38a1991-05-05 20:09:44 +0000476}
477
Serhiy Storchaka95949422013-08-27 19:40:23 +0300478/* Get a C long int from an int object or any object that has an __int__
Mark Dickinson8d48b432011-10-23 20:47:14 +0100479 method. Return -1 and set an error if overflow occurs. */
480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481long
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000482PyLong_AsLong(PyObject *obj)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 int overflow;
485 long result = PyLong_AsLongAndOverflow(obj, &overflow);
486 if (overflow) {
487 /* XXX: could be cute and give a different
488 message for overflow == -1 */
489 PyErr_SetString(PyExc_OverflowError,
490 "Python int too large to convert to C long");
491 }
492 return result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +0000493}
494
Serhiy Storchaka95949422013-08-27 19:40:23 +0300495/* Get a C int from an int object or any object that has an __int__
Serhiy Storchaka78980432013-01-15 01:12:17 +0200496 method. Return -1 and set an error if overflow occurs. */
497
498int
499_PyLong_AsInt(PyObject *obj)
500{
501 int overflow;
502 long result = PyLong_AsLongAndOverflow(obj, &overflow);
503 if (overflow || result > INT_MAX || result < INT_MIN) {
504 /* XXX: could be cute and give a different
505 message for overflow == -1 */
506 PyErr_SetString(PyExc_OverflowError,
507 "Python int too large to convert to C int");
508 return -1;
509 }
510 return (int)result;
511}
512
Serhiy Storchaka95949422013-08-27 19:40:23 +0300513/* Get a Py_ssize_t from an int object.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000514 Returns -1 and sets an error condition if overflow occurs. */
515
516Py_ssize_t
Guido van Rossumddefaf32007-01-14 03:31:43 +0000517PyLong_AsSsize_t(PyObject *vv) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200518 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 size_t x, prev;
520 Py_ssize_t i;
521 int sign;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (vv == NULL) {
524 PyErr_BadInternalCall();
525 return -1;
526 }
527 if (!PyLong_Check(vv)) {
528 PyErr_SetString(PyExc_TypeError, "an integer is required");
529 return -1;
530 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 v = (PyLongObject *)vv;
533 i = Py_SIZE(v);
534 switch (i) {
535 case -1: return -(sdigit)v->ob_digit[0];
536 case 0: return 0;
537 case 1: return v->ob_digit[0];
538 }
539 sign = 1;
540 x = 0;
541 if (i < 0) {
542 sign = -1;
543 i = -(i);
544 }
545 while (--i >= 0) {
546 prev = x;
547 x = (x << PyLong_SHIFT) | v->ob_digit[i];
548 if ((x >> PyLong_SHIFT) != prev)
549 goto overflow;
550 }
551 /* Haven't lost any bits, but casting to a signed type requires
552 * extra care (see comment above).
553 */
554 if (x <= (size_t)PY_SSIZE_T_MAX) {
555 return (Py_ssize_t)x * sign;
556 }
557 else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
558 return PY_SSIZE_T_MIN;
559 }
560 /* else overflow */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000561
Mark Dickinson22b20182010-05-10 21:27:53 +0000562 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyErr_SetString(PyExc_OverflowError,
564 "Python int too large to convert to C ssize_t");
565 return -1;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000566}
567
Serhiy Storchaka95949422013-08-27 19:40:23 +0300568/* Get a C unsigned long int from an int object.
Guido van Rossum53756b11997-01-03 17:14:46 +0000569 Returns -1 and sets an error condition if overflow occurs. */
570
571unsigned long
Tim Peters9f688bf2000-07-07 15:53:28 +0000572PyLong_AsUnsignedLong(PyObject *vv)
Guido van Rossum53756b11997-01-03 17:14:46 +0000573{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200574 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 unsigned long x, prev;
576 Py_ssize_t i;
Tim Peters5af4e6c2002-08-12 02:31:19 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (vv == NULL) {
579 PyErr_BadInternalCall();
580 return (unsigned long)-1;
581 }
582 if (!PyLong_Check(vv)) {
583 PyErr_SetString(PyExc_TypeError, "an integer is required");
584 return (unsigned long)-1;
585 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 v = (PyLongObject *)vv;
588 i = Py_SIZE(v);
589 x = 0;
590 if (i < 0) {
591 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000592 "can't convert negative value to unsigned int");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return (unsigned long) -1;
594 }
595 switch (i) {
596 case 0: return 0;
597 case 1: return v->ob_digit[0];
598 }
599 while (--i >= 0) {
600 prev = x;
601 x = (x << PyLong_SHIFT) | v->ob_digit[i];
602 if ((x >> PyLong_SHIFT) != prev) {
603 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +0100604 "Python int too large to convert "
Mark Dickinson22b20182010-05-10 21:27:53 +0000605 "to C unsigned long");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return (unsigned long) -1;
607 }
608 }
609 return x;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000610}
611
Serhiy Storchaka95949422013-08-27 19:40:23 +0300612/* Get a C size_t from an int object. Returns (size_t)-1 and sets
Stefan Krahb77c6c62011-09-12 16:22:47 +0200613 an error condition if overflow occurs. */
Guido van Rossumddefaf32007-01-14 03:31:43 +0000614
615size_t
616PyLong_AsSize_t(PyObject *vv)
617{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200618 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 size_t x, prev;
620 Py_ssize_t i;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (vv == NULL) {
623 PyErr_BadInternalCall();
624 return (size_t) -1;
625 }
626 if (!PyLong_Check(vv)) {
627 PyErr_SetString(PyExc_TypeError, "an integer is required");
628 return (size_t)-1;
629 }
Mark Dickinsond59b4162010-03-13 11:34:40 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 v = (PyLongObject *)vv;
632 i = Py_SIZE(v);
633 x = 0;
634 if (i < 0) {
635 PyErr_SetString(PyExc_OverflowError,
636 "can't convert negative value to size_t");
637 return (size_t) -1;
638 }
639 switch (i) {
640 case 0: return 0;
641 case 1: return v->ob_digit[0];
642 }
643 while (--i >= 0) {
644 prev = x;
645 x = (x << PyLong_SHIFT) | v->ob_digit[i];
646 if ((x >> PyLong_SHIFT) != prev) {
647 PyErr_SetString(PyExc_OverflowError,
648 "Python int too large to convert to C size_t");
Stefan Krahb77c6c62011-09-12 16:22:47 +0200649 return (size_t) -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 }
651 }
652 return x;
Guido van Rossum53756b11997-01-03 17:14:46 +0000653}
654
Serhiy Storchaka95949422013-08-27 19:40:23 +0300655/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +0000656 Returns -1 and sets an error condition if an error occurs. */
657
Guido van Rossumddefaf32007-01-14 03:31:43 +0000658static unsigned long
659_PyLong_AsUnsignedLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +0000660{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200661 PyLongObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 unsigned long x;
663 Py_ssize_t i;
664 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 if (vv == NULL || !PyLong_Check(vv)) {
667 PyErr_BadInternalCall();
668 return (unsigned long) -1;
669 }
670 v = (PyLongObject *)vv;
671 i = Py_SIZE(v);
672 switch (i) {
673 case 0: return 0;
674 case 1: return v->ob_digit[0];
675 }
676 sign = 1;
677 x = 0;
678 if (i < 0) {
679 sign = -1;
680 i = -i;
681 }
682 while (--i >= 0) {
683 x = (x << PyLong_SHIFT) | v->ob_digit[i];
684 }
685 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +0000686}
687
Guido van Rossumddefaf32007-01-14 03:31:43 +0000688unsigned long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200689PyLong_AsUnsignedLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 PyLongObject *lo;
692 unsigned long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000693
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200694 if (op == NULL) {
695 PyErr_BadInternalCall();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return (unsigned long)-1;
697 }
Guido van Rossumddefaf32007-01-14 03:31:43 +0000698
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200699 if (PyLong_Check(op)) {
700 return _PyLong_AsUnsignedLongMask(op);
701 }
702
703 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (lo == NULL)
705 return (unsigned long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +0200706
707 val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
708 Py_DECREF(lo);
709 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000710}
711
Tim Peters5b8132f2003-01-31 15:52:05 +0000712int
713_PyLong_Sign(PyObject *vv)
714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyLongObject *v = (PyLongObject *)vv;
Tim Peters5b8132f2003-01-31 15:52:05 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 assert(v != NULL);
718 assert(PyLong_Check(v));
Tim Peters5b8132f2003-01-31 15:52:05 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
Tim Peters5b8132f2003-01-31 15:52:05 +0000721}
722
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200723/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
724 2**k if d is nonzero, else 0. */
725
726static const unsigned char BitLengthTable[32] = {
727 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
728 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
729};
730
731static int
732bits_in_digit(digit d)
733{
734 int d_bits = 0;
735 while (d >= 32) {
736 d_bits += 6;
737 d >>= 6;
738 }
739 d_bits += (int)BitLengthTable[d];
740 return d_bits;
741}
742
Tim Petersbaefd9e2003-01-28 20:37:45 +0000743size_t
744_PyLong_NumBits(PyObject *vv)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyLongObject *v = (PyLongObject *)vv;
747 size_t result = 0;
748 Py_ssize_t ndigits;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200749 int msd_bits;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 assert(v != NULL);
752 assert(PyLong_Check(v));
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200753 ndigits = Py_ABS(Py_SIZE(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
755 if (ndigits > 0) {
756 digit msd = v->ob_digit[ndigits - 1];
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700757 if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 goto Overflow;
Mark Dickinsonfc9adb62012-10-06 18:50:02 +0100759 result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +0200760 msd_bits = bits_in_digit(msd);
761 if (SIZE_MAX - msd_bits < result)
762 goto Overflow;
763 result += msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 }
765 return result;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000766
Mark Dickinson22b20182010-05-10 21:27:53 +0000767 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 PyErr_SetString(PyExc_OverflowError, "int has too many bits "
769 "to express in a platform size_t");
770 return (size_t)-1;
Tim Petersbaefd9e2003-01-28 20:37:45 +0000771}
772
Tim Peters2a9b3672001-06-11 21:23:58 +0000773PyObject *
774_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000776{
Mark Dickinson22b20182010-05-10 21:27:53 +0000777 const unsigned char* pstartbyte; /* LSB of bytes */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 int incr; /* direction to move pstartbyte */
779 const unsigned char* pendbyte; /* MSB of bytes */
780 size_t numsignificantbytes; /* number of bytes that matter */
Serhiy Storchaka95949422013-08-27 19:40:23 +0300781 Py_ssize_t ndigits; /* number of Python int digits */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyLongObject* v; /* result */
783 Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
Tim Peters2a9b3672001-06-11 21:23:58 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (n == 0)
786 return PyLong_FromLong(0L);
Tim Peters2a9b3672001-06-11 21:23:58 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (little_endian) {
789 pstartbyte = bytes;
790 pendbyte = bytes + n - 1;
791 incr = 1;
792 }
793 else {
794 pstartbyte = bytes + n - 1;
795 pendbyte = bytes;
796 incr = -1;
797 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 if (is_signed)
800 is_signed = *pendbyte >= 0x80;
Tim Peters2a9b3672001-06-11 21:23:58 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* Compute numsignificantbytes. This consists of finding the most
Ezio Melotti13925002011-03-16 11:05:33 +0200803 significant byte. Leading 0 bytes are insignificant if the number
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 is positive, and leading 0xff bytes if negative. */
805 {
806 size_t i;
807 const unsigned char* p = pendbyte;
808 const int pincr = -incr; /* search MSB to LSB */
Martin Pantereb995702016-07-28 01:11:04 +0000809 const unsigned char insignificant = is_signed ? 0xff : 0x00;
Tim Peters2a9b3672001-06-11 21:23:58 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 for (i = 0; i < n; ++i, p += pincr) {
Martin Pantereb995702016-07-28 01:11:04 +0000812 if (*p != insignificant)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 break;
814 }
815 numsignificantbytes = n - i;
816 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
817 actually has 2 significant bytes. OTOH, 0xff0001 ==
818 -0x00ffff, so we wouldn't *need* to bump it there; but we
819 do for 0xffff = -0x0001. To be safe without bothering to
820 check every case, bump it regardless. */
821 if (is_signed && numsignificantbytes < n)
822 ++numsignificantbytes;
823 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000824
Serhiy Storchaka95949422013-08-27 19:40:23 +0300825 /* How many Python int digits do we need? We have
826 8*numsignificantbytes bits, and each Python int digit has
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 PyLong_SHIFT bits, so it's the ceiling of the quotient. */
828 /* catch overflow before it happens */
829 if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
830 PyErr_SetString(PyExc_OverflowError,
831 "byte array too long to convert to int");
832 return NULL;
833 }
834 ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
835 v = _PyLong_New(ndigits);
836 if (v == NULL)
837 return NULL;
Tim Peters2a9b3672001-06-11 21:23:58 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 /* Copy the bits over. The tricky parts are computing 2's-comp on
840 the fly for signed numbers, and dealing with the mismatch between
841 8-bit bytes and (probably) 15-bit Python digits.*/
842 {
843 size_t i;
844 twodigits carry = 1; /* for 2's-comp calculation */
845 twodigits accum = 0; /* sliding register */
846 unsigned int accumbits = 0; /* number of bits in accum */
847 const unsigned char* p = pstartbyte;
Tim Peters2a9b3672001-06-11 21:23:58 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 for (i = 0; i < numsignificantbytes; ++i, p += incr) {
850 twodigits thisbyte = *p;
851 /* Compute correction for 2's comp, if needed. */
852 if (is_signed) {
853 thisbyte = (0xff ^ thisbyte) + carry;
854 carry = thisbyte >> 8;
855 thisbyte &= 0xff;
856 }
857 /* Because we're going LSB to MSB, thisbyte is
858 more significant than what's already in accum,
859 so needs to be prepended to accum. */
orenmn86aa2692017-03-06 10:42:47 +0200860 accum |= thisbyte << accumbits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 accumbits += 8;
862 if (accumbits >= PyLong_SHIFT) {
863 /* There's enough to fill a Python digit. */
864 assert(idigit < ndigits);
Mark Dickinson22b20182010-05-10 21:27:53 +0000865 v->ob_digit[idigit] = (digit)(accum & PyLong_MASK);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 ++idigit;
867 accum >>= PyLong_SHIFT;
868 accumbits -= PyLong_SHIFT;
869 assert(accumbits < PyLong_SHIFT);
870 }
871 }
872 assert(accumbits < PyLong_SHIFT);
873 if (accumbits) {
874 assert(idigit < ndigits);
875 v->ob_digit[idigit] = (digit)accum;
876 ++idigit;
877 }
878 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 Py_SIZE(v) = is_signed ? -idigit : idigit;
881 return (PyObject *)long_normalize(v);
Tim Peters2a9b3672001-06-11 21:23:58 +0000882}
883
884int
885_PyLong_AsByteArray(PyLongObject* v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 unsigned char* bytes, size_t n,
887 int little_endian, int is_signed)
Tim Peters2a9b3672001-06-11 21:23:58 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 Py_ssize_t i; /* index into v->ob_digit */
Mark Dickinson22b20182010-05-10 21:27:53 +0000890 Py_ssize_t ndigits; /* |v->ob_size| */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 twodigits accum; /* sliding register */
Mark Dickinson22b20182010-05-10 21:27:53 +0000892 unsigned int accumbits; /* # bits in accum */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
894 digit carry; /* for computing 2's-comp */
895 size_t j; /* # bytes filled */
896 unsigned char* p; /* pointer to next byte in bytes */
897 int pincr; /* direction to move p */
Tim Peters2a9b3672001-06-11 21:23:58 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 assert(v != NULL && PyLong_Check(v));
Tim Peters2a9b3672001-06-11 21:23:58 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (Py_SIZE(v) < 0) {
902 ndigits = -(Py_SIZE(v));
903 if (!is_signed) {
904 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +0000905 "can't convert negative int to unsigned");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 return -1;
907 }
908 do_twos_comp = 1;
909 }
910 else {
911 ndigits = Py_SIZE(v);
912 do_twos_comp = 0;
913 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (little_endian) {
916 p = bytes;
917 pincr = 1;
918 }
919 else {
920 p = bytes + n - 1;
921 pincr = -1;
922 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Copy over all the Python digits.
925 It's crucial that every Python digit except for the MSD contribute
Serhiy Storchaka95949422013-08-27 19:40:23 +0300926 exactly PyLong_SHIFT bits to the total, so first assert that the int is
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 normalized. */
928 assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
929 j = 0;
930 accum = 0;
931 accumbits = 0;
932 carry = do_twos_comp ? 1 : 0;
933 for (i = 0; i < ndigits; ++i) {
934 digit thisdigit = v->ob_digit[i];
935 if (do_twos_comp) {
936 thisdigit = (thisdigit ^ PyLong_MASK) + carry;
937 carry = thisdigit >> PyLong_SHIFT;
938 thisdigit &= PyLong_MASK;
939 }
940 /* Because we're going LSB to MSB, thisdigit is more
941 significant than what's already in accum, so needs to be
942 prepended to accum. */
943 accum |= (twodigits)thisdigit << accumbits;
Tim Peters8bc84b42001-06-12 19:17:03 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* The most-significant digit may be (probably is) at least
946 partly empty. */
947 if (i == ndigits - 1) {
948 /* Count # of sign bits -- they needn't be stored,
949 * although for signed conversion we need later to
950 * make sure at least one sign bit gets stored. */
Mark Dickinson22b20182010-05-10 21:27:53 +0000951 digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 while (s != 0) {
953 s >>= 1;
954 accumbits++;
955 }
956 }
957 else
958 accumbits += PyLong_SHIFT;
Tim Peters8bc84b42001-06-12 19:17:03 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Store as many bytes as possible. */
961 while (accumbits >= 8) {
962 if (j >= n)
963 goto Overflow;
964 ++j;
965 *p = (unsigned char)(accum & 0xff);
966 p += pincr;
967 accumbits -= 8;
968 accum >>= 8;
969 }
970 }
Tim Peters2a9b3672001-06-11 21:23:58 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 /* Store the straggler (if any). */
973 assert(accumbits < 8);
974 assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
975 if (accumbits > 0) {
976 if (j >= n)
977 goto Overflow;
978 ++j;
979 if (do_twos_comp) {
980 /* Fill leading bits of the byte with sign bits
Serhiy Storchaka95949422013-08-27 19:40:23 +0300981 (appropriately pretending that the int had an
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 infinite supply of sign bits). */
983 accum |= (~(twodigits)0) << accumbits;
984 }
985 *p = (unsigned char)(accum & 0xff);
986 p += pincr;
987 }
988 else if (j == n && n > 0 && is_signed) {
989 /* The main loop filled the byte array exactly, so the code
990 just above didn't get to ensure there's a sign bit, and the
991 loop below wouldn't add one either. Make sure a sign bit
992 exists. */
993 unsigned char msb = *(p - pincr);
994 int sign_bit_set = msb >= 0x80;
995 assert(accumbits == 0);
996 if (sign_bit_set == do_twos_comp)
997 return 0;
998 else
999 goto Overflow;
1000 }
Tim Peters05607ad2001-06-13 21:01:27 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Fill remaining bytes with copies of the sign bit. */
1003 {
1004 unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
1005 for ( ; j < n; ++j, p += pincr)
1006 *p = signbyte;
1007 }
Tim Peters05607ad2001-06-13 21:01:27 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 return 0;
Tim Peters2a9b3672001-06-11 21:23:58 +00001010
Mark Dickinson22b20182010-05-10 21:27:53 +00001011 Overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyErr_SetString(PyExc_OverflowError, "int too big to convert");
1013 return -1;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001014
Tim Peters2a9b3672001-06-11 21:23:58 +00001015}
1016
Serhiy Storchaka95949422013-08-27 19:40:23 +03001017/* Create a new int object from a C pointer */
Guido van Rossum78694d91998-09-18 14:14:13 +00001018
1019PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00001020PyLong_FromVoidPtr(void *p)
Guido van Rossum78694d91998-09-18 14:14:13 +00001021{
Mark Dickinson91044792012-10-18 19:21:43 +01001022#if SIZEOF_VOID_P <= SIZEOF_LONG
Benjamin Petersonca470632016-09-06 13:47:26 -07001023 return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001024#else
1025
Tim Peters70128a12001-06-16 08:48:40 +00001026#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001027# error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001028#endif
Benjamin Petersonca470632016-09-06 13:47:26 -07001029 return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
Mark Dickinson91044792012-10-18 19:21:43 +01001030#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Tim Peters70128a12001-06-16 08:48:40 +00001031
Guido van Rossum78694d91998-09-18 14:14:13 +00001032}
1033
Serhiy Storchaka95949422013-08-27 19:40:23 +03001034/* Get a C pointer from an int object. */
Guido van Rossum78694d91998-09-18 14:14:13 +00001035
1036void *
Tim Peters9f688bf2000-07-07 15:53:28 +00001037PyLong_AsVoidPtr(PyObject *vv)
Guido van Rossum78694d91998-09-18 14:14:13 +00001038{
Tim Peters70128a12001-06-16 08:48:40 +00001039#if SIZEOF_VOID_P <= SIZEOF_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1043 x = PyLong_AsLong(vv);
1044 else
1045 x = PyLong_AsUnsignedLong(vv);
Guido van Rossum78694d91998-09-18 14:14:13 +00001046#else
Tim Peters70128a12001-06-16 08:48:40 +00001047
Tim Peters70128a12001-06-16 08:48:40 +00001048#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001049# error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
Tim Peters70128a12001-06-16 08:48:40 +00001050#endif
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001051 long long x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
1054 x = PyLong_AsLongLong(vv);
1055 else
1056 x = PyLong_AsUnsignedLongLong(vv);
Tim Peters70128a12001-06-16 08:48:40 +00001057
1058#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
Guido van Rossum78694d91998-09-18 14:14:13 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (x == -1 && PyErr_Occurred())
1061 return NULL;
1062 return (void *)x;
Guido van Rossum78694d91998-09-18 14:14:13 +00001063}
1064
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001065/* Initial long long support by Chris Herborth (chrish@qnx.com), later
Tim Petersd1a7da62001-06-13 00:35:57 +00001066 * rewritten to use the newer PyLong_{As,From}ByteArray API.
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001067 */
1068
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001069#define PY_ABS_LLONG_MIN (0-(unsigned long long)PY_LLONG_MIN)
Tim Petersd1a7da62001-06-13 00:35:57 +00001070
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001071/* Create a new int object from a C long long int. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001072
1073PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001074PyLong_FromLongLong(long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001077 unsigned long long abs_ival;
1078 unsigned long long t; /* unsigned so >> doesn't propagate sign bit */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 int ndigits = 0;
1080 int negative = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 CHECK_SMALL_INT(ival);
1083 if (ival < 0) {
1084 /* avoid signed overflow on negation; see comments
1085 in PyLong_FromLong above. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001086 abs_ival = (unsigned long long)(-1-ival) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 negative = 1;
1088 }
1089 else {
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001090 abs_ival = (unsigned long long)ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 /* Count the number of Python digits.
1094 We used to pick 5 ("big enough for anything"), but that's a
1095 waste of time and space given that 5*15 = 75 bits are rarely
1096 needed. */
1097 t = abs_ival;
1098 while (t) {
1099 ++ndigits;
1100 t >>= PyLong_SHIFT;
1101 }
1102 v = _PyLong_New(ndigits);
1103 if (v != NULL) {
1104 digit *p = v->ob_digit;
1105 Py_SIZE(v) = negative ? -ndigits : ndigits;
1106 t = abs_ival;
1107 while (t) {
1108 *p++ = (digit)(t & PyLong_MASK);
1109 t >>= PyLong_SHIFT;
1110 }
1111 }
1112 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001113}
1114
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001115/* Create a new int object from a C unsigned long long int. */
Tim Petersd1a7da62001-06-13 00:35:57 +00001116
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001117PyObject *
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001118PyLong_FromUnsignedLongLong(unsigned long long ival)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001121 unsigned long long t;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 int ndigits = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (ival < PyLong_BASE)
1125 return PyLong_FromLong((long)ival);
1126 /* Count the number of Python digits. */
orenmn86aa2692017-03-06 10:42:47 +02001127 t = ival;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 while (t) {
1129 ++ndigits;
1130 t >>= PyLong_SHIFT;
1131 }
1132 v = _PyLong_New(ndigits);
1133 if (v != NULL) {
1134 digit *p = v->ob_digit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 while (ival) {
1136 *p++ = (digit)(ival & PyLong_MASK);
1137 ival >>= PyLong_SHIFT;
1138 }
1139 }
1140 return (PyObject *)v;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001141}
1142
Serhiy Storchaka95949422013-08-27 19:40:23 +03001143/* Create a new int object from a C Py_ssize_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144
1145PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001146PyLong_FromSsize_t(Py_ssize_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 PyLongObject *v;
1149 size_t abs_ival;
1150 size_t t; /* unsigned so >> doesn't propagate sign bit */
1151 int ndigits = 0;
1152 int negative = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 CHECK_SMALL_INT(ival);
1155 if (ival < 0) {
1156 /* avoid signed overflow when ival = SIZE_T_MIN */
1157 abs_ival = (size_t)(-1-ival)+1;
1158 negative = 1;
1159 }
1160 else {
1161 abs_ival = (size_t)ival;
1162 }
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 /* Count the number of Python digits. */
1165 t = abs_ival;
1166 while (t) {
1167 ++ndigits;
1168 t >>= PyLong_SHIFT;
1169 }
1170 v = _PyLong_New(ndigits);
1171 if (v != NULL) {
1172 digit *p = v->ob_digit;
1173 Py_SIZE(v) = negative ? -ndigits : ndigits;
1174 t = abs_ival;
1175 while (t) {
1176 *p++ = (digit)(t & PyLong_MASK);
1177 t >>= PyLong_SHIFT;
1178 }
1179 }
1180 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181}
1182
Serhiy Storchaka95949422013-08-27 19:40:23 +03001183/* Create a new int object from a C size_t. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001184
1185PyObject *
Guido van Rossumddefaf32007-01-14 03:31:43 +00001186PyLong_FromSize_t(size_t ival)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyLongObject *v;
1189 size_t t;
1190 int ndigits = 0;
Mark Dickinson7ab6be22008-04-15 21:42:42 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 if (ival < PyLong_BASE)
1193 return PyLong_FromLong((long)ival);
1194 /* Count the number of Python digits. */
1195 t = ival;
1196 while (t) {
1197 ++ndigits;
1198 t >>= PyLong_SHIFT;
1199 }
1200 v = _PyLong_New(ndigits);
1201 if (v != NULL) {
1202 digit *p = v->ob_digit;
1203 Py_SIZE(v) = ndigits;
1204 while (ival) {
1205 *p++ = (digit)(ival & PyLong_MASK);
1206 ival >>= PyLong_SHIFT;
1207 }
1208 }
1209 return (PyObject *)v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210}
1211
Serhiy Storchaka95949422013-08-27 19:40:23 +03001212/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001213 __int__ method. Return -1 and set an error if overflow occurs. */
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001214
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001215long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001216PyLong_AsLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001219 long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 int res;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001221 int do_decref = 0; /* if nb_int was called */
Tim Petersd1a7da62001-06-13 00:35:57 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (vv == NULL) {
1224 PyErr_BadInternalCall();
1225 return -1;
1226 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001227
1228 if (PyLong_Check(vv)) {
1229 v = (PyLongObject *)vv;
1230 }
1231 else {
1232 v = _PyLong_FromNbInt(vv);
1233 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return -1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001235 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001237
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001238 res = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 switch(Py_SIZE(v)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001240 case -1:
1241 bytes = -(sdigit)v->ob_digit[0];
1242 break;
1243 case 0:
1244 bytes = 0;
1245 break;
1246 case 1:
1247 bytes = v->ob_digit[0];
1248 break;
1249 default:
1250 res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
Serhiy Storchakac4f32122013-12-11 21:26:36 +02001251 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 }
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001253 if (do_decref) {
1254 Py_DECREF(v);
1255 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001256
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001257 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001259 return (long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 else
1261 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001262}
1263
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001264/* Get a C unsigned long long int from an int object.
Tim Petersd1a7da62001-06-13 00:35:57 +00001265 Return -1 and set an error if overflow occurs. */
1266
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001267unsigned long long
Tim Peters9f688bf2000-07-07 15:53:28 +00001268PyLong_AsUnsignedLongLong(PyObject *vv)
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001271 unsigned long long bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 int res;
Tim Petersd1a7da62001-06-13 00:35:57 +00001273
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001274 if (vv == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 PyErr_BadInternalCall();
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001276 return (unsigned long long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001278 if (!PyLong_Check(vv)) {
1279 PyErr_SetString(PyExc_TypeError, "an integer is required");
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001280 return (unsigned long long)-1;
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02001281 }
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 v = (PyLongObject*)vv;
1284 switch(Py_SIZE(v)) {
1285 case 0: return 0;
1286 case 1: return v->ob_digit[0];
1287 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001288
Mark Dickinson22b20182010-05-10 21:27:53 +00001289 res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
Christian Heimes743e0cd2012-10-17 23:52:17 +02001290 SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001291
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001292 /* Plan 9 can't handle long long in ? : expressions */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (res < 0)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001294 return (unsigned long long)res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 else
1296 return bytes;
Guido van Rossum1a8791e1998-08-04 22:46:29 +00001297}
Tim Petersd1a7da62001-06-13 00:35:57 +00001298
Serhiy Storchaka95949422013-08-27 19:40:23 +03001299/* Get a C unsigned long int from an int object, ignoring the high bits.
Thomas Hellera4ea6032003-04-17 18:55:45 +00001300 Returns -1 and sets an error condition if an error occurs. */
1301
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001302static unsigned long long
Guido van Rossumddefaf32007-01-14 03:31:43 +00001303_PyLong_AsUnsignedLongLongMask(PyObject *vv)
Thomas Hellera4ea6032003-04-17 18:55:45 +00001304{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001305 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001306 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 Py_ssize_t i;
1308 int sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (vv == NULL || !PyLong_Check(vv)) {
1311 PyErr_BadInternalCall();
1312 return (unsigned long) -1;
1313 }
1314 v = (PyLongObject *)vv;
1315 switch(Py_SIZE(v)) {
1316 case 0: return 0;
1317 case 1: return v->ob_digit[0];
1318 }
1319 i = Py_SIZE(v);
1320 sign = 1;
1321 x = 0;
1322 if (i < 0) {
1323 sign = -1;
1324 i = -i;
1325 }
1326 while (--i >= 0) {
1327 x = (x << PyLong_SHIFT) | v->ob_digit[i];
1328 }
1329 return x * sign;
Thomas Hellera4ea6032003-04-17 18:55:45 +00001330}
Guido van Rossumddefaf32007-01-14 03:31:43 +00001331
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001332unsigned long long
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001333PyLong_AsUnsignedLongLongMask(PyObject *op)
Guido van Rossumddefaf32007-01-14 03:31:43 +00001334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PyLongObject *lo;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001336 unsigned long long val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001337
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001338 if (op == NULL) {
1339 PyErr_BadInternalCall();
1340 return (unsigned long)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00001342
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001343 if (PyLong_Check(op)) {
1344 return _PyLong_AsUnsignedLongLongMask(op);
1345 }
1346
1347 lo = _PyLong_FromNbInt(op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (lo == NULL)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001349 return (unsigned long long)-1;
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001350
1351 val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
1352 Py_DECREF(lo);
1353 return val;
Guido van Rossumddefaf32007-01-14 03:31:43 +00001354}
Tim Petersd1a7da62001-06-13 00:35:57 +00001355
Serhiy Storchaka95949422013-08-27 19:40:23 +03001356/* Get a C long long int from an int object or any object that has an
Mark Dickinson8d48b432011-10-23 20:47:14 +01001357 __int__ method.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001358
Mark Dickinson8d48b432011-10-23 20:47:14 +01001359 On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
1360 the result. Otherwise *overflow is 0.
1361
1362 For other errors (e.g., TypeError), return -1 and set an error condition.
1363 In this case *overflow will be 0.
Mark Dickinson93f562c2010-01-30 10:30:15 +00001364*/
1365
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001366long long
Mark Dickinson93f562c2010-01-30 10:30:15 +00001367PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
1368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* This version by Tim Peters */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001370 PyLongObject *v;
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001371 unsigned long long x, prev;
1372 long long res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 Py_ssize_t i;
1374 int sign;
1375 int do_decref = 0; /* if nb_int was called */
Mark Dickinson93f562c2010-01-30 10:30:15 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 *overflow = 0;
1378 if (vv == NULL) {
1379 PyErr_BadInternalCall();
1380 return -1;
1381 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001382
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001383 if (PyLong_Check(vv)) {
1384 v = (PyLongObject *)vv;
1385 }
1386 else {
1387 v = _PyLong_FromNbInt(vv);
1388 if (v == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 return -1;
1390 do_decref = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 }
Mark Dickinson93f562c2010-01-30 10:30:15 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 res = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 i = Py_SIZE(v);
Mark Dickinson93f562c2010-01-30 10:30:15 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 switch (i) {
1397 case -1:
1398 res = -(sdigit)v->ob_digit[0];
1399 break;
1400 case 0:
1401 res = 0;
1402 break;
1403 case 1:
1404 res = v->ob_digit[0];
1405 break;
1406 default:
1407 sign = 1;
1408 x = 0;
1409 if (i < 0) {
1410 sign = -1;
1411 i = -(i);
1412 }
1413 while (--i >= 0) {
1414 prev = x;
1415 x = (x << PyLong_SHIFT) + v->ob_digit[i];
1416 if ((x >> PyLong_SHIFT) != prev) {
1417 *overflow = sign;
1418 goto exit;
1419 }
1420 }
1421 /* Haven't lost any bits, but casting to long requires extra
1422 * care (see comment above).
1423 */
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001424 if (x <= (unsigned long long)PY_LLONG_MAX) {
1425 res = (long long)x * sign;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 }
1427 else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
1428 res = PY_LLONG_MIN;
1429 }
1430 else {
1431 *overflow = sign;
1432 /* res is already set to -1 */
1433 }
1434 }
Mark Dickinson22b20182010-05-10 21:27:53 +00001435 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 if (do_decref) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001437 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 }
1439 return res;
Mark Dickinson93f562c2010-01-30 10:30:15 +00001440}
1441
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001442#define CHECK_BINOP(v,w) \
1443 do { \
Brian Curtindfc80e32011-08-10 20:28:54 -05001444 if (!PyLong_Check(v) || !PyLong_Check(w)) \
1445 Py_RETURN_NOTIMPLEMENTED; \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001446 } while(0)
Neil Schemenauerba872e22001-01-04 01:46:03 +00001447
Tim Peters877a2122002-08-12 05:09:36 +00001448/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1449 * is modified in place, by adding y to it. Carries are propagated as far as
1450 * x[m-1], and the remaining carry (0 or 1) is returned.
1451 */
1452static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001453v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 Py_ssize_t i;
1456 digit carry = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 assert(m >= n);
1459 for (i = 0; i < n; ++i) {
1460 carry += x[i] + y[i];
1461 x[i] = carry & PyLong_MASK;
1462 carry >>= PyLong_SHIFT;
1463 assert((carry & 1) == carry);
1464 }
1465 for (; carry && i < m; ++i) {
1466 carry += x[i];
1467 x[i] = carry & PyLong_MASK;
1468 carry >>= PyLong_SHIFT;
1469 assert((carry & 1) == carry);
1470 }
1471 return carry;
Tim Peters877a2122002-08-12 05:09:36 +00001472}
1473
1474/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
1475 * is modified in place, by subtracting y from it. Borrows are propagated as
1476 * far as x[m-1], and the remaining borrow (0 or 1) is returned.
1477 */
1478static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001479v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
Tim Peters877a2122002-08-12 05:09:36 +00001480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 Py_ssize_t i;
1482 digit borrow = 0;
Tim Peters877a2122002-08-12 05:09:36 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 assert(m >= n);
1485 for (i = 0; i < n; ++i) {
1486 borrow = x[i] - y[i] - borrow;
1487 x[i] = borrow & PyLong_MASK;
1488 borrow >>= PyLong_SHIFT;
1489 borrow &= 1; /* keep only 1 sign bit */
1490 }
1491 for (; borrow && i < m; ++i) {
1492 borrow = x[i] - borrow;
1493 x[i] = borrow & PyLong_MASK;
1494 borrow >>= PyLong_SHIFT;
1495 borrow &= 1;
1496 }
1497 return borrow;
Tim Peters877a2122002-08-12 05:09:36 +00001498}
Neil Schemenauerba872e22001-01-04 01:46:03 +00001499
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001500/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
1501 * result in z[0:m], and return the d bits shifted out of the top.
1502 */
1503static digit
1504v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 Py_ssize_t i;
1507 digit carry = 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 assert(0 <= d && d < PyLong_SHIFT);
1510 for (i=0; i < m; i++) {
1511 twodigits acc = (twodigits)a[i] << d | carry;
1512 z[i] = (digit)acc & PyLong_MASK;
1513 carry = (digit)(acc >> PyLong_SHIFT);
1514 }
1515 return carry;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001516}
1517
1518/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
1519 * result in z[0:m], and return the d bits shifted out of the bottom.
1520 */
1521static digit
1522v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
1523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_ssize_t i;
1525 digit carry = 0;
1526 digit mask = ((digit)1 << d) - 1U;
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 assert(0 <= d && d < PyLong_SHIFT);
1529 for (i=m; i-- > 0;) {
1530 twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
1531 carry = (digit)acc & mask;
1532 z[i] = (digit)(acc >> d);
1533 }
1534 return carry;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001535}
1536
Tim Peters212e6142001-07-14 12:23:19 +00001537/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
1538 in pout, and returning the remainder. pin and pout point at the LSD.
1539 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
Serhiy Storchaka95949422013-08-27 19:40:23 +03001540 _PyLong_Format, but that should be done with great care since ints are
Tim Peters212e6142001-07-14 12:23:19 +00001541 immutable. */
1542
1543static digit
Martin v. Löwis18e16552006-02-15 17:27:45 +00001544inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
Tim Peters212e6142001-07-14 12:23:19 +00001545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 twodigits rem = 0;
Tim Peters212e6142001-07-14 12:23:19 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 assert(n > 0 && n <= PyLong_MASK);
1549 pin += size;
1550 pout += size;
1551 while (--size >= 0) {
1552 digit hi;
1553 rem = (rem << PyLong_SHIFT) | *--pin;
1554 *--pout = hi = (digit)(rem / n);
1555 rem -= (twodigits)hi * n;
1556 }
1557 return (digit)rem;
Tim Peters212e6142001-07-14 12:23:19 +00001558}
1559
Serhiy Storchaka95949422013-08-27 19:40:23 +03001560/* Divide an integer by a digit, returning both the quotient
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001561 (as function result) and the remainder (through *prem).
1562 The sign of a is ignored; n should not be zero. */
1563
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001564static PyLongObject *
Tim Peters212e6142001-07-14 12:23:19 +00001565divrem1(PyLongObject *a, digit n, digit *prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001566{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001567 const Py_ssize_t size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 assert(n > 0 && n <= PyLong_MASK);
1571 z = _PyLong_New(size);
1572 if (z == NULL)
1573 return NULL;
1574 *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
1575 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001576}
1577
Serhiy Storchaka95949422013-08-27 19:40:23 +03001578/* Convert an integer to a base 10 string. Returns a new non-shared
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001579 string. (Return value is non-shared so that callers can modify the
1580 returned value if necessary.) */
1581
Victor Stinnerd3f08822012-05-29 12:57:52 +02001582static int
1583long_to_decimal_string_internal(PyObject *aa,
1584 PyObject **p_output,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001585 _PyUnicodeWriter *writer,
1586 _PyBytesWriter *bytes_writer,
1587 char **bytes_str)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 PyLongObject *scratch, *a;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001590 PyObject *str = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 Py_ssize_t size, strlen, size_a, i, j;
1592 digit *pout, *pin, rem, tenpow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 int negative;
Mark Dickinson4e1de162016-08-29 17:26:43 +01001594 int d;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001595 enum PyUnicode_Kind kind;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 a = (PyLongObject *)aa;
1598 if (a == NULL || !PyLong_Check(a)) {
1599 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001600 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001602 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 negative = Py_SIZE(a) < 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 /* quick and dirty upper bound for the number of digits
1606 required to express a in base _PyLong_DECIMAL_BASE:
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 But log2(a) < size_a * PyLong_SHIFT, and
1611 log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
Mark Dickinson4e1de162016-08-29 17:26:43 +01001612 > 3.3 * _PyLong_DECIMAL_SHIFT
1613
1614 size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
1615 size_a + size_a / d < size_a + size_a / floor(d),
1616 where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
1617 (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 */
Mark Dickinson4e1de162016-08-29 17:26:43 +01001619 d = (33 * _PyLong_DECIMAL_SHIFT) /
1620 (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
1621 assert(size_a < PY_SSIZE_T_MAX/2);
1622 size = 1 + size_a + size_a / d;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 scratch = _PyLong_New(size);
1624 if (scratch == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001625 return -1;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* convert array of base _PyLong_BASE digits in pin to an array of
1628 base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
1629 Volume 2 (3rd edn), section 4.4, Method 1b). */
1630 pin = a->ob_digit;
1631 pout = scratch->ob_digit;
1632 size = 0;
1633 for (i = size_a; --i >= 0; ) {
1634 digit hi = pin[i];
1635 for (j = 0; j < size; j++) {
1636 twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
1637 hi = (digit)(z / _PyLong_DECIMAL_BASE);
1638 pout[j] = (digit)(z - (twodigits)hi *
1639 _PyLong_DECIMAL_BASE);
1640 }
1641 while (hi) {
1642 pout[size++] = hi % _PyLong_DECIMAL_BASE;
1643 hi /= _PyLong_DECIMAL_BASE;
1644 }
1645 /* check for keyboard interrupt */
1646 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00001647 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001648 return -1;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00001649 });
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 }
1651 /* pout should have at least one digit, so that the case when a = 0
1652 works correctly */
1653 if (size == 0)
1654 pout[size++] = 0;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 /* calculate exact length of output string, and allocate */
1657 strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
1658 tenpow = 10;
1659 rem = pout[size-1];
1660 while (rem >= tenpow) {
1661 tenpow *= 10;
1662 strlen++;
1663 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001664 if (writer) {
Christian Heimes110ac162012-09-10 02:51:27 +02001665 if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
1666 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001667 return -1;
Christian Heimes110ac162012-09-10 02:51:27 +02001668 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001669 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001671 else if (bytes_writer) {
1672 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
1673 if (*bytes_str == NULL) {
1674 Py_DECREF(scratch);
1675 return -1;
1676 }
1677 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678 else {
1679 str = PyUnicode_New(strlen, '9');
1680 if (str == NULL) {
1681 Py_DECREF(scratch);
1682 return -1;
1683 }
1684 kind = PyUnicode_KIND(str);
1685 }
1686
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001687#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001688 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001689 /* pout[0] through pout[size-2] contribute exactly \
1690 _PyLong_DECIMAL_SHIFT digits each */ \
1691 for (i=0; i < size - 1; i++) { \
1692 rem = pout[i]; \
1693 for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
1694 *--p = '0' + rem % 10; \
1695 rem /= 10; \
1696 } \
1697 } \
1698 /* pout[size-1]: always produce at least one decimal digit */ \
1699 rem = pout[i]; \
1700 do { \
1701 *--p = '0' + rem % 10; \
1702 rem /= 10; \
1703 } while (rem != 0); \
1704 \
1705 /* and sign */ \
1706 if (negative) \
1707 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001708 } while (0)
1709
1710#define WRITE_UNICODE_DIGITS(TYPE) \
1711 do { \
1712 if (writer) \
1713 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
1714 else \
1715 p = (TYPE*)PyUnicode_DATA(str) + strlen; \
1716 \
1717 WRITE_DIGITS(p); \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001718 \
1719 /* check we've counted correctly */ \
1720 if (writer) \
1721 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1722 else \
1723 assert(p == (TYPE*)PyUnicode_DATA(str)); \
1724 } while (0)
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* fill the string right-to-left */
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001727 if (bytes_writer) {
1728 char *p = *bytes_str + strlen;
1729 WRITE_DIGITS(p);
1730 assert(p == *bytes_str);
1731 }
1732 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001733 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001734 WRITE_UNICODE_DIGITS(Py_UCS1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001736 else if (kind == PyUnicode_2BYTE_KIND) {
1737 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001738 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001739 }
1740 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001741 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001742 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001743 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001744 }
1745#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001746#undef WRITE_UNICODE_DIGITS
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 Py_DECREF(scratch);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001749 if (writer) {
1750 writer->pos += strlen;
1751 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001752 else if (bytes_writer) {
1753 (*bytes_str) += strlen;
1754 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001755 else {
1756 assert(_PyUnicode_CheckConsistency(str, 1));
1757 *p_output = (PyObject *)str;
1758 }
1759 return 0;
1760}
1761
1762static PyObject *
1763long_to_decimal_string(PyObject *aa)
1764{
1765 PyObject *v;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001766 if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
Victor Stinnerd3f08822012-05-29 12:57:52 +02001767 return NULL;
1768 return v;
Mark Dickinson0a1efd02009-09-16 21:23:34 +00001769}
1770
Serhiy Storchaka95949422013-08-27 19:40:23 +03001771/* Convert an int object to a string, using a given conversion base,
Victor Stinnerd3f08822012-05-29 12:57:52 +02001772 which should be one of 2, 8 or 16. Return a string object.
1773 If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
1774 if alternate is nonzero. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001775
Victor Stinnerd3f08822012-05-29 12:57:52 +02001776static int
1777long_format_binary(PyObject *aa, int base, int alternate,
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001778 PyObject **p_output, _PyUnicodeWriter *writer,
1779 _PyBytesWriter *bytes_writer, char **bytes_str)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001780{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001781 PyLongObject *a = (PyLongObject *)aa;
Victor Stinner1285e5c2015-10-14 12:10:20 +02001782 PyObject *v = NULL;
Mark Dickinsone2846542012-04-20 21:21:24 +01001783 Py_ssize_t sz;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 Py_ssize_t size_a;
Victor Stinnerd3f08822012-05-29 12:57:52 +02001785 enum PyUnicode_Kind kind;
Mark Dickinsone2846542012-04-20 21:21:24 +01001786 int negative;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 int bits;
Guido van Rossume32e0141992-01-19 16:31:05 +00001788
Victor Stinnerd3f08822012-05-29 12:57:52 +02001789 assert(base == 2 || base == 8 || base == 16);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (a == NULL || !PyLong_Check(a)) {
1791 PyErr_BadInternalCall();
Victor Stinnerd3f08822012-05-29 12:57:52 +02001792 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02001794 size_a = Py_ABS(Py_SIZE(a));
Mark Dickinsone2846542012-04-20 21:21:24 +01001795 negative = Py_SIZE(a) < 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 /* Compute a rough upper bound for the length of the string */
1798 switch (base) {
1799 case 16:
1800 bits = 4;
1801 break;
1802 case 8:
1803 bits = 3;
1804 break;
1805 case 2:
1806 bits = 1;
1807 break;
1808 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001809 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00001811
Mark Dickinsone2846542012-04-20 21:21:24 +01001812 /* Compute exact length 'sz' of output string. */
1813 if (size_a == 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001814 sz = 1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001815 }
1816 else {
1817 Py_ssize_t size_a_in_bits;
1818 /* Ensure overflow doesn't occur during computation of sz. */
1819 if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
1820 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01001821 "int too large to format");
Victor Stinnerd3f08822012-05-29 12:57:52 +02001822 return -1;
Mark Dickinsone2846542012-04-20 21:21:24 +01001823 }
1824 size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
1825 bits_in_digit(a->ob_digit[size_a - 1]);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001826 /* Allow 1 character for a '-' sign. */
1827 sz = negative + (size_a_in_bits + (bits - 1)) / bits;
1828 }
1829 if (alternate) {
1830 /* 2 characters for prefix */
1831 sz += 2;
Mark Dickinsone2846542012-04-20 21:21:24 +01001832 }
1833
Victor Stinnerd3f08822012-05-29 12:57:52 +02001834 if (writer) {
1835 if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
1836 return -1;
1837 kind = writer->kind;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
Victor Stinner199c9a62015-10-14 09:47:23 +02001839 else if (bytes_writer) {
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001840 *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
1841 if (*bytes_str == NULL)
1842 return -1;
1843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001845 v = PyUnicode_New(sz, 'x');
1846 if (v == NULL)
1847 return -1;
1848 kind = PyUnicode_KIND(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 }
Mark Dickinson8accd6b2009-09-17 19:39:12 +00001850
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001851#define WRITE_DIGITS(p) \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001852 do { \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001853 if (size_a == 0) { \
1854 *--p = '0'; \
1855 } \
1856 else { \
1857 /* JRH: special case for power-of-2 bases */ \
1858 twodigits accum = 0; \
1859 int accumbits = 0; /* # of bits in accum */ \
1860 Py_ssize_t i; \
1861 for (i = 0; i < size_a; ++i) { \
1862 accum |= (twodigits)a->ob_digit[i] << accumbits; \
1863 accumbits += PyLong_SHIFT; \
1864 assert(accumbits >= bits); \
1865 do { \
1866 char cdigit; \
1867 cdigit = (char)(accum & (base - 1)); \
1868 cdigit += (cdigit < 10) ? '0' : 'a'-10; \
1869 *--p = cdigit; \
1870 accumbits -= bits; \
1871 accum >>= bits; \
1872 } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
1873 } \
1874 } \
1875 \
1876 if (alternate) { \
1877 if (base == 16) \
1878 *--p = 'x'; \
1879 else if (base == 8) \
1880 *--p = 'o'; \
1881 else /* (base == 2) */ \
1882 *--p = 'b'; \
1883 *--p = '0'; \
1884 } \
1885 if (negative) \
1886 *--p = '-'; \
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001887 } while (0)
1888
1889#define WRITE_UNICODE_DIGITS(TYPE) \
1890 do { \
1891 if (writer) \
1892 p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
1893 else \
1894 p = (TYPE*)PyUnicode_DATA(v) + sz; \
1895 \
1896 WRITE_DIGITS(p); \
1897 \
Victor Stinnerd3f08822012-05-29 12:57:52 +02001898 if (writer) \
1899 assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
1900 else \
1901 assert(p == (TYPE*)PyUnicode_DATA(v)); \
1902 } while (0)
1903
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001904 if (bytes_writer) {
1905 char *p = *bytes_str + sz;
1906 WRITE_DIGITS(p);
1907 assert(p == *bytes_str);
1908 }
1909 else if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001910 Py_UCS1 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001911 WRITE_UNICODE_DIGITS(Py_UCS1);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001912 }
1913 else if (kind == PyUnicode_2BYTE_KIND) {
1914 Py_UCS2 *p;
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001915 WRITE_UNICODE_DIGITS(Py_UCS2);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001916 }
1917 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001918 Py_UCS4 *p;
Victor Stinnere577ab32012-05-29 18:51:10 +02001919 assert (kind == PyUnicode_4BYTE_KIND);
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001920 WRITE_UNICODE_DIGITS(Py_UCS4);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001921 }
1922#undef WRITE_DIGITS
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001923#undef WRITE_UNICODE_DIGITS
Victor Stinnerd3f08822012-05-29 12:57:52 +02001924
1925 if (writer) {
1926 writer->pos += sz;
1927 }
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001928 else if (bytes_writer) {
1929 (*bytes_str) += sz;
1930 }
Victor Stinnerd3f08822012-05-29 12:57:52 +02001931 else {
1932 assert(_PyUnicode_CheckConsistency(v, 1));
1933 *p_output = v;
1934 }
1935 return 0;
1936}
1937
1938PyObject *
1939_PyLong_Format(PyObject *obj, int base)
1940{
1941 PyObject *str;
1942 int err;
1943 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001944 err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001945 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001946 err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001947 if (err == -1)
1948 return NULL;
1949 return str;
1950}
1951
1952int
1953_PyLong_FormatWriter(_PyUnicodeWriter *writer,
1954 PyObject *obj,
1955 int base, int alternate)
1956{
1957 if (base == 10)
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001958 return long_to_decimal_string_internal(obj, NULL, writer,
1959 NULL, NULL);
Victor Stinnerd3f08822012-05-29 12:57:52 +02001960 else
Victor Stinnerbe75b8c2015-10-09 22:43:24 +02001961 return long_format_binary(obj, base, alternate, NULL, writer,
1962 NULL, NULL);
1963}
1964
1965char*
1966_PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
1967 PyObject *obj,
1968 int base, int alternate)
1969{
1970 char *str2;
1971 int res;
1972 str2 = str;
1973 if (base == 10)
1974 res = long_to_decimal_string_internal(obj, NULL, NULL,
1975 writer, &str2);
1976 else
1977 res = long_format_binary(obj, base, alternate, NULL, NULL,
1978 writer, &str2);
1979 if (res < 0)
1980 return NULL;
1981 assert(str2 != NULL);
1982 return str2;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00001983}
1984
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985/* Table of digit values for 8-bit string -> integer conversion.
1986 * '0' maps to 0, ..., '9' maps to 9.
1987 * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
1988 * All other indices map to 37.
1989 * Note that when converting a base B string, a char c is a legitimate
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001990 * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991 */
Raymond Hettinger35631532009-01-09 03:58:09 +00001992unsigned char _PyLong_DigitValue[256] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1994 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1995 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
1996 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
1997 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
1998 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
1999 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
2000 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
2001 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2002 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2003 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2004 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2005 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2006 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2007 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
2008 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002009};
2010
2011/* *str points to the first digit in a string of base `base` digits. base
Tim Petersbf2674b2003-02-02 07:51:32 +00002012 * 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 +03002013 * non-digit (which may be *str!). A normalized int is returned.
Tim Petersbf2674b2003-02-02 07:51:32 +00002014 * The point to this routine is that it takes time linear in the number of
2015 * string characters.
Brett Cannona721aba2016-09-09 14:57:09 -07002016 *
2017 * Return values:
2018 * -1 on syntax error (exception needs to be set, *res is untouched)
2019 * 0 else (exception may be set, in that case *res is set to NULL)
Tim Petersbf2674b2003-02-02 07:51:32 +00002020 */
Brett Cannona721aba2016-09-09 14:57:09 -07002021static int
2022long_from_binary_base(const char **str, int base, PyLongObject **res)
Tim Petersbf2674b2003-02-02 07:51:32 +00002023{
Serhiy Storchakac6792272013-10-19 21:03:34 +03002024 const char *p = *str;
2025 const char *start = p;
Brett Cannona721aba2016-09-09 14:57:09 -07002026 char prev = 0;
2027 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 int bits_per_char;
2029 Py_ssize_t n;
2030 PyLongObject *z;
2031 twodigits accum;
2032 int bits_in_accum;
2033 digit *pdigit;
Tim Petersbf2674b2003-02-02 07:51:32 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
2036 n = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002037 for (bits_per_char = -1; n; ++bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 n >>= 1;
Brett Cannona721aba2016-09-09 14:57:09 -07002039 }
2040 /* count digits and set p to end-of-string */
2041 while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
2042 if (*p == '_') {
2043 if (prev == '_') {
2044 *str = p - 1;
2045 return -1;
2046 }
2047 } else {
2048 ++digits;
2049 }
2050 prev = *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 ++p;
Brett Cannona721aba2016-09-09 14:57:09 -07002052 }
2053 if (prev == '_') {
2054 /* Trailing underscore not allowed. */
2055 *str = p - 1;
2056 return -1;
2057 }
2058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 *str = p;
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002060 /* n <- the number of Python digits needed,
2061 = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
2062 if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyErr_SetString(PyExc_ValueError,
2064 "int string too large to convert");
Brett Cannona721aba2016-09-09 14:57:09 -07002065 *res = NULL;
2066 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 }
Serhiy Storchaka85c0b892017-10-03 14:13:44 +03002068 n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 z = _PyLong_New(n);
Brett Cannona721aba2016-09-09 14:57:09 -07002070 if (z == NULL) {
2071 *res = NULL;
2072 return 0;
2073 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03002074 /* Read string from right, and fill in int from left; i.e.,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 * from least to most significant in both.
2076 */
2077 accum = 0;
2078 bits_in_accum = 0;
2079 pdigit = z->ob_digit;
2080 while (--p >= start) {
Brett Cannona721aba2016-09-09 14:57:09 -07002081 int k;
2082 if (*p == '_') {
2083 continue;
2084 }
2085 k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 assert(k >= 0 && k < base);
2087 accum |= (twodigits)k << bits_in_accum;
2088 bits_in_accum += bits_per_char;
2089 if (bits_in_accum >= PyLong_SHIFT) {
2090 *pdigit++ = (digit)(accum & PyLong_MASK);
2091 assert(pdigit - z->ob_digit <= n);
2092 accum >>= PyLong_SHIFT;
2093 bits_in_accum -= PyLong_SHIFT;
2094 assert(bits_in_accum < PyLong_SHIFT);
2095 }
2096 }
2097 if (bits_in_accum) {
2098 assert(bits_in_accum <= PyLong_SHIFT);
2099 *pdigit++ = (digit)accum;
2100 assert(pdigit - z->ob_digit <= n);
2101 }
2102 while (pdigit - z->ob_digit < n)
2103 *pdigit++ = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002104 *res = long_normalize(z);
2105 return 0;
Tim Petersbf2674b2003-02-02 07:51:32 +00002106}
2107
Serhiy Storchaka95949422013-08-27 19:40:23 +03002108/* Parses an int from a bytestring. Leading and trailing whitespace will be
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002109 * ignored.
2110 *
2111 * If successful, a PyLong object will be returned and 'pend' will be pointing
2112 * to the first unused byte unless it's NULL.
2113 *
2114 * If unsuccessful, NULL will be returned.
2115 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002117PyLong_FromString(const char *str, char **pend, int base)
Guido van Rossumeb1fafc1994-08-29 12:47:19 +00002118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 int sign = 1, error_if_nonzero = 0;
Serhiy Storchakac6792272013-10-19 21:03:34 +03002120 const char *start, *orig_str = str;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 PyLongObject *z = NULL;
2122 PyObject *strobj;
2123 Py_ssize_t slen;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if ((base != 0 && base < 2) || base > 36) {
2126 PyErr_SetString(PyExc_ValueError,
2127 "int() arg 2 must be >= 2 and <= 36");
2128 return NULL;
2129 }
Brett Cannona721aba2016-09-09 14:57:09 -07002130 while (*str != '\0' && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002132 }
2133 if (*str == '+') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 ++str;
Brett Cannona721aba2016-09-09 14:57:09 -07002135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 else if (*str == '-') {
2137 ++str;
2138 sign = -1;
2139 }
2140 if (base == 0) {
Brett Cannona721aba2016-09-09 14:57:09 -07002141 if (str[0] != '0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 base = 10;
Brett Cannona721aba2016-09-09 14:57:09 -07002143 }
2144 else if (str[1] == 'x' || str[1] == 'X') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 base = 16;
Brett Cannona721aba2016-09-09 14:57:09 -07002146 }
2147 else if (str[1] == 'o' || str[1] == 'O') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 base = 8;
Brett Cannona721aba2016-09-09 14:57:09 -07002149 }
2150 else if (str[1] == 'b' || str[1] == 'B') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 base = 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 else {
2154 /* "old" (C-style) octal literal, now invalid.
2155 it might still be zero though */
2156 error_if_nonzero = 1;
2157 base = 10;
2158 }
2159 }
2160 if (str[0] == '0' &&
2161 ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
2162 (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
Brett Cannona721aba2016-09-09 14:57:09 -07002163 (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 str += 2;
Brett Cannona721aba2016-09-09 14:57:09 -07002165 /* One underscore allowed here. */
2166 if (*str == '_') {
2167 ++str;
2168 }
2169 }
2170 if (str[0] == '_') {
Barry Warsawb2e57942017-09-14 18:13:16 -07002171 /* May not start with underscores. */
2172 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002173 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 start = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002176 if ((base & (base - 1)) == 0) {
2177 int res = long_from_binary_base(&str, base, &z);
2178 if (res < 0) {
2179 /* Syntax error. */
2180 goto onError;
2181 }
2182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +00002184/***
2185Binary bases can be converted in time linear in the number of digits, because
2186Python's representation base is binary. Other bases (including decimal!) use
2187the simple quadratic-time algorithm below, complicated by some speed tricks.
Tim Peters5af4e6c2002-08-12 02:31:19 +00002188
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189First some math: the largest integer that can be expressed in N base-B digits
2190is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
2191case number of Python digits needed to hold it is the smallest integer n s.t.
2192
2193 BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
2194 BASE**n >= B**N [taking logs to base BASE]
2195 n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
2196
2197The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
Serhiy Storchaka95949422013-08-27 19:40:23 +03002198this quickly. A Python int with that much space is reserved near the start,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002199and the result is computed into it.
2200
2201The input string is actually treated as being in base base**i (i.e., i digits
2202are processed at a time), where two more static arrays hold:
2203
2204 convwidth_base[base] = the largest integer i such that base**i <= BASE
2205 convmultmax_base[base] = base ** convwidth_base[base]
2206
2207The first of these is the largest i such that i consecutive input digits
2208must fit in a single Python digit. The second is effectively the input
2209base we're really using.
2210
2211Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
2212convmultmax_base[base], the result is "simply"
2213
2214 (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
2215
2216where B = convmultmax_base[base].
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002217
2218Error analysis: as above, the number of Python digits `n` needed is worst-
2219case
2220
2221 n >= N * log(B)/log(BASE)
2222
2223where `N` is the number of input digits in base `B`. This is computed via
2224
2225 size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
2226
2227below. Two numeric concerns are how much space this can waste, and whether
2228the computed result can be too small. To be concrete, assume BASE = 2**15,
2229which is the default (and it's unlikely anyone changes that).
2230
2231Waste isn't a problem: provided the first input digit isn't 0, the difference
2232between the worst-case input with N digits and the smallest input with N
2233digits is about a factor of B, but B is small compared to BASE so at most
2234one allocated Python digit can remain unused on that count. If
2235N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
2236and adding 1 returns a result 1 larger than necessary. However, that can't
2237happen: whenever B is a power of 2, long_from_binary_base() is called
2238instead, and it's impossible for B**i to be an integer power of 2**15 when
2239B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
2240an exact integer when B is not a power of 2, since B**i has a prime factor
2241other than 2 in that case, but (2**15)**j's only prime factor is 2).
2242
2243The computed result can be too small if the true value of N*log(B)/log(BASE)
2244is a little bit larger than an exact integer, but due to roundoff errors (in
2245computing log(B), log(BASE), their quotient, and/or multiplying that by N)
2246yields a numeric result a little less than that integer. Unfortunately, "how
2247close can a transcendental function get to an integer over some range?"
2248questions are generally theoretically intractable. Computer analysis via
2249continued fractions is practical: expand log(B)/log(BASE) via continued
2250fractions, giving a sequence i/j of "the best" rational approximations. Then
2251j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
2252we can get very close to being in trouble, but very rarely. For example,
225376573 is a denominator in one of the continued-fraction approximations to
2254log(10)/log(2**15), and indeed:
2255
2256 >>> log(10)/log(2**15)*76573
2257 16958.000000654003
2258
2259is very close to an integer. If we were working with IEEE single-precision,
2260rounding errors could kill us. Finding worst cases in IEEE double-precision
2261requires better-than-double-precision log() functions, and Tim didn't bother.
2262Instead the code checks to see whether the allocated space is enough as each
Serhiy Storchaka95949422013-08-27 19:40:23 +03002263new Python digit is added, and copies the whole thing to a larger int if not.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002264This should happen extremely rarely, and in fact I don't have a test case
2265that triggers it(!). Instead the code was tested by artificially allocating
2266just 1 digit at the start, so that the copying code was exercised for every
2267digit beyond the first.
Thomas Wouters477c8d52006-05-27 19:21:47 +00002268***/
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002269 twodigits c; /* current input character */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 Py_ssize_t size_z;
Brett Cannona721aba2016-09-09 14:57:09 -07002271 int digits = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 int i;
2273 int convwidth;
2274 twodigits convmultmax, convmult;
2275 digit *pz, *pzstop;
Brett Cannona721aba2016-09-09 14:57:09 -07002276 const char *scan, *lastdigit;
2277 char prev = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 static double log_base_BASE[37] = {0.0e0,};
2280 static int convwidth_base[37] = {0,};
2281 static twodigits convmultmax_base[37] = {0,};
Thomas Wouters477c8d52006-05-27 19:21:47 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 if (log_base_BASE[base] == 0.0) {
2284 twodigits convmax = base;
2285 int i = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002286
Mark Dickinson22b20182010-05-10 21:27:53 +00002287 log_base_BASE[base] = (log((double)base) /
2288 log((double)PyLong_BASE));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 for (;;) {
2290 twodigits next = convmax * base;
Brett Cannona721aba2016-09-09 14:57:09 -07002291 if (next > PyLong_BASE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 break;
Brett Cannona721aba2016-09-09 14:57:09 -07002293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 convmax = next;
2295 ++i;
2296 }
2297 convmultmax_base[base] = convmax;
2298 assert(i > 0);
2299 convwidth_base[base] = i;
2300 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Find length of the string of numeric characters. */
2303 scan = str;
Brett Cannona721aba2016-09-09 14:57:09 -07002304 lastdigit = str;
2305
2306 while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base || *scan == '_') {
2307 if (*scan == '_') {
2308 if (prev == '_') {
2309 /* Only one underscore allowed. */
2310 str = lastdigit + 1;
2311 goto onError;
2312 }
2313 }
2314 else {
2315 ++digits;
2316 lastdigit = scan;
2317 }
2318 prev = *scan;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 ++scan;
Brett Cannona721aba2016-09-09 14:57:09 -07002320 }
2321 if (prev == '_') {
2322 /* Trailing underscore not allowed. */
2323 /* Set error pointer to first underscore. */
2324 str = lastdigit + 1;
2325 goto onError;
2326 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002327
Serhiy Storchaka95949422013-08-27 19:40:23 +03002328 /* Create an int object that can contain the largest possible
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 * integer with this base and length. Note that there's no
2330 * need to initialize z->ob_digit -- no slot is read up before
2331 * being stored into.
2332 */
Brett Cannona721aba2016-09-09 14:57:09 -07002333 size_z = (Py_ssize_t)(digits * log_base_BASE[base]) + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Uncomment next line to test exceedingly rare copy code */
2335 /* size_z = 1; */
2336 assert(size_z > 0);
2337 z = _PyLong_New(size_z);
Brett Cannona721aba2016-09-09 14:57:09 -07002338 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002340 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 Py_SIZE(z) = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* `convwidth` consecutive input digits are treated as a single
2344 * digit in base `convmultmax`.
2345 */
2346 convwidth = convwidth_base[base];
2347 convmultmax = convmultmax_base[base];
Thomas Wouters477c8d52006-05-27 19:21:47 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Work ;-) */
2350 while (str < scan) {
Brett Cannona721aba2016-09-09 14:57:09 -07002351 if (*str == '_') {
2352 str++;
2353 continue;
2354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* grab up to convwidth digits from the input string */
2356 c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
Brett Cannona721aba2016-09-09 14:57:09 -07002357 for (i = 1; i < convwidth && str != scan; ++str) {
2358 if (*str == '_') {
2359 continue;
2360 }
2361 i++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 c = (twodigits)(c * base +
Mark Dickinson22b20182010-05-10 21:27:53 +00002363 (int)_PyLong_DigitValue[Py_CHARMASK(*str)]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 assert(c < PyLong_BASE);
2365 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 convmult = convmultmax;
2368 /* Calculate the shift only if we couldn't get
2369 * convwidth digits.
2370 */
2371 if (i != convwidth) {
2372 convmult = base;
Brett Cannona721aba2016-09-09 14:57:09 -07002373 for ( ; i > 1; --i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 convmult *= base;
Brett Cannona721aba2016-09-09 14:57:09 -07002375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* Multiply z by convmult, and add c. */
2379 pz = z->ob_digit;
2380 pzstop = pz + Py_SIZE(z);
2381 for (; pz < pzstop; ++pz) {
2382 c += (twodigits)*pz * convmult;
2383 *pz = (digit)(c & PyLong_MASK);
2384 c >>= PyLong_SHIFT;
2385 }
2386 /* carry off the current end? */
2387 if (c) {
2388 assert(c < PyLong_BASE);
2389 if (Py_SIZE(z) < size_z) {
2390 *pz = (digit)c;
2391 ++Py_SIZE(z);
2392 }
2393 else {
2394 PyLongObject *tmp;
2395 /* Extremely rare. Get more space. */
2396 assert(Py_SIZE(z) == size_z);
2397 tmp = _PyLong_New(size_z + 1);
2398 if (tmp == NULL) {
2399 Py_DECREF(z);
2400 return NULL;
2401 }
2402 memcpy(tmp->ob_digit,
2403 z->ob_digit,
2404 sizeof(digit) * size_z);
2405 Py_DECREF(z);
2406 z = tmp;
2407 z->ob_digit[size_z] = (digit)c;
2408 ++size_z;
2409 }
2410 }
2411 }
2412 }
Brett Cannona721aba2016-09-09 14:57:09 -07002413 if (z == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002415 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 if (error_if_nonzero) {
2417 /* reset the base to 0, else the exception message
2418 doesn't make too much sense */
2419 base = 0;
Brett Cannona721aba2016-09-09 14:57:09 -07002420 if (Py_SIZE(z) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 /* there might still be other problems, therefore base
2424 remains zero here for the same reason */
2425 }
Brett Cannona721aba2016-09-09 14:57:09 -07002426 if (str == start) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002428 }
2429 if (sign < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 Py_SIZE(z) = -(Py_SIZE(z));
Brett Cannona721aba2016-09-09 14:57:09 -07002431 }
2432 while (*str && Py_ISSPACE(Py_CHARMASK(*str))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 str++;
Brett Cannona721aba2016-09-09 14:57:09 -07002434 }
2435 if (*str != '\0') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 goto onError;
Brett Cannona721aba2016-09-09 14:57:09 -07002437 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 long_normalize(z);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002439 z = maybe_small_long(z);
Brett Cannona721aba2016-09-09 14:57:09 -07002440 if (z == NULL) {
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002441 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002442 }
2443 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002444 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002445 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002446 return (PyObject *) z;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002447
Mark Dickinson22b20182010-05-10 21:27:53 +00002448 onError:
Brett Cannona721aba2016-09-09 14:57:09 -07002449 if (pend != NULL) {
Serhiy Storchakac6792272013-10-19 21:03:34 +03002450 *pend = (char *)str;
Brett Cannona721aba2016-09-09 14:57:09 -07002451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 Py_XDECREF(z);
2453 slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
2454 strobj = PyUnicode_FromStringAndSize(orig_str, slen);
Brett Cannona721aba2016-09-09 14:57:09 -07002455 if (strobj == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return NULL;
Brett Cannona721aba2016-09-09 14:57:09 -07002457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002459 "invalid literal for int() with base %d: %.200R",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 base, strobj);
2461 Py_DECREF(strobj);
2462 return NULL;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002463}
2464
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002465/* Since PyLong_FromString doesn't have a length parameter,
2466 * check here for possible NULs in the string.
2467 *
2468 * Reports an invalid literal as a bytes object.
2469 */
2470PyObject *
2471_PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
2472{
2473 PyObject *result, *strobj;
2474 char *end = NULL;
2475
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03002476 result = PyLong_FromString(s, &end, base);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002477 if (end == NULL || (result != NULL && end == s + len))
2478 return result;
2479 Py_XDECREF(result);
2480 strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
2481 if (strobj != NULL) {
2482 PyErr_Format(PyExc_ValueError,
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002483 "invalid literal for int() with base %d: %.200R",
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002484 base, strobj);
2485 Py_DECREF(strobj);
2486 }
2487 return NULL;
2488}
2489
Guido van Rossum9e896b32000-04-05 20:11:21 +00002490PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002491PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002492{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002493 PyObject *v, *unicode = PyUnicode_FromWideChar(u, length);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002494 if (unicode == NULL)
2495 return NULL;
2496 v = PyLong_FromUnicodeObject(unicode, base);
2497 Py_DECREF(unicode);
2498 return v;
2499}
2500
2501PyObject *
2502PyLong_FromUnicodeObject(PyObject *u, int base)
2503{
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002504 PyObject *result, *asciidig;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002505 const char *buffer;
2506 char *end = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002507 Py_ssize_t buflen;
Guido van Rossum9e896b32000-04-05 20:11:21 +00002508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002510 if (asciidig == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002512 buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002513 if (buffer == NULL) {
2514 Py_DECREF(asciidig);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002515 if (!PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
2516 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 }
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002518 else {
2519 result = PyLong_FromString(buffer, &end, base);
2520 if (end == NULL || (result != NULL && end == buffer + buflen)) {
2521 Py_DECREF(asciidig);
2522 return result;
2523 }
2524 Py_DECREF(asciidig);
2525 Py_XDECREF(result);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002526 }
Serhiy Storchaka579ddc22013-08-03 21:14:05 +03002527 PyErr_Format(PyExc_ValueError,
2528 "invalid literal for int() with base %d: %.200R",
2529 base, u);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03002530 return NULL;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002531}
2532
Tim Peters9f688bf2000-07-07 15:53:28 +00002533/* forward */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002534static PyLongObject *x_divrem
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 (PyLongObject *, PyLongObject *, PyLongObject **);
Guido van Rossumb43daf72007-08-01 18:08:08 +00002536static PyObject *long_long(PyObject *v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002537
Serhiy Storchaka95949422013-08-27 19:40:23 +03002538/* Int division with remainder, top-level routine */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002539
Guido van Rossume32e0141992-01-19 16:31:05 +00002540static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002541long_divrem(PyLongObject *a, PyLongObject *b,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 PyLongObject **pdiv, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002543{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002544 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (size_b == 0) {
2548 PyErr_SetString(PyExc_ZeroDivisionError,
2549 "integer division or modulo by zero");
2550 return -1;
2551 }
2552 if (size_a < size_b ||
2553 (size_a == size_b &&
2554 a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
2555 /* |a| < |b|. */
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002556 *prem = (PyLongObject *)long_long((PyObject *)a);
2557 if (*prem == NULL) {
Mark Dickinsonb820d7f2016-08-22 12:24:46 +01002558 return -1;
2559 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03002560 Py_INCREF(_PyLong_Zero);
2561 *pdiv = (PyLongObject*)_PyLong_Zero;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return 0;
2563 }
2564 if (size_b == 1) {
2565 digit rem = 0;
2566 z = divrem1(a, b->ob_digit[0], &rem);
2567 if (z == NULL)
2568 return -1;
2569 *prem = (PyLongObject *) PyLong_FromLong((long)rem);
2570 if (*prem == NULL) {
2571 Py_DECREF(z);
2572 return -1;
2573 }
2574 }
2575 else {
2576 z = x_divrem(a, b, prem);
2577 if (z == NULL)
2578 return -1;
2579 }
2580 /* Set the signs.
2581 The quotient z has the sign of a*b;
2582 the remainder r has the sign of a,
2583 so a = b*z + r. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02002584 if ((Py_SIZE(a) < 0) != (Py_SIZE(b) < 0)) {
2585 _PyLong_Negate(&z);
2586 if (z == NULL) {
2587 Py_CLEAR(*prem);
2588 return -1;
2589 }
2590 }
2591 if (Py_SIZE(a) < 0 && Py_SIZE(*prem) != 0) {
2592 _PyLong_Negate(prem);
2593 if (*prem == NULL) {
2594 Py_DECREF(z);
2595 Py_CLEAR(*prem);
2596 return -1;
2597 }
2598 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 *pdiv = maybe_small_long(z);
2600 return 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002601}
2602
Serhiy Storchaka95949422013-08-27 19:40:23 +03002603/* Unsigned int division with remainder -- the algorithm. The arguments v1
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002604 and w1 should satisfy 2 <= Py_ABS(Py_SIZE(w1)) <= Py_ABS(Py_SIZE(v1)). */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002605
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002606static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00002607x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 PyLongObject *v, *w, *a;
2610 Py_ssize_t i, k, size_v, size_w;
2611 int d;
2612 digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
2613 twodigits vv;
2614 sdigit zhi;
2615 stwodigits z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
2618 edn.), section 4.3.1, Algorithm D], except that we don't explicitly
2619 handle the special case when the initial estimate q for a quotient
2620 digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
2621 that won't overflow a digit. */
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /* allocate space; w will also be used to hold the final remainder */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002624 size_v = Py_ABS(Py_SIZE(v1));
2625 size_w = Py_ABS(Py_SIZE(w1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
2627 v = _PyLong_New(size_v+1);
2628 if (v == NULL) {
2629 *prem = NULL;
2630 return NULL;
2631 }
2632 w = _PyLong_New(size_w);
2633 if (w == NULL) {
2634 Py_DECREF(v);
2635 *prem = NULL;
2636 return NULL;
2637 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
2640 shift v1 left by the same amount. Results go into w and v. */
2641 d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
2642 carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
2643 assert(carry == 0);
2644 carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
2645 if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
2646 v->ob_digit[size_v] = carry;
2647 size_v++;
2648 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
2651 at most (and usually exactly) k = size_v - size_w digits. */
2652 k = size_v - size_w;
2653 assert(k >= 0);
2654 a = _PyLong_New(k);
2655 if (a == NULL) {
2656 Py_DECREF(w);
2657 Py_DECREF(v);
2658 *prem = NULL;
2659 return NULL;
2660 }
2661 v0 = v->ob_digit;
2662 w0 = w->ob_digit;
2663 wm1 = w0[size_w-1];
2664 wm2 = w0[size_w-2];
2665 for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
2666 /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
2667 single-digit quotient q, remainder in vk[0:size_w]. */
Tim Peters5af4e6c2002-08-12 02:31:19 +00002668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00002670 Py_DECREF(a);
2671 Py_DECREF(w);
2672 Py_DECREF(v);
2673 *prem = NULL;
2674 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00002675 });
Tim Peters5af4e6c2002-08-12 02:31:19 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 /* estimate quotient digit q; may overestimate by 1 (rare) */
2678 vtop = vk[size_w];
2679 assert(vtop <= wm1);
2680 vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
2681 q = (digit)(vv / wm1);
2682 r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
2683 while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
2684 | vk[size_w-2])) {
2685 --q;
2686 r += wm1;
2687 if (r >= PyLong_BASE)
2688 break;
2689 }
2690 assert(q <= PyLong_BASE);
Tim Peters5af4e6c2002-08-12 02:31:19 +00002691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
2693 zhi = 0;
2694 for (i = 0; i < size_w; ++i) {
2695 /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
2696 -PyLong_BASE * q <= z < PyLong_BASE */
2697 z = (sdigit)vk[i] + zhi -
2698 (stwodigits)q * (stwodigits)w0[i];
2699 vk[i] = (digit)z & PyLong_MASK;
2700 zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
Mark Dickinson22b20182010-05-10 21:27:53 +00002701 z, PyLong_SHIFT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 /* add w back if q was too large (this branch taken rarely) */
2705 assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
2706 if ((sdigit)vtop + zhi < 0) {
2707 carry = 0;
2708 for (i = 0; i < size_w; ++i) {
2709 carry += vk[i] + w0[i];
2710 vk[i] = carry & PyLong_MASK;
2711 carry >>= PyLong_SHIFT;
2712 }
2713 --q;
2714 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00002715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 /* store quotient digit */
2717 assert(q < PyLong_BASE);
2718 *--ak = q;
2719 }
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 /* unshift remainder; we reuse w to store the result */
2722 carry = v_rshift(w0, v0, size_w, d);
2723 assert(carry==0);
2724 Py_DECREF(v);
Mark Dickinson17e4fdd2009-03-23 18:44:57 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 *prem = long_normalize(w);
2727 return long_normalize(a);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002728}
2729
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002730/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
2731 abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
2732 rounded to DBL_MANT_DIG significant bits using round-half-to-even.
2733 If a == 0, return 0.0 and set *e = 0. If the resulting exponent
2734 e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
2735 -1.0. */
2736
2737/* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
2738#if DBL_MANT_DIG == 53
2739#define EXP2_DBL_MANT_DIG 9007199254740992.0
2740#else
2741#define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
2742#endif
2743
2744double
2745_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
2746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
2748 /* See below for why x_digits is always large enough. */
2749 digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
2750 double dx;
2751 /* Correction term for round-half-to-even rounding. For a digit x,
2752 "x + half_even_correction[x & 7]" gives x rounded to the nearest
2753 multiple of 4, rounding ties to a multiple of 8. */
2754 static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002755
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002756 a_size = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 if (a_size == 0) {
2758 /* Special case for 0: significand 0.0, exponent 0. */
2759 *e = 0;
2760 return 0.0;
2761 }
2762 a_bits = bits_in_digit(a->ob_digit[a_size-1]);
2763 /* The following is an overflow-free version of the check
2764 "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
2765 if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
2766 (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
2767 a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
Mark Dickinson22b20182010-05-10 21:27:53 +00002768 goto overflow;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
2772 (shifting left if a_bits <= DBL_MANT_DIG + 2).
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 Number of digits needed for result: write // for floor division.
2775 Then if shifting left, we end up using
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 digits. If shifting right, we use
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
2784 the inequalities
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
2787 m // PyLong_SHIFT - n // PyLong_SHIFT <=
2788 1 + (m - n - 1) // PyLong_SHIFT,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 valid for any integers m and n, we find that x_size satisfies
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 in both cases.
2795 */
2796 if (a_bits <= DBL_MANT_DIG + 2) {
2797 shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
2798 shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
2799 x_size = 0;
2800 while (x_size < shift_digits)
2801 x_digits[x_size++] = 0;
2802 rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
2803 (int)shift_bits);
2804 x_size += a_size;
2805 x_digits[x_size++] = rem;
2806 }
2807 else {
2808 shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
2809 shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
2810 rem = v_rshift(x_digits, a->ob_digit + shift_digits,
2811 a_size - shift_digits, (int)shift_bits);
2812 x_size = a_size - shift_digits;
2813 /* For correct rounding below, we need the least significant
2814 bit of x to be 'sticky' for this shift: if any of the bits
2815 shifted out was nonzero, we set the least significant bit
2816 of x. */
2817 if (rem)
2818 x_digits[0] |= 1;
2819 else
2820 while (shift_digits > 0)
2821 if (a->ob_digit[--shift_digits]) {
2822 x_digits[0] |= 1;
2823 break;
2824 }
2825 }
Victor Stinner63941882011-09-29 00:42:28 +02002826 assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 /* Round, and convert to double. */
2829 x_digits[0] += half_even_correction[x_digits[0] & 7];
2830 dx = x_digits[--x_size];
2831 while (x_size > 0)
2832 dx = dx * PyLong_BASE + x_digits[--x_size];
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 /* Rescale; make correction if result is 1.0. */
2835 dx /= 4.0 * EXP2_DBL_MANT_DIG;
2836 if (dx == 1.0) {
2837 if (a_bits == PY_SSIZE_T_MAX)
2838 goto overflow;
2839 dx = 0.5;
2840 a_bits += 1;
2841 }
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 *e = a_bits;
2844 return Py_SIZE(a) < 0 ? -dx : dx;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002845
2846 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 /* exponent > PY_SSIZE_T_MAX */
2848 PyErr_SetString(PyExc_OverflowError,
2849 "huge integer: number of bits overflows a Py_ssize_t");
2850 *e = 0;
2851 return -1.0;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002852}
2853
Serhiy Storchaka95949422013-08-27 19:40:23 +03002854/* Get a C double from an int object. Rounds to the nearest double,
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002855 using the round-half-to-even rule in the case of a tie. */
2856
2857double
2858PyLong_AsDouble(PyObject *v)
2859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 Py_ssize_t exponent;
2861 double x;
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002862
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002863 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 PyErr_BadInternalCall();
2865 return -1.0;
2866 }
Nadeem Vawda3d5881e2011-09-07 21:40:26 +02002867 if (!PyLong_Check(v)) {
2868 PyErr_SetString(PyExc_TypeError, "an integer is required");
2869 return -1.0;
2870 }
Yury Selivanov186c30b2016-02-05 19:40:01 -05002871 if (Py_ABS(Py_SIZE(v)) <= 1) {
Yury Selivanova0fcaca2016-02-06 12:21:33 -05002872 /* Fast path; single digit long (31 bits) will cast safely
Mark Dickinson1dc3c892016-08-21 10:33:36 +01002873 to double. This improves performance of FP/long operations
2874 by 20%.
Yury Selivanov186c30b2016-02-05 19:40:01 -05002875 */
2876 return (double)MEDIUM_VALUE((PyLongObject *)v);
2877 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 x = _PyLong_Frexp((PyLongObject *)v, &exponent);
2879 if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
2880 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson02515f72013-08-03 12:08:22 +01002881 "int too large to convert to float");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 return -1.0;
2883 }
2884 return ldexp(x, (int)exponent);
Mark Dickinson6ecd9e52010-01-02 15:33:56 +00002885}
2886
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002887/* Methods */
2888
2889static void
Tim Peters9f688bf2000-07-07 15:53:28 +00002890long_dealloc(PyObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 Py_TYPE(v)->tp_free(v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002893}
2894
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002895static int
Tim Peters9f688bf2000-07-07 15:53:28 +00002896long_compare(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 Py_ssize_t sign;
Tim Peters5af4e6c2002-08-12 02:31:19 +00002899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 if (Py_SIZE(a) != Py_SIZE(b)) {
2901 sign = Py_SIZE(a) - Py_SIZE(b);
2902 }
2903 else {
Victor Stinner45e8e2f2014-05-14 17:24:35 +02002904 Py_ssize_t i = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002905 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
2906 ;
2907 if (i < 0)
2908 sign = 0;
2909 else {
2910 sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
2911 if (Py_SIZE(a) < 0)
2912 sign = -sign;
2913 }
2914 }
2915 return sign < 0 ? -1 : sign > 0 ? 1 : 0;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00002916}
2917
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002918#define TEST_COND(cond) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +00002920
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002921static PyObject *
2922long_richcompare(PyObject *self, PyObject *other, int op)
2923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002924 int result;
2925 PyObject *v;
2926 CHECK_BINOP(self, other);
2927 if (self == other)
2928 result = 0;
2929 else
2930 result = long_compare((PyLongObject*)self, (PyLongObject*)other);
2931 /* Convert the return value to a Boolean */
2932 switch (op) {
2933 case Py_EQ:
2934 v = TEST_COND(result == 0);
2935 break;
2936 case Py_NE:
2937 v = TEST_COND(result != 0);
2938 break;
2939 case Py_LE:
2940 v = TEST_COND(result <= 0);
2941 break;
2942 case Py_GE:
2943 v = TEST_COND(result >= 0);
2944 break;
2945 case Py_LT:
2946 v = TEST_COND(result == -1);
2947 break;
2948 case Py_GT:
2949 v = TEST_COND(result == 1);
2950 break;
2951 default:
2952 PyErr_BadArgument();
2953 return NULL;
2954 }
2955 Py_INCREF(v);
2956 return v;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002957}
2958
Benjamin Peterson8f67d082010-10-17 20:54:53 +00002959static Py_hash_t
Tim Peters9f688bf2000-07-07 15:53:28 +00002960long_hash(PyLongObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +00002961{
Benjamin Peterson8035bc52010-10-23 16:20:50 +00002962 Py_uhash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 Py_ssize_t i;
2964 int sign;
Guido van Rossum9bfef441993-03-29 10:43:31 +00002965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 i = Py_SIZE(v);
2967 switch(i) {
2968 case -1: return v->ob_digit[0]==1 ? -2 : -(sdigit)v->ob_digit[0];
2969 case 0: return 0;
2970 case 1: return v->ob_digit[0];
2971 }
2972 sign = 1;
2973 x = 0;
2974 if (i < 0) {
2975 sign = -1;
2976 i = -(i);
2977 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 while (--i >= 0) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00002979 /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
2980 want to compute x * 2**PyLong_SHIFT + v->ob_digit[i] modulo
2981 _PyHASH_MODULUS.
2982
2983 The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
2984 amounts to a rotation of the bits of x. To see this, write
2985
2986 x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
2987
2988 where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
2989 PyLong_SHIFT bits of x (those that are shifted out of the
2990 original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
2991 _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
2992 bits of x, shifted up. Then since 2**_PyHASH_BITS is
2993 congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
2994 congruent to y modulo _PyHASH_MODULUS. So
2995
2996 x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
2997
2998 The right-hand side is just the result of rotating the
2999 _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
3000 not all _PyHASH_BITS bits of x are 1s, the same is true
3001 after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
3002 the reduction of x*2**PyLong_SHIFT modulo
3003 _PyHASH_MODULUS. */
3004 x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
3005 (x >> (_PyHASH_BITS - PyLong_SHIFT));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 x += v->ob_digit[i];
Mark Dickinsondc787d22010-05-23 13:33:13 +00003007 if (x >= _PyHASH_MODULUS)
3008 x -= _PyHASH_MODULUS;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 }
3010 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +00003011 if (x == (Py_uhash_t)-1)
3012 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +00003013 return (Py_hash_t)x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00003014}
3015
3016
Serhiy Storchaka95949422013-08-27 19:40:23 +03003017/* Add the absolute values of two integers. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003018
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003019static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003020x_add(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003021{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003022 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 PyLongObject *z;
3024 Py_ssize_t i;
3025 digit carry = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027 /* Ensure a is the larger of the two: */
3028 if (size_a < size_b) {
3029 { PyLongObject *temp = a; a = b; b = temp; }
3030 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003031 size_a = size_b;
3032 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 }
3034 z = _PyLong_New(size_a+1);
3035 if (z == NULL)
3036 return NULL;
3037 for (i = 0; i < size_b; ++i) {
3038 carry += a->ob_digit[i] + b->ob_digit[i];
3039 z->ob_digit[i] = carry & PyLong_MASK;
3040 carry >>= PyLong_SHIFT;
3041 }
3042 for (; i < size_a; ++i) {
3043 carry += a->ob_digit[i];
3044 z->ob_digit[i] = carry & PyLong_MASK;
3045 carry >>= PyLong_SHIFT;
3046 }
3047 z->ob_digit[i] = carry;
3048 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003049}
3050
3051/* Subtract the absolute values of two integers. */
3052
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003053static PyLongObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00003054x_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003055{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003056 Py_ssize_t size_a = Py_ABS(Py_SIZE(a)), size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057 PyLongObject *z;
3058 Py_ssize_t i;
3059 int sign = 1;
3060 digit borrow = 0;
Tim Peters69c2de32001-09-11 22:31:33 +00003061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 /* Ensure a is the larger of the two: */
3063 if (size_a < size_b) {
3064 sign = -1;
3065 { PyLongObject *temp = a; a = b; b = temp; }
3066 { Py_ssize_t size_temp = size_a;
Mark Dickinson22b20182010-05-10 21:27:53 +00003067 size_a = size_b;
3068 size_b = size_temp; }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 }
3070 else if (size_a == size_b) {
3071 /* Find highest digit where a and b differ: */
3072 i = size_a;
3073 while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
3074 ;
3075 if (i < 0)
3076 return (PyLongObject *)PyLong_FromLong(0);
3077 if (a->ob_digit[i] < b->ob_digit[i]) {
3078 sign = -1;
3079 { PyLongObject *temp = a; a = b; b = temp; }
3080 }
3081 size_a = size_b = i+1;
3082 }
3083 z = _PyLong_New(size_a);
3084 if (z == NULL)
3085 return NULL;
3086 for (i = 0; i < size_b; ++i) {
3087 /* The following assumes unsigned arithmetic
3088 works module 2**N for some N>PyLong_SHIFT. */
3089 borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
3090 z->ob_digit[i] = borrow & PyLong_MASK;
3091 borrow >>= PyLong_SHIFT;
3092 borrow &= 1; /* Keep only one sign bit */
3093 }
3094 for (; i < size_a; ++i) {
3095 borrow = a->ob_digit[i] - borrow;
3096 z->ob_digit[i] = borrow & PyLong_MASK;
3097 borrow >>= PyLong_SHIFT;
3098 borrow &= 1; /* Keep only one sign bit */
3099 }
3100 assert(borrow == 0);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003101 if (sign < 0) {
Victor Stinner8bcf3122016-08-17 19:48:33 +02003102 Py_SIZE(z) = -Py_SIZE(z);
Victor Stinner8aed6f12013-07-17 22:31:17 +02003103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 return long_normalize(z);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003105}
3106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003107static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003108long_add(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 PyLongObject *z;
Tim Peters69c2de32001-09-11 22:31:33 +00003111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003113
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003114 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003115 return PyLong_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
3117 if (Py_SIZE(a) < 0) {
3118 if (Py_SIZE(b) < 0) {
3119 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003120 if (z != NULL) {
3121 /* x_add received at least one multiple-digit int,
3122 and thus z must be a multiple-digit int.
3123 That also means z is not an element of
3124 small_ints, so negating it in-place is safe. */
3125 assert(Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
3129 else
3130 z = x_sub(b, a);
3131 }
3132 else {
3133 if (Py_SIZE(b) < 0)
3134 z = x_sub(a, b);
3135 else
3136 z = x_add(a, b);
3137 }
3138 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003139}
3140
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003141static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003142long_sub(PyLongObject *a, PyLongObject *b)
Guido van Rossum4c260ff1992-01-14 18:36:43 +00003143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00003147
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003148 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Mark Dickinsonc1c4a642016-09-17 20:01:56 +01003149 return PyLong_FromLong(MEDIUM_VALUE(a) - MEDIUM_VALUE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 }
3151 if (Py_SIZE(a) < 0) {
3152 if (Py_SIZE(b) < 0)
3153 z = x_sub(a, b);
3154 else
3155 z = x_add(a, b);
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003156 if (z != NULL) {
3157 assert(Py_SIZE(z) == 0 || Py_REFCNT(z) == 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 Py_SIZE(z) = -(Py_SIZE(z));
Serhiy Storchakae63e5d62016-06-04 00:06:45 +03003159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 }
3161 else {
3162 if (Py_SIZE(b) < 0)
3163 z = x_add(a, b);
3164 else
3165 z = x_sub(a, b);
3166 }
3167 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003168}
3169
Tim Peters5af4e6c2002-08-12 02:31:19 +00003170/* Grade school multiplication, ignoring the signs.
3171 * Returns the absolute value of the product, or NULL if error.
3172 */
3173static PyLongObject *
3174x_mul(PyLongObject *a, PyLongObject *b)
Neil Schemenauerba872e22001-01-04 01:46:03 +00003175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003177 Py_ssize_t size_a = Py_ABS(Py_SIZE(a));
3178 Py_ssize_t size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 Py_ssize_t i;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 z = _PyLong_New(size_a + size_b);
3182 if (z == NULL)
3183 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003185 memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
3186 if (a == b) {
3187 /* Efficient squaring per HAC, Algorithm 14.16:
3188 * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
3189 * Gives slightly less than a 2x speedup when a == b,
3190 * via exploiting that each entry in the multiplication
3191 * pyramid appears twice (except for the size_a squares).
3192 */
3193 for (i = 0; i < size_a; ++i) {
3194 twodigits carry;
3195 twodigits f = a->ob_digit[i];
3196 digit *pz = z->ob_digit + (i << 1);
3197 digit *pa = a->ob_digit + i + 1;
3198 digit *paend = a->ob_digit + size_a;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003201 Py_DECREF(z);
3202 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003203 });
Tim Peters0973b992004-08-29 22:16:50 +00003204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003205 carry = *pz + f * f;
3206 *pz++ = (digit)(carry & PyLong_MASK);
3207 carry >>= PyLong_SHIFT;
3208 assert(carry <= PyLong_MASK);
Tim Peters0973b992004-08-29 22:16:50 +00003209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 /* Now f is added in twice in each column of the
3211 * pyramid it appears. Same as adding f<<1 once.
3212 */
3213 f <<= 1;
3214 while (pa < paend) {
3215 carry += *pz + *pa++ * f;
3216 *pz++ = (digit)(carry & PyLong_MASK);
3217 carry >>= PyLong_SHIFT;
3218 assert(carry <= (PyLong_MASK << 1));
3219 }
3220 if (carry) {
3221 carry += *pz;
3222 *pz++ = (digit)(carry & PyLong_MASK);
3223 carry >>= PyLong_SHIFT;
3224 }
3225 if (carry)
3226 *pz += (digit)(carry & PyLong_MASK);
3227 assert((carry >> PyLong_SHIFT) == 0);
3228 }
3229 }
Serhiy Storchaka95949422013-08-27 19:40:23 +03003230 else { /* a is not the same as b -- gradeschool int mult */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 for (i = 0; i < size_a; ++i) {
3232 twodigits carry = 0;
3233 twodigits f = a->ob_digit[i];
3234 digit *pz = z->ob_digit + i;
3235 digit *pb = b->ob_digit;
3236 digit *pbend = b->ob_digit + size_b;
Tim Peters0973b992004-08-29 22:16:50 +00003237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003238 SIGCHECK({
Mark Dickinson22b20182010-05-10 21:27:53 +00003239 Py_DECREF(z);
3240 return NULL;
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00003241 });
Tim Peters0973b992004-08-29 22:16:50 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 while (pb < pbend) {
3244 carry += *pz + *pb++ * f;
3245 *pz++ = (digit)(carry & PyLong_MASK);
3246 carry >>= PyLong_SHIFT;
3247 assert(carry <= PyLong_MASK);
3248 }
3249 if (carry)
3250 *pz += (digit)(carry & PyLong_MASK);
3251 assert((carry >> PyLong_SHIFT) == 0);
3252 }
3253 }
3254 return long_normalize(z);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003255}
3256
3257/* A helper for Karatsuba multiplication (k_mul).
Serhiy Storchaka95949422013-08-27 19:40:23 +03003258 Takes an int "n" and an integer "size" representing the place to
Tim Peters5af4e6c2002-08-12 02:31:19 +00003259 split, and sets low and high such that abs(n) == (high << size) + low,
3260 viewing the shift as being by digits. The sign bit is ignored, and
3261 the return values are >= 0.
3262 Returns 0 on success, -1 on failure.
3263*/
3264static int
Mark Dickinson22b20182010-05-10 21:27:53 +00003265kmul_split(PyLongObject *n,
3266 Py_ssize_t size,
3267 PyLongObject **high,
3268 PyLongObject **low)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 PyLongObject *hi, *lo;
3271 Py_ssize_t size_lo, size_hi;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003272 const Py_ssize_t size_n = Py_ABS(Py_SIZE(n));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003273
Victor Stinner640c35c2013-06-04 23:14:37 +02003274 size_lo = Py_MIN(size_n, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 size_hi = size_n - size_lo;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if ((hi = _PyLong_New(size_hi)) == NULL)
3278 return -1;
3279 if ((lo = _PyLong_New(size_lo)) == NULL) {
3280 Py_DECREF(hi);
3281 return -1;
3282 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
3285 memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 *high = long_normalize(hi);
3288 *low = long_normalize(lo);
3289 return 0;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003290}
3291
Tim Peters60004642002-08-12 22:01:34 +00003292static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
3293
Tim Peters5af4e6c2002-08-12 02:31:19 +00003294/* Karatsuba multiplication. Ignores the input signs, and returns the
3295 * absolute value of the product (or NULL if error).
3296 * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
3297 */
3298static PyLongObject *
3299k_mul(PyLongObject *a, PyLongObject *b)
3300{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003301 Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3302 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 PyLongObject *ah = NULL;
3304 PyLongObject *al = NULL;
3305 PyLongObject *bh = NULL;
3306 PyLongObject *bl = NULL;
3307 PyLongObject *ret = NULL;
3308 PyLongObject *t1, *t2, *t3;
3309 Py_ssize_t shift; /* the number of digits we split off */
3310 Py_ssize_t i;
Tim Peters738eda72002-08-12 15:08:20 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
3313 * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
3314 * Then the original product is
3315 * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
3316 * By picking X to be a power of 2, "*X" is just shifting, and it's
3317 * been reduced to 3 multiplies on numbers half the size.
3318 */
Tim Peters5af4e6c2002-08-12 02:31:19 +00003319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 /* We want to split based on the larger number; fiddle so that b
3321 * is largest.
3322 */
3323 if (asize > bsize) {
3324 t1 = a;
3325 a = b;
3326 b = t1;
Tim Peters738eda72002-08-12 15:08:20 +00003327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 i = asize;
3329 asize = bsize;
3330 bsize = i;
3331 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 /* Use gradeschool math when either number is too small. */
3334 i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
3335 if (asize <= i) {
3336 if (asize == 0)
3337 return (PyLongObject *)PyLong_FromLong(0);
3338 else
3339 return x_mul(a, b);
3340 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00003341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 /* If a is small compared to b, splitting on b gives a degenerate
3343 * case with ah==0, and Karatsuba may be (even much) less efficient
3344 * than "grade school" then. However, we can still win, by viewing
3345 * b as a string of "big digits", each of width a->ob_size. That
3346 * leads to a sequence of balanced calls to k_mul.
3347 */
3348 if (2 * asize <= bsize)
3349 return k_lopsided_mul(a, b);
Tim Peters60004642002-08-12 22:01:34 +00003350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 /* Split a & b into hi & lo pieces. */
3352 shift = bsize >> 1;
3353 if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
3354 assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
Tim Petersd6974a52002-08-13 20:37:51 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 if (a == b) {
3357 bh = ah;
3358 bl = al;
3359 Py_INCREF(bh);
3360 Py_INCREF(bl);
3361 }
3362 else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003364 /* The plan:
3365 * 1. Allocate result space (asize + bsize digits: that's always
3366 * enough).
3367 * 2. Compute ah*bh, and copy into result at 2*shift.
3368 * 3. Compute al*bl, and copy into result at 0. Note that this
3369 * can't overlap with #2.
3370 * 4. Subtract al*bl from the result, starting at shift. This may
3371 * underflow (borrow out of the high digit), but we don't care:
3372 * we're effectively doing unsigned arithmetic mod
3373 * BASE**(sizea + sizeb), and so long as the *final* result fits,
3374 * borrows and carries out of the high digit can be ignored.
3375 * 5. Subtract ah*bh from the result, starting at shift.
3376 * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
3377 * at shift.
3378 */
Tim Petersd64c1de2002-08-12 17:36:03 +00003379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003380 /* 1. Allocate result space. */
3381 ret = _PyLong_New(asize + bsize);
3382 if (ret == NULL) goto fail;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003383#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* Fill with trash, to catch reference to uninitialized digits. */
3385 memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003386#endif
Tim Peters44121a62002-08-12 06:17:58 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 /* 2. t1 <- ah*bh, and copy into high digits of result. */
3389 if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
3390 assert(Py_SIZE(t1) >= 0);
3391 assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
3392 memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
3393 Py_SIZE(t1) * sizeof(digit));
Tim Peters738eda72002-08-12 15:08:20 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 /* Zero-out the digits higher than the ah*bh copy. */
3396 i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
3397 if (i)
3398 memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
3399 i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 /* 3. t2 <- al*bl, and copy into the low digits. */
3402 if ((t2 = k_mul(al, bl)) == NULL) {
3403 Py_DECREF(t1);
3404 goto fail;
3405 }
3406 assert(Py_SIZE(t2) >= 0);
3407 assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
3408 memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 /* Zero out remaining digits. */
3411 i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
3412 if (i)
3413 memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
Tim Peters5af4e6c2002-08-12 02:31:19 +00003414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
3416 * because it's fresher in cache.
3417 */
3418 i = Py_SIZE(ret) - shift; /* # digits after shift */
3419 (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
3420 Py_DECREF(t2);
Tim Peters738eda72002-08-12 15:08:20 +00003421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003422 (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
3423 Py_DECREF(t1);
Tim Peters738eda72002-08-12 15:08:20 +00003424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
3426 if ((t1 = x_add(ah, al)) == NULL) goto fail;
3427 Py_DECREF(ah);
3428 Py_DECREF(al);
3429 ah = al = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 if (a == b) {
3432 t2 = t1;
3433 Py_INCREF(t2);
3434 }
3435 else if ((t2 = x_add(bh, bl)) == NULL) {
3436 Py_DECREF(t1);
3437 goto fail;
3438 }
3439 Py_DECREF(bh);
3440 Py_DECREF(bl);
3441 bh = bl = NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 t3 = k_mul(t1, t2);
3444 Py_DECREF(t1);
3445 Py_DECREF(t2);
3446 if (t3 == NULL) goto fail;
3447 assert(Py_SIZE(t3) >= 0);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 /* Add t3. It's not obvious why we can't run out of room here.
3450 * See the (*) comment after this function.
3451 */
3452 (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
3453 Py_DECREF(t3);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003455 return long_normalize(ret);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003456
Mark Dickinson22b20182010-05-10 21:27:53 +00003457 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 Py_XDECREF(ret);
3459 Py_XDECREF(ah);
3460 Py_XDECREF(al);
3461 Py_XDECREF(bh);
3462 Py_XDECREF(bl);
3463 return NULL;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003464}
3465
Tim Petersd6974a52002-08-13 20:37:51 +00003466/* (*) Why adding t3 can't "run out of room" above.
3467
Tim Petersab86c2b2002-08-15 20:06:00 +00003468Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
3469to start with:
Tim Petersd6974a52002-08-13 20:37:51 +00003470
Tim Petersab86c2b2002-08-15 20:06:00 +000034711. For any integer i, i = c(i/2) + f(i/2). In particular,
3472 bsize = c(bsize/2) + f(bsize/2).
34732. shift = f(bsize/2)
34743. asize <= bsize
34754. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
3476 routine, so asize > bsize/2 >= f(bsize/2) in this routine.
Tim Petersd6974a52002-08-13 20:37:51 +00003477
Tim Petersab86c2b2002-08-15 20:06:00 +00003478We allocated asize + bsize result digits, and add t3 into them at an offset
3479of shift. This leaves asize+bsize-shift allocated digit positions for t3
3480to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
3481asize + c(bsize/2) available digit positions.
Tim Petersd6974a52002-08-13 20:37:51 +00003482
Tim Petersab86c2b2002-08-15 20:06:00 +00003483bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
3484at most c(bsize/2) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003485
Tim Petersab86c2b2002-08-15 20:06:00 +00003486If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
3487digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
3488most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
Tim Petersd6974a52002-08-13 20:37:51 +00003489
Tim Petersab86c2b2002-08-15 20:06:00 +00003490The product (ah+al)*(bh+bl) therefore has at most
Tim Petersd6974a52002-08-13 20:37:51 +00003491
Tim Petersab86c2b2002-08-15 20:06:00 +00003492 c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
Tim Petersd6974a52002-08-13 20:37:51 +00003493
Tim Petersab86c2b2002-08-15 20:06:00 +00003494and we have asize + c(bsize/2) available digit positions. We need to show
3495this is always enough. An instance of c(bsize/2) cancels out in both, so
3496the question reduces to whether asize digits is enough to hold
3497(asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
3498then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
3499asize 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 +00003500digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
Tim Petersab86c2b2002-08-15 20:06:00 +00003501asize == bsize, then we're asking whether bsize digits is enough to hold
Tim Peterse417de02002-08-15 20:10:45 +00003502c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
3503is enough to hold 2 bits. This is so if bsize >= 2, which holds because
3504bsize >= KARATSUBA_CUTOFF >= 2.
Tim Peters8e966ee2002-08-14 16:36:23 +00003505
Tim Peters48d52c02002-08-14 17:07:32 +00003506Note that since there's always enough room for (ah+al)*(bh+bl), and that's
3507clearly >= each of ah*bh and al*bl, there's always enough room to subtract
3508ah*bh and al*bl too.
Tim Petersd6974a52002-08-13 20:37:51 +00003509*/
3510
Tim Peters60004642002-08-12 22:01:34 +00003511/* b has at least twice the digits of a, and a is big enough that Karatsuba
3512 * would pay off *if* the inputs had balanced sizes. View b as a sequence
3513 * of slices, each with a->ob_size digits, and multiply the slices by a,
3514 * one at a time. This gives k_mul balanced inputs to work with, and is
3515 * also cache-friendly (we compute one double-width slice of the result
Ezio Melotti42da6632011-03-15 05:18:48 +02003516 * at a time, then move on, never backtracking except for the helpful
Tim Peters60004642002-08-12 22:01:34 +00003517 * single-width slice overlap between successive partial sums).
3518 */
3519static PyLongObject *
3520k_lopsided_mul(PyLongObject *a, PyLongObject *b)
3521{
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003522 const Py_ssize_t asize = Py_ABS(Py_SIZE(a));
3523 Py_ssize_t bsize = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003524 Py_ssize_t nbdone; /* # of b digits already multiplied */
3525 PyLongObject *ret;
3526 PyLongObject *bslice = NULL;
Tim Peters60004642002-08-12 22:01:34 +00003527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 assert(asize > KARATSUBA_CUTOFF);
3529 assert(2 * asize <= bsize);
Tim Peters60004642002-08-12 22:01:34 +00003530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 /* Allocate result space, and zero it out. */
3532 ret = _PyLong_New(asize + bsize);
3533 if (ret == NULL)
3534 return NULL;
3535 memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
Tim Peters60004642002-08-12 22:01:34 +00003536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 /* Successive slices of b are copied into bslice. */
3538 bslice = _PyLong_New(asize);
3539 if (bslice == NULL)
3540 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 nbdone = 0;
3543 while (bsize > 0) {
3544 PyLongObject *product;
Victor Stinner640c35c2013-06-04 23:14:37 +02003545 const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
Tim Peters60004642002-08-12 22:01:34 +00003546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003547 /* Multiply the next slice of b by a. */
3548 memcpy(bslice->ob_digit, b->ob_digit + nbdone,
3549 nbtouse * sizeof(digit));
3550 Py_SIZE(bslice) = nbtouse;
3551 product = k_mul(a, bslice);
3552 if (product == NULL)
3553 goto fail;
Tim Peters60004642002-08-12 22:01:34 +00003554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 /* Add into result. */
3556 (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
3557 product->ob_digit, Py_SIZE(product));
3558 Py_DECREF(product);
Tim Peters60004642002-08-12 22:01:34 +00003559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003560 bsize -= nbtouse;
3561 nbdone += nbtouse;
3562 }
Tim Peters60004642002-08-12 22:01:34 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 Py_DECREF(bslice);
3565 return long_normalize(ret);
Tim Peters60004642002-08-12 22:01:34 +00003566
Mark Dickinson22b20182010-05-10 21:27:53 +00003567 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 Py_DECREF(ret);
3569 Py_XDECREF(bslice);
3570 return NULL;
Tim Peters60004642002-08-12 22:01:34 +00003571}
Tim Peters5af4e6c2002-08-12 02:31:19 +00003572
3573static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003574long_mul(PyLongObject *a, PyLongObject *b)
Tim Peters5af4e6c2002-08-12 02:31:19 +00003575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 CHECK_BINOP(a, b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 /* fast path for single-digit multiplication */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003581 if (Py_ABS(Py_SIZE(a)) <= 1 && Py_ABS(Py_SIZE(b)) <= 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 stwodigits v = (stwodigits)(MEDIUM_VALUE(a)) * MEDIUM_VALUE(b);
Benjamin Petersonaf580df2016-09-06 10:46:49 -07003583 return PyLong_FromLongLong((long long)v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 z = k_mul(a, b);
3587 /* Negate if exactly one of the inputs is negative. */
Victor Stinner8aed6f12013-07-17 22:31:17 +02003588 if (((Py_SIZE(a) ^ Py_SIZE(b)) < 0) && z) {
3589 _PyLong_Negate(&z);
3590 if (z == NULL)
3591 return NULL;
3592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003594}
3595
Yury Selivanove0b23092016-02-11 10:26:27 -05003596/* Fast modulo division for single-digit longs. */
3597static PyObject *
3598fast_mod(PyLongObject *a, PyLongObject *b)
3599{
3600 sdigit left = a->ob_digit[0];
3601 sdigit right = b->ob_digit[0];
3602 sdigit mod;
3603
3604 assert(Py_ABS(Py_SIZE(a)) == 1);
3605 assert(Py_ABS(Py_SIZE(b)) == 1);
3606
3607 if (Py_SIZE(a) == Py_SIZE(b)) {
3608 /* 'a' and 'b' have the same sign. */
3609 mod = left % right;
3610 }
3611 else {
3612 /* Either 'a' or 'b' is negative. */
3613 mod = right - 1 - (left - 1) % right;
3614 }
3615
Victor Stinnerf963c132016-03-23 18:36:54 +01003616 return PyLong_FromLong(mod * (sdigit)Py_SIZE(b));
Yury Selivanove0b23092016-02-11 10:26:27 -05003617}
3618
3619/* Fast floor division for single-digit longs. */
3620static PyObject *
3621fast_floor_div(PyLongObject *a, PyLongObject *b)
3622{
3623 sdigit left = a->ob_digit[0];
3624 sdigit right = b->ob_digit[0];
3625 sdigit div;
3626
3627 assert(Py_ABS(Py_SIZE(a)) == 1);
3628 assert(Py_ABS(Py_SIZE(b)) == 1);
3629
3630 if (Py_SIZE(a) == Py_SIZE(b)) {
3631 /* 'a' and 'b' have the same sign. */
3632 div = left / right;
3633 }
3634 else {
3635 /* Either 'a' or 'b' is negative. */
3636 div = -1 - (left - 1) / right;
3637 }
3638
3639 return PyLong_FromLong(div);
3640}
3641
Guido van Rossume32e0141992-01-19 16:31:05 +00003642/* The / and % operators are now defined in terms of divmod().
3643 The expression a mod b has the value a - b*floor(a/b).
3644 The long_divrem function gives the remainder after division of
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003645 |a| by |b|, with the sign of a. This is also expressed
3646 as a - b*trunc(a/b), if trunc truncates towards zero.
3647 Some examples:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 a b a rem b a mod b
3649 13 10 3 3
3650 -13 10 -3 7
3651 13 -10 3 -7
3652 -13 -10 -3 -3
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003653 So, to get from rem to mod, we have to add b if a and b
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00003654 have different signs. We then subtract one from the 'div'
3655 part of the outcome to keep the invariant intact. */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00003656
Tim Peters47e52ee2004-08-30 02:44:38 +00003657/* Compute
3658 * *pdiv, *pmod = divmod(v, w)
3659 * NULL can be passed for pdiv or pmod, in which case that part of
3660 * the result is simply thrown away. The caller owns a reference to
3661 * each of these it requests (does not pass NULL for).
3662 */
Guido van Rossume32e0141992-01-19 16:31:05 +00003663static int
Tim Peters5af4e6c2002-08-12 02:31:19 +00003664l_divmod(PyLongObject *v, PyLongObject *w,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003665 PyLongObject **pdiv, PyLongObject **pmod)
Guido van Rossume32e0141992-01-19 16:31:05 +00003666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003667 PyLongObject *div, *mod;
Tim Peters5af4e6c2002-08-12 02:31:19 +00003668
Yury Selivanove0b23092016-02-11 10:26:27 -05003669 if (Py_ABS(Py_SIZE(v)) == 1 && Py_ABS(Py_SIZE(w)) == 1) {
3670 /* Fast path for single-digit longs */
3671 div = NULL;
3672 if (pdiv != NULL) {
3673 div = (PyLongObject *)fast_floor_div(v, w);
3674 if (div == NULL) {
3675 return -1;
3676 }
3677 }
3678 if (pmod != NULL) {
3679 mod = (PyLongObject *)fast_mod(v, w);
3680 if (mod == NULL) {
3681 Py_XDECREF(div);
3682 return -1;
3683 }
3684 *pmod = mod;
3685 }
3686 if (pdiv != NULL) {
3687 /* We only want to set `*pdiv` when `*pmod` is
3688 set successfully. */
3689 *pdiv = div;
3690 }
3691 return 0;
3692 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 if (long_divrem(v, w, &div, &mod) < 0)
3694 return -1;
3695 if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
3696 (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
3697 PyLongObject *temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003698 temp = (PyLongObject *) long_add(mod, w);
3699 Py_DECREF(mod);
3700 mod = temp;
3701 if (mod == NULL) {
3702 Py_DECREF(div);
3703 return -1;
3704 }
Serhiy Storchakaba85d692017-03-30 09:09:41 +03003705 temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_One);
3706 if (temp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003707 Py_DECREF(mod);
3708 Py_DECREF(div);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003709 return -1;
3710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003711 Py_DECREF(div);
3712 div = temp;
3713 }
3714 if (pdiv != NULL)
3715 *pdiv = div;
3716 else
3717 Py_DECREF(div);
Tim Peters47e52ee2004-08-30 02:44:38 +00003718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003719 if (pmod != NULL)
3720 *pmod = mod;
3721 else
3722 Py_DECREF(mod);
Tim Peters47e52ee2004-08-30 02:44:38 +00003723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003724 return 0;
Guido van Rossume32e0141992-01-19 16:31:05 +00003725}
3726
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003727static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00003728long_div(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00003729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003730 PyLongObject *div;
Neil Schemenauerba872e22001-01-04 01:46:03 +00003731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003732 CHECK_BINOP(a, b);
Yury Selivanove0b23092016-02-11 10:26:27 -05003733
3734 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
3735 return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
3736 }
3737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
3739 div = NULL;
3740 return (PyObject *)div;
Guido van Rossume32e0141992-01-19 16:31:05 +00003741}
3742
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003743/* PyLong/PyLong -> float, with correctly rounded result. */
3744
3745#define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
3746#define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
3747
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003748static PyObject *
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003749long_true_divide(PyObject *v, PyObject *w)
Tim Peters20dab9f2001-09-04 05:31:47 +00003750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 PyLongObject *a, *b, *x;
3752 Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
3753 digit mask, low;
3754 int inexact, negate, a_is_small, b_is_small;
3755 double dx, result;
Tim Peterse2a60002001-09-04 06:17:36 +00003756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 CHECK_BINOP(v, w);
3758 a = (PyLongObject *)v;
3759 b = (PyLongObject *)w;
Tim Peterse2a60002001-09-04 06:17:36 +00003760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003761 /*
3762 Method in a nutshell:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003764 0. reduce to case a, b > 0; filter out obvious underflow/overflow
3765 1. choose a suitable integer 'shift'
3766 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
3767 3. adjust x for correct rounding
3768 4. convert x to a double dx with the same value
3769 5. return ldexp(dx, shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 In more detail:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003773 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
3774 returns either 0.0 or -0.0, depending on the sign of b. For a and
3775 b both nonzero, ignore signs of a and b, and add the sign back in
3776 at the end. Now write a_bits and b_bits for the bit lengths of a
3777 and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
3778 for b). Then
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003782 So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
3783 so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
3784 DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
3785 the way, we can assume that
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003789 1. The integer 'shift' is chosen so that x has the right number of
3790 bits for a double, plus two or three extra bits that will be used
3791 in the rounding decisions. Writing a_bits and b_bits for the
3792 number of significant bits in a and b respectively, a
3793 straightforward formula for shift is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003795 shift = a_bits - b_bits - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003797 This is fine in the usual case, but if a/b is smaller than the
3798 smallest normal float then it can lead to double rounding on an
3799 IEEE 754 platform, giving incorrectly rounded results. So we
3800 adjust the formula slightly. The actual formula used is:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 2. The quantity x is computed by first shifting a (left -shift bits
3805 if shift <= 0, right shift bits if shift > 0) and then dividing by
3806 b. For both the shift and the division, we keep track of whether
3807 the result is inexact, in a flag 'inexact'; this information is
3808 needed at the rounding stage.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003810 With the choice of shift above, together with our assumption that
3811 a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
3812 that x >= 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003814 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
3815 this with an exactly representable float of the form
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003817 round(x/2**extra_bits) * 2**(extra_bits+shift).
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003819 For float representability, we need x/2**extra_bits <
3820 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
3821 DBL_MANT_DIG. This translates to the condition:
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003823 extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 To round, we just modify the bottom digit of x in-place; this can
3826 end up giving a digit with value > PyLONG_MASK, but that's not a
3827 problem since digits can hold values up to 2*PyLONG_MASK+1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 With the original choices for shift above, extra_bits will always
3830 be 2 or 3. Then rounding under the round-half-to-even rule, we
3831 round up iff the most significant of the extra bits is 1, and
3832 either: (a) the computation of x in step 2 had an inexact result,
3833 or (b) at least one other of the extra bits is 1, or (c) the least
3834 significant bit of x (above those to be rounded) is 1.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003836 4. Conversion to a double is straightforward; all floating-point
3837 operations involved in the conversion are exact, so there's no
3838 danger of rounding errors.
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003840 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
3841 The result will always be exactly representable as a double, except
3842 in the case that it overflows. To avoid dependence on the exact
3843 behaviour of ldexp on overflow, we check for overflow before
3844 applying ldexp. The result of ldexp is adjusted for sign before
3845 returning.
3846 */
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003848 /* Reduce to case where a and b are both positive. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003849 a_size = Py_ABS(Py_SIZE(a));
3850 b_size = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003851 negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
3852 if (b_size == 0) {
3853 PyErr_SetString(PyExc_ZeroDivisionError,
3854 "division by zero");
3855 goto error;
3856 }
3857 if (a_size == 0)
3858 goto underflow_or_zero;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003860 /* Fast path for a and b small (exactly representable in a double).
3861 Relies on floating-point division being correctly rounded; results
3862 may be subject to double rounding on x86 machines that operate with
3863 the x87 FPU set to 64-bit precision. */
3864 a_is_small = a_size <= MANT_DIG_DIGITS ||
3865 (a_size == MANT_DIG_DIGITS+1 &&
3866 a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3867 b_is_small = b_size <= MANT_DIG_DIGITS ||
3868 (b_size == MANT_DIG_DIGITS+1 &&
3869 b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
3870 if (a_is_small && b_is_small) {
3871 double da, db;
3872 da = a->ob_digit[--a_size];
3873 while (a_size > 0)
3874 da = da * PyLong_BASE + a->ob_digit[--a_size];
3875 db = b->ob_digit[--b_size];
3876 while (b_size > 0)
3877 db = db * PyLong_BASE + b->ob_digit[--b_size];
3878 result = da / db;
3879 goto success;
3880 }
Tim Peterse2a60002001-09-04 06:17:36 +00003881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003882 /* Catch obvious cases of underflow and overflow */
3883 diff = a_size - b_size;
3884 if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
3885 /* Extreme overflow */
3886 goto overflow;
3887 else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
3888 /* Extreme underflow */
3889 goto underflow_or_zero;
3890 /* Next line is now safe from overflowing a Py_ssize_t */
3891 diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
3892 bits_in_digit(b->ob_digit[b_size - 1]);
3893 /* Now diff = a_bits - b_bits. */
3894 if (diff > DBL_MAX_EXP)
3895 goto overflow;
3896 else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
3897 goto underflow_or_zero;
Tim Peterse2a60002001-09-04 06:17:36 +00003898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 /* Choose value for shift; see comments for step 1 above. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003900 shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 inexact = 0;
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003904 /* x = abs(a * 2**-shift) */
3905 if (shift <= 0) {
3906 Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
3907 digit rem;
3908 /* x = a << -shift */
3909 if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
3910 /* In practice, it's probably impossible to end up
3911 here. Both a and b would have to be enormous,
3912 using close to SIZE_T_MAX bytes of memory each. */
3913 PyErr_SetString(PyExc_OverflowError,
Mark Dickinson22b20182010-05-10 21:27:53 +00003914 "intermediate overflow during division");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 goto error;
3916 }
3917 x = _PyLong_New(a_size + shift_digits + 1);
3918 if (x == NULL)
3919 goto error;
3920 for (i = 0; i < shift_digits; i++)
3921 x->ob_digit[i] = 0;
3922 rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
3923 a_size, -shift % PyLong_SHIFT);
3924 x->ob_digit[a_size + shift_digits] = rem;
3925 }
3926 else {
3927 Py_ssize_t shift_digits = shift / PyLong_SHIFT;
3928 digit rem;
3929 /* x = a >> shift */
3930 assert(a_size >= shift_digits);
3931 x = _PyLong_New(a_size - shift_digits);
3932 if (x == NULL)
3933 goto error;
3934 rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
3935 a_size - shift_digits, shift % PyLong_SHIFT);
3936 /* set inexact if any of the bits shifted out is nonzero */
3937 if (rem)
3938 inexact = 1;
3939 while (!inexact && shift_digits > 0)
3940 if (a->ob_digit[--shift_digits])
3941 inexact = 1;
3942 }
3943 long_normalize(x);
3944 x_size = Py_SIZE(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 /* x //= b. If the remainder is nonzero, set inexact. We own the only
3947 reference to x, so it's safe to modify it in-place. */
3948 if (b_size == 1) {
3949 digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
3950 b->ob_digit[0]);
3951 long_normalize(x);
3952 if (rem)
3953 inexact = 1;
3954 }
3955 else {
3956 PyLongObject *div, *rem;
3957 div = x_divrem(x, b, &rem);
3958 Py_DECREF(x);
3959 x = div;
3960 if (x == NULL)
3961 goto error;
3962 if (Py_SIZE(rem))
3963 inexact = 1;
3964 Py_DECREF(rem);
3965 }
Victor Stinner45e8e2f2014-05-14 17:24:35 +02003966 x_size = Py_ABS(Py_SIZE(x));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003967 assert(x_size > 0); /* result of division is never zero */
3968 x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 /* The number of extra bits that have to be rounded away. */
Victor Stinner640c35c2013-06-04 23:14:37 +02003971 extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003972 assert(extra_bits == 2 || extra_bits == 3);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 /* Round by directly modifying the low digit of x. */
3975 mask = (digit)1 << (extra_bits - 1);
3976 low = x->ob_digit[0] | inexact;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003977 if ((low & mask) && (low & (3U*mask-1U)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 low += mask;
Mark Dickinsondc590a42016-08-21 10:23:23 +01003979 x->ob_digit[0] = low & ~(2U*mask-1U);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 /* Convert x to a double dx; the conversion is exact. */
3982 dx = x->ob_digit[--x_size];
3983 while (x_size > 0)
3984 dx = dx * PyLong_BASE + x->ob_digit[--x_size];
3985 Py_DECREF(x);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003987 /* Check whether ldexp result will overflow a double. */
3988 if (shift + x_bits >= DBL_MAX_EXP &&
3989 (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
3990 goto overflow;
3991 result = ldexp(dx, (int)shift);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003992
3993 success:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003994 return PyFloat_FromDouble(negate ? -result : result);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003995
3996 underflow_or_zero:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 return PyFloat_FromDouble(negate ? -0.0 : 0.0);
Mark Dickinsoncbb62742009-12-27 15:09:50 +00003998
3999 overflow:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004000 PyErr_SetString(PyExc_OverflowError,
4001 "integer division result too large for a float");
Mark Dickinsoncbb62742009-12-27 15:09:50 +00004002 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004003 return NULL;
Tim Peters20dab9f2001-09-04 05:31:47 +00004004}
4005
4006static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004007long_mod(PyObject *a, PyObject *b)
Guido van Rossume32e0141992-01-19 16:31:05 +00004008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004009 PyLongObject *mod;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004011 CHECK_BINOP(a, b);
4012
Yury Selivanove0b23092016-02-11 10:26:27 -05004013 if (Py_ABS(Py_SIZE(a)) == 1 && Py_ABS(Py_SIZE(b)) == 1) {
4014 return fast_mod((PyLongObject*)a, (PyLongObject*)b);
4015 }
4016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004017 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0)
4018 mod = NULL;
4019 return (PyObject *)mod;
Guido van Rossume32e0141992-01-19 16:31:05 +00004020}
4021
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004022static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004023long_divmod(PyObject *a, PyObject *b)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004025 PyLongObject *div, *mod;
4026 PyObject *z;
Neil Schemenauerba872e22001-01-04 01:46:03 +00004027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004028 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004030 if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
4031 return NULL;
4032 }
4033 z = PyTuple_New(2);
4034 if (z != NULL) {
4035 PyTuple_SetItem(z, 0, (PyObject *) div);
4036 PyTuple_SetItem(z, 1, (PyObject *) mod);
4037 }
4038 else {
4039 Py_DECREF(div);
4040 Py_DECREF(mod);
4041 }
4042 return z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004043}
4044
Tim Peters47e52ee2004-08-30 02:44:38 +00004045/* pow(v, w, x) */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004046static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004047long_pow(PyObject *v, PyObject *w, PyObject *x)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
4050 int negativeOutput = 0; /* if x<0 return negative output */
Neil Schemenauerba872e22001-01-04 01:46:03 +00004051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004052 PyLongObject *z = NULL; /* accumulated result */
4053 Py_ssize_t i, j, k; /* counters */
4054 PyLongObject *temp = NULL;
Tim Peters47e52ee2004-08-30 02:44:38 +00004055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004056 /* 5-ary values. If the exponent is large enough, table is
4057 * precomputed so that table[i] == a**i % c for i in range(32).
4058 */
4059 PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
4060 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
Tim Peters47e52ee2004-08-30 02:44:38 +00004061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 /* a, b, c = v, w, x */
4063 CHECK_BINOP(v, w);
4064 a = (PyLongObject*)v; Py_INCREF(a);
4065 b = (PyLongObject*)w; Py_INCREF(b);
4066 if (PyLong_Check(x)) {
4067 c = (PyLongObject *)x;
4068 Py_INCREF(x);
4069 }
4070 else if (x == Py_None)
4071 c = NULL;
4072 else {
4073 Py_DECREF(a);
4074 Py_DECREF(b);
Brian Curtindfc80e32011-08-10 20:28:54 -05004075 Py_RETURN_NOTIMPLEMENTED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004076 }
Tim Peters4c483c42001-09-05 06:24:58 +00004077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004078 if (Py_SIZE(b) < 0) { /* if exponent is negative */
4079 if (c) {
Mark Dickinson0c346d82014-04-11 14:34:40 -04004080 PyErr_SetString(PyExc_ValueError, "pow() 2nd argument "
Mark Dickinson22b20182010-05-10 21:27:53 +00004081 "cannot be negative when 3rd argument specified");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004082 goto Error;
4083 }
4084 else {
4085 /* else return a float. This works because we know
4086 that this calls float_pow() which converts its
4087 arguments to double. */
4088 Py_DECREF(a);
4089 Py_DECREF(b);
4090 return PyFloat_Type.tp_as_number->nb_power(v, w, x);
4091 }
4092 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004094 if (c) {
4095 /* if modulus == 0:
4096 raise ValueError() */
4097 if (Py_SIZE(c) == 0) {
4098 PyErr_SetString(PyExc_ValueError,
4099 "pow() 3rd argument cannot be 0");
4100 goto Error;
4101 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004103 /* if modulus < 0:
4104 negativeOutput = True
4105 modulus = -modulus */
4106 if (Py_SIZE(c) < 0) {
4107 negativeOutput = 1;
4108 temp = (PyLongObject *)_PyLong_Copy(c);
4109 if (temp == NULL)
4110 goto Error;
4111 Py_DECREF(c);
4112 c = temp;
4113 temp = NULL;
Victor Stinner8aed6f12013-07-17 22:31:17 +02004114 _PyLong_Negate(&c);
4115 if (c == NULL)
4116 goto Error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004117 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 /* if modulus == 1:
4120 return 0 */
4121 if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
4122 z = (PyLongObject *)PyLong_FromLong(0L);
4123 goto Done;
4124 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004125
Tim Peters81a93152013-10-05 16:53:52 -05004126 /* Reduce base by modulus in some cases:
4127 1. If base < 0. Forcing the base non-negative makes things easier.
4128 2. If base is obviously larger than the modulus. The "small
4129 exponent" case later can multiply directly by base repeatedly,
4130 while the "large exponent" case multiplies directly by base 31
4131 times. It can be unboundedly faster to multiply by
4132 base % modulus instead.
4133 We could _always_ do this reduction, but l_divmod() isn't cheap,
4134 so we only do it when it buys something. */
4135 if (Py_SIZE(a) < 0 || Py_SIZE(a) > Py_SIZE(c)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004136 if (l_divmod(a, c, NULL, &temp) < 0)
4137 goto Error;
4138 Py_DECREF(a);
4139 a = temp;
4140 temp = NULL;
4141 }
4142 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004144 /* At this point a, b, and c are guaranteed non-negative UNLESS
4145 c is NULL, in which case a may be negative. */
Tim Peters47e52ee2004-08-30 02:44:38 +00004146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004147 z = (PyLongObject *)PyLong_FromLong(1L);
4148 if (z == NULL)
4149 goto Error;
Tim Peters47e52ee2004-08-30 02:44:38 +00004150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004151 /* Perform a modular reduction, X = X % c, but leave X alone if c
4152 * is NULL.
4153 */
4154#define REDUCE(X) \
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004155 do { \
4156 if (c != NULL) { \
4157 if (l_divmod(X, c, NULL, &temp) < 0) \
4158 goto Error; \
4159 Py_XDECREF(X); \
4160 X = temp; \
4161 temp = NULL; \
4162 } \
4163 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 /* Multiply two values, then reduce the result:
4166 result = X*Y % c. If c is NULL, skip the mod. */
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004167#define MULT(X, Y, result) \
4168 do { \
4169 temp = (PyLongObject *)long_mul(X, Y); \
4170 if (temp == NULL) \
4171 goto Error; \
4172 Py_XDECREF(result); \
4173 result = temp; \
4174 temp = NULL; \
4175 REDUCE(result); \
4176 } while(0)
Tim Peters47e52ee2004-08-30 02:44:38 +00004177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004178 if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
4179 /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
4180 /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
4181 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4182 digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004185 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 if (bi & j)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004187 MULT(z, a, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004188 }
4189 }
4190 }
4191 else {
4192 /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
4193 Py_INCREF(z); /* still holds 1L */
4194 table[0] = z;
4195 for (i = 1; i < 32; ++i)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004196 MULT(table[i-1], a, table[i]);
Tim Peters47e52ee2004-08-30 02:44:38 +00004197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004198 for (i = Py_SIZE(b) - 1; i >= 0; --i) {
4199 const digit bi = b->ob_digit[i];
Tim Peters47e52ee2004-08-30 02:44:38 +00004200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004201 for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
4202 const int index = (bi >> j) & 0x1f;
4203 for (k = 0; k < 5; ++k)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004204 MULT(z, z, z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004205 if (index)
Mark Dickinsoncdd01d22010-05-10 21:37:34 +00004206 MULT(z, table[index], z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004207 }
4208 }
4209 }
Tim Peters47e52ee2004-08-30 02:44:38 +00004210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004211 if (negativeOutput && (Py_SIZE(z) != 0)) {
4212 temp = (PyLongObject *)long_sub(z, c);
4213 if (temp == NULL)
4214 goto Error;
4215 Py_DECREF(z);
4216 z = temp;
4217 temp = NULL;
4218 }
4219 goto Done;
Tim Peters47e52ee2004-08-30 02:44:38 +00004220
Mark Dickinson22b20182010-05-10 21:27:53 +00004221 Error:
Victor Stinner8aed6f12013-07-17 22:31:17 +02004222 Py_CLEAR(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004223 /* fall through */
Mark Dickinson22b20182010-05-10 21:27:53 +00004224 Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004225 if (Py_SIZE(b) > FIVEARY_CUTOFF) {
4226 for (i = 0; i < 32; ++i)
4227 Py_XDECREF(table[i]);
4228 }
4229 Py_DECREF(a);
4230 Py_DECREF(b);
4231 Py_XDECREF(c);
4232 Py_XDECREF(temp);
4233 return (PyObject *)z;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004234}
4235
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004236static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004237long_invert(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004239 /* Implement ~x as -(x+1) */
4240 PyLongObject *x;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004241 if (Py_ABS(Py_SIZE(v)) <=1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004242 return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004243 x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_One);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004244 if (x == NULL)
4245 return NULL;
Mark Dickinson583c6e82016-08-29 16:40:29 +01004246 _PyLong_Negate(&x);
4247 /* No need for maybe_small_long here, since any small
4248 longs will have been caught in the Py_SIZE <= 1 fast path. */
4249 return (PyObject *)x;
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004250}
4251
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004252static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004253long_neg(PyLongObject *v)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 PyLongObject *z;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004256 if (Py_ABS(Py_SIZE(v)) <= 1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004257 return PyLong_FromLong(-MEDIUM_VALUE(v));
4258 z = (PyLongObject *)_PyLong_Copy(v);
4259 if (z != NULL)
4260 Py_SIZE(z) = -(Py_SIZE(v));
4261 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004262}
4263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004264static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004265long_abs(PyLongObject *v)
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004267 if (Py_SIZE(v) < 0)
4268 return long_neg(v);
4269 else
4270 return long_long((PyObject *)v);
Guido van Rossumedcc38a1991-05-05 20:09:44 +00004271}
4272
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004273static int
Jack Diederich4dafcc42006-11-28 19:15:13 +00004274long_bool(PyLongObject *v)
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004276 return Py_SIZE(v) != 0;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004277}
4278
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004279/* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
4280static int
4281divmod_shift(PyLongObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
4282{
4283 assert(PyLong_Check((PyObject *)shiftby));
4284 assert(Py_SIZE(shiftby) >= 0);
4285 Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
4286 if (lshiftby >= 0) {
4287 *wordshift = lshiftby / PyLong_SHIFT;
4288 *remshift = lshiftby % PyLong_SHIFT;
4289 return 0;
4290 }
4291 /* PyLong_Check(shiftby) is true and Py_SIZE(shiftby) >= 0, so it must
4292 be that PyLong_AsSsize_t raised an OverflowError. */
4293 assert(PyErr_ExceptionMatches(PyExc_OverflowError));
4294 PyErr_Clear();
4295 PyLongObject *wordshift_obj = divrem1(shiftby, PyLong_SHIFT, remshift);
4296 if (wordshift_obj == NULL) {
4297 return -1;
4298 }
4299 *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
4300 Py_DECREF(wordshift_obj);
4301 if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
4302 return 0;
4303 }
4304 PyErr_Clear();
4305 /* Clip the value. With such large wordshift the right shift
4306 returns 0 and the left shift raises an error in _PyLong_New(). */
4307 *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
4308 *remshift = 0;
4309 return 0;
4310}
4311
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004312static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004313long_rshift(PyLongObject *a, PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004315 PyLongObject *z = NULL;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004316 Py_ssize_t newsize, wordshift, hishift, i, j;
4317 digit loshift, lomask, himask;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004319 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004320
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004321 if (Py_SIZE(b) < 0) {
4322 PyErr_SetString(PyExc_ValueError,
4323 "negative shift count");
4324 return NULL;
4325 }
4326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004327 if (Py_SIZE(a) < 0) {
4328 /* Right shifting negative numbers is harder */
4329 PyLongObject *a1, *a2;
4330 a1 = (PyLongObject *) long_invert(a);
4331 if (a1 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004332 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004333 a2 = (PyLongObject *) long_rshift(a1, b);
4334 Py_DECREF(a1);
4335 if (a2 == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004336 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004337 z = (PyLongObject *) long_invert(a2);
4338 Py_DECREF(a2);
4339 }
4340 else {
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004341 if (divmod_shift(b, &wordshift, &loshift) < 0)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004342 return NULL;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004343 newsize = Py_SIZE(a) - wordshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004344 if (newsize <= 0)
4345 return PyLong_FromLong(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 hishift = PyLong_SHIFT - loshift;
4347 lomask = ((digit)1 << hishift) - 1;
4348 himask = PyLong_MASK ^ lomask;
4349 z = _PyLong_New(newsize);
4350 if (z == NULL)
Mark Dickinson92ca5352016-09-17 17:50:50 +01004351 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004352 for (i = 0, j = wordshift; i < newsize; i++, j++) {
4353 z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
4354 if (i+1 < newsize)
Mark Dickinson22b20182010-05-10 21:27:53 +00004355 z->ob_digit[i] |= (a->ob_digit[j+1] << hishift) & himask;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004356 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004357 z = maybe_small_long(long_normalize(z));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004358 }
Mark Dickinson92ca5352016-09-17 17:50:50 +01004359 return (PyObject *)z;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004360}
4361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004362static PyObject *
Neil Schemenauerba872e22001-01-04 01:46:03 +00004363long_lshift(PyObject *v, PyObject *w)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 /* This version due to Tim Peters */
4366 PyLongObject *a = (PyLongObject*)v;
4367 PyLongObject *b = (PyLongObject*)w;
4368 PyLongObject *z = NULL;
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004369 Py_ssize_t oldsize, newsize, wordshift, i, j;
4370 digit remshift;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004371 twodigits accum;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004373 CHECK_BINOP(a, b);
Neil Schemenauerba872e22001-01-04 01:46:03 +00004374
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004375 if (Py_SIZE(b) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004376 PyErr_SetString(PyExc_ValueError, "negative shift count");
Victor Stinner8aed6f12013-07-17 22:31:17 +02004377 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004378 }
Mark Dickinson82a95272016-08-29 19:27:06 +01004379 if (Py_SIZE(a) == 0) {
4380 return PyLong_FromLong(0);
4381 }
4382
Serhiy Storchaka918403c2017-03-30 09:47:07 +03004383 if (divmod_shift(b, &wordshift, &remshift) < 0)
4384 return NULL;
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004385 oldsize = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 newsize = oldsize + wordshift;
4387 if (remshift)
4388 ++newsize;
4389 z = _PyLong_New(newsize);
4390 if (z == NULL)
Victor Stinner8aed6f12013-07-17 22:31:17 +02004391 return NULL;
4392 if (Py_SIZE(a) < 0) {
4393 assert(Py_REFCNT(z) == 1);
4394 Py_SIZE(z) = -Py_SIZE(z);
4395 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 for (i = 0; i < wordshift; i++)
4397 z->ob_digit[i] = 0;
4398 accum = 0;
4399 for (i = wordshift, j = 0; j < oldsize; i++, j++) {
4400 accum |= (twodigits)a->ob_digit[j] << remshift;
4401 z->ob_digit[i] = (digit)(accum & PyLong_MASK);
4402 accum >>= PyLong_SHIFT;
4403 }
4404 if (remshift)
4405 z->ob_digit[newsize-1] = (digit)accum;
4406 else
4407 assert(!accum);
4408 z = long_normalize(z);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004409 return (PyObject *) maybe_small_long(z);
Guido van Rossumc6913e71991-11-19 20:26:46 +00004410}
4411
Mark Dickinson27a87a22009-10-25 20:43:34 +00004412/* Compute two's complement of digit vector a[0:m], writing result to
4413 z[0:m]. The digit vector a need not be normalized, but should not
4414 be entirely zero. a and z may point to the same digit vector. */
4415
4416static void
4417v_complement(digit *z, digit *a, Py_ssize_t m)
4418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 Py_ssize_t i;
4420 digit carry = 1;
4421 for (i = 0; i < m; ++i) {
4422 carry += a[i] ^ PyLong_MASK;
4423 z[i] = carry & PyLong_MASK;
4424 carry >>= PyLong_SHIFT;
4425 }
4426 assert(carry == 0);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004427}
Guido van Rossum4c260ff1992-01-14 18:36:43 +00004428
4429/* Bitwise and/xor/or operations */
4430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004431static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004432long_bitwise(PyLongObject *a,
Benjamin Peterson513762f2012-12-26 16:43:33 -06004433 char op, /* '&', '|', '^' */
Mark Dickinson22b20182010-05-10 21:27:53 +00004434 PyLongObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 int nega, negb, negz;
4437 Py_ssize_t size_a, size_b, size_z, i;
4438 PyLongObject *z;
Tim Peters5af4e6c2002-08-12 02:31:19 +00004439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 /* Bitwise operations for negative numbers operate as though
4441 on a two's complement representation. So convert arguments
4442 from sign-magnitude to two's complement, and convert the
4443 result back to sign-magnitude at the end. */
Mark Dickinson27a87a22009-10-25 20:43:34 +00004444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004445 /* If a is negative, replace it by its two's complement. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004446 size_a = Py_ABS(Py_SIZE(a));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 nega = Py_SIZE(a) < 0;
4448 if (nega) {
4449 z = _PyLong_New(size_a);
4450 if (z == NULL)
4451 return NULL;
4452 v_complement(z->ob_digit, a->ob_digit, size_a);
4453 a = z;
4454 }
4455 else
4456 /* Keep reference count consistent. */
4457 Py_INCREF(a);
Mark Dickinson27a87a22009-10-25 20:43:34 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 /* Same for b. */
Victor Stinner45e8e2f2014-05-14 17:24:35 +02004460 size_b = Py_ABS(Py_SIZE(b));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 negb = Py_SIZE(b) < 0;
4462 if (negb) {
4463 z = _PyLong_New(size_b);
4464 if (z == NULL) {
4465 Py_DECREF(a);
4466 return NULL;
4467 }
4468 v_complement(z->ob_digit, b->ob_digit, size_b);
4469 b = z;
4470 }
4471 else
4472 Py_INCREF(b);
Tim Peters5af4e6c2002-08-12 02:31:19 +00004473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004474 /* Swap a and b if necessary to ensure size_a >= size_b. */
4475 if (size_a < size_b) {
4476 z = a; a = b; b = z;
4477 size_z = size_a; size_a = size_b; size_b = size_z;
4478 negz = nega; nega = negb; negb = negz;
4479 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 /* JRH: The original logic here was to allocate the result value (z)
4482 as the longer of the two operands. However, there are some cases
4483 where the result is guaranteed to be shorter than that: AND of two
4484 positives, OR of two negatives: use the shorter number. AND with
4485 mixed signs: use the positive number. OR with mixed signs: use the
4486 negative number.
4487 */
4488 switch (op) {
4489 case '^':
4490 negz = nega ^ negb;
4491 size_z = size_a;
4492 break;
4493 case '&':
4494 negz = nega & negb;
4495 size_z = negb ? size_a : size_b;
4496 break;
4497 case '|':
4498 negz = nega | negb;
4499 size_z = negb ? size_b : size_a;
4500 break;
4501 default:
4502 PyErr_BadArgument();
4503 return NULL;
4504 }
Guido van Rossumbd3a5271998-08-11 15:04:47 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 /* We allow an extra digit if z is negative, to make sure that
4507 the final two's complement of z doesn't overflow. */
4508 z = _PyLong_New(size_z + negz);
4509 if (z == NULL) {
4510 Py_DECREF(a);
4511 Py_DECREF(b);
4512 return NULL;
4513 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 /* Compute digits for overlap of a and b. */
4516 switch(op) {
4517 case '&':
4518 for (i = 0; i < size_b; ++i)
4519 z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
4520 break;
4521 case '|':
4522 for (i = 0; i < size_b; ++i)
4523 z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
4524 break;
4525 case '^':
4526 for (i = 0; i < size_b; ++i)
4527 z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
4528 break;
4529 default:
4530 PyErr_BadArgument();
4531 return NULL;
4532 }
Mark Dickinson27a87a22009-10-25 20:43:34 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 /* Copy any remaining digits of a, inverting if necessary. */
4535 if (op == '^' && negb)
4536 for (; i < size_z; ++i)
4537 z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
4538 else if (i < size_z)
4539 memcpy(&z->ob_digit[i], &a->ob_digit[i],
4540 (size_z-i)*sizeof(digit));
Mark Dickinson27a87a22009-10-25 20:43:34 +00004541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004542 /* Complement result if negative. */
4543 if (negz) {
4544 Py_SIZE(z) = -(Py_SIZE(z));
4545 z->ob_digit[size_z] = PyLong_MASK;
4546 v_complement(z->ob_digit, z->ob_digit, size_z+1);
4547 }
Tim Peters5af4e6c2002-08-12 02:31:19 +00004548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549 Py_DECREF(a);
4550 Py_DECREF(b);
4551 return (PyObject *)maybe_small_long(long_normalize(z));
Guido van Rossumc6913e71991-11-19 20:26:46 +00004552}
4553
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004554static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004555long_and(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004557 PyObject *c;
4558 CHECK_BINOP(a, b);
4559 c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b);
4560 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004561}
4562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004563static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004564long_xor(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004566 PyObject *c;
4567 CHECK_BINOP(a, b);
4568 c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b);
4569 return c;
Guido van Rossumc6913e71991-11-19 20:26:46 +00004570}
4571
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004572static PyObject *
Martin v. Löwisda86fcc2007-09-10 07:59:54 +00004573long_or(PyObject *a, PyObject *b)
Guido van Rossumc6913e71991-11-19 20:26:46 +00004574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004575 PyObject *c;
4576 CHECK_BINOP(a, b);
4577 c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b);
4578 return c;
Guido van Rossum23d6f0e1991-05-14 12:06:49 +00004579}
4580
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004581static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004582long_long(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004584 if (PyLong_CheckExact(v))
4585 Py_INCREF(v);
4586 else
4587 v = _PyLong_Copy((PyLongObject *)v);
4588 return v;
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004589}
4590
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004591PyObject *
4592_PyLong_GCD(PyObject *aarg, PyObject *barg)
4593{
4594 PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
4595 stwodigits x, y, q, s, t, c_carry, d_carry;
4596 stwodigits A, B, C, D, T;
4597 int nbits, k;
4598 Py_ssize_t size_a, size_b, alloc_a, alloc_b;
4599 digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
4600
4601 a = (PyLongObject *)aarg;
4602 b = (PyLongObject *)barg;
4603 size_a = Py_SIZE(a);
4604 size_b = Py_SIZE(b);
4605 if (-2 <= size_a && size_a <= 2 && -2 <= size_b && size_b <= 2) {
4606 Py_INCREF(a);
4607 Py_INCREF(b);
4608 goto simple;
4609 }
4610
4611 /* Initial reduction: make sure that 0 <= b <= a. */
4612 a = (PyLongObject *)long_abs(a);
4613 if (a == NULL)
4614 return NULL;
4615 b = (PyLongObject *)long_abs(b);
4616 if (b == NULL) {
4617 Py_DECREF(a);
4618 return NULL;
4619 }
4620 if (long_compare(a, b) < 0) {
4621 r = a;
4622 a = b;
4623 b = r;
4624 }
4625 /* We now own references to a and b */
4626
4627 alloc_a = Py_SIZE(a);
4628 alloc_b = Py_SIZE(b);
4629 /* reduce until a fits into 2 digits */
4630 while ((size_a = Py_SIZE(a)) > 2) {
4631 nbits = bits_in_digit(a->ob_digit[size_a-1]);
4632 /* extract top 2*PyLong_SHIFT bits of a into x, along with
4633 corresponding bits of b into y */
4634 size_b = Py_SIZE(b);
4635 assert(size_b <= size_a);
4636 if (size_b == 0) {
4637 if (size_a < alloc_a) {
4638 r = (PyLongObject *)_PyLong_Copy(a);
4639 Py_DECREF(a);
4640 }
4641 else
4642 r = a;
4643 Py_DECREF(b);
4644 Py_XDECREF(c);
4645 Py_XDECREF(d);
4646 return (PyObject *)r;
4647 }
4648 x = (((twodigits)a->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
4649 ((twodigits)a->ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
4650 (a->ob_digit[size_a-3] >> nbits));
4651
4652 y = ((size_b >= size_a - 2 ? b->ob_digit[size_a-3] >> nbits : 0) |
4653 (size_b >= size_a - 1 ? (twodigits)b->ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
4654 (size_b >= size_a ? (twodigits)b->ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
4655
4656 /* inner loop of Lehmer's algorithm; A, B, C, D never grow
4657 larger than PyLong_MASK during the algorithm. */
4658 A = 1; B = 0; C = 0; D = 1;
4659 for (k=0;; k++) {
4660 if (y-C == 0)
4661 break;
4662 q = (x+(A-1))/(y-C);
4663 s = B+q*D;
4664 t = x-q*y;
4665 if (s > t)
4666 break;
4667 x = y; y = t;
4668 t = A+q*C; A = D; B = C; C = s; D = t;
4669 }
4670
4671 if (k == 0) {
4672 /* no progress; do a Euclidean step */
4673 if (l_divmod(a, b, NULL, &r) < 0)
4674 goto error;
4675 Py_DECREF(a);
4676 a = b;
4677 b = r;
4678 alloc_a = alloc_b;
4679 alloc_b = Py_SIZE(b);
4680 continue;
4681 }
4682
4683 /*
4684 a, b = A*b-B*a, D*a-C*b if k is odd
4685 a, b = A*a-B*b, D*b-C*a if k is even
4686 */
4687 if (k&1) {
4688 T = -A; A = -B; B = T;
4689 T = -C; C = -D; D = T;
4690 }
4691 if (c != NULL)
4692 Py_SIZE(c) = size_a;
4693 else if (Py_REFCNT(a) == 1) {
4694 Py_INCREF(a);
4695 c = a;
4696 }
4697 else {
4698 alloc_a = size_a;
4699 c = _PyLong_New(size_a);
4700 if (c == NULL)
4701 goto error;
4702 }
4703
4704 if (d != NULL)
4705 Py_SIZE(d) = size_a;
4706 else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
4707 Py_INCREF(b);
4708 d = b;
4709 Py_SIZE(d) = size_a;
4710 }
4711 else {
4712 alloc_b = size_a;
4713 d = _PyLong_New(size_a);
4714 if (d == NULL)
4715 goto error;
4716 }
4717 a_end = a->ob_digit + size_a;
4718 b_end = b->ob_digit + size_b;
4719
4720 /* compute new a and new b in parallel */
4721 a_digit = a->ob_digit;
4722 b_digit = b->ob_digit;
4723 c_digit = c->ob_digit;
4724 d_digit = d->ob_digit;
4725 c_carry = 0;
4726 d_carry = 0;
4727 while (b_digit < b_end) {
4728 c_carry += (A * *a_digit) - (B * *b_digit);
4729 d_carry += (D * *b_digit++) - (C * *a_digit++);
4730 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4731 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4732 c_carry >>= PyLong_SHIFT;
4733 d_carry >>= PyLong_SHIFT;
4734 }
4735 while (a_digit < a_end) {
4736 c_carry += A * *a_digit;
4737 d_carry -= C * *a_digit++;
4738 *c_digit++ = (digit)(c_carry & PyLong_MASK);
4739 *d_digit++ = (digit)(d_carry & PyLong_MASK);
4740 c_carry >>= PyLong_SHIFT;
4741 d_carry >>= PyLong_SHIFT;
4742 }
4743 assert(c_carry == 0);
4744 assert(d_carry == 0);
4745
4746 Py_INCREF(c);
4747 Py_INCREF(d);
4748 Py_DECREF(a);
4749 Py_DECREF(b);
4750 a = long_normalize(c);
4751 b = long_normalize(d);
4752 }
4753 Py_XDECREF(c);
4754 Py_XDECREF(d);
4755
4756simple:
4757 assert(Py_REFCNT(a) > 0);
4758 assert(Py_REFCNT(b) > 0);
Victor Stinner5783fd22015-09-19 13:39:03 +02004759/* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
4760 undefined behaviour when LONG_MAX type is smaller than 60 bits */
4761#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004762 /* a fits into a long, so b must too */
4763 x = PyLong_AsLong((PyObject *)a);
4764 y = PyLong_AsLong((PyObject *)b);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004765#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004766 x = PyLong_AsLongLong((PyObject *)a);
4767 y = PyLong_AsLongLong((PyObject *)b);
4768#else
4769# error "_PyLong_GCD"
4770#endif
4771 x = Py_ABS(x);
4772 y = Py_ABS(y);
4773 Py_DECREF(a);
4774 Py_DECREF(b);
4775
4776 /* usual Euclidean algorithm for longs */
4777 while (y != 0) {
4778 t = y;
4779 y = x % y;
4780 x = t;
4781 }
Victor Stinner5783fd22015-09-19 13:39:03 +02004782#if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004783 return PyLong_FromLong(x);
Benjamin Petersond953f8e2016-09-06 10:51:19 -07004784#elif PY_LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
Serhiy Storchaka48e47aa2015-05-13 00:19:51 +03004785 return PyLong_FromLongLong(x);
4786#else
4787# error "_PyLong_GCD"
4788#endif
4789
4790error:
4791 Py_DECREF(a);
4792 Py_DECREF(b);
4793 Py_XDECREF(c);
4794 Py_XDECREF(d);
4795 return NULL;
4796}
4797
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004798static PyObject *
Tim Peters9f688bf2000-07-07 15:53:28 +00004799long_float(PyObject *v)
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004801 double result;
4802 result = PyLong_AsDouble(v);
4803 if (result == -1.0 && PyErr_Occurred())
4804 return NULL;
4805 return PyFloat_FromDouble(result);
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004806}
4807
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004808static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004809long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
4810
4811/*[clinic input]
4812@classmethod
4813int.__new__ as long_new
4814 x: object(c_default="NULL") = 0
4815 /
4816 base as obase: object(c_default="NULL") = 10
4817[clinic start generated code]*/
Guido van Rossum1899c2e1992-09-12 11:09:23 +00004818
Tim Peters6d6c1a32001-08-02 04:15:00 +00004819static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004820long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
4821/*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00004822{
Gregory P. Smitha689e522012-12-25 22:38:32 -08004823 Py_ssize_t base;
Tim Peters6d6c1a32001-08-02 04:15:00 +00004824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004825 if (type != &PyLong_Type)
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004826 return long_subtype_new(type, x, obase); /* Wimp out */
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004827 if (x == NULL) {
4828 if (obase != NULL) {
4829 PyErr_SetString(PyExc_TypeError,
4830 "int() missing string argument");
4831 return NULL;
4832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004833 return PyLong_FromLong(0L);
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004834 }
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004835 if (obase == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004836 return PyNumber_Long(x);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004837
Gregory P. Smitha689e522012-12-25 22:38:32 -08004838 base = PyNumber_AsSsize_t(obase, NULL);
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004839 if (base == -1 && PyErr_Occurred())
4840 return NULL;
Gregory P. Smitha689e522012-12-25 22:38:32 -08004841 if ((base != 0 && base < 2) || base > 36) {
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004842 PyErr_SetString(PyExc_ValueError,
Serhiy Storchaka0b386d52012-12-28 09:42:11 +02004843 "int() base must be >= 2 and <= 36");
Mark Dickinsonf9a5a8e2010-05-26 20:07:58 +00004844 return NULL;
4845 }
4846
4847 if (PyUnicode_Check(x))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004848 return PyLong_FromUnicodeObject(x, (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004850 char *string;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004851 if (PyByteArray_Check(x))
4852 string = PyByteArray_AS_STRING(x);
4853 else
4854 string = PyBytes_AS_STRING(x);
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03004855 return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004856 }
4857 else {
4858 PyErr_SetString(PyExc_TypeError,
Mark Dickinson22b20182010-05-10 21:27:53 +00004859 "int() can't convert non-string with explicit base");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004860 return NULL;
4861 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00004862}
4863
Serhiy Storchaka95949422013-08-27 19:40:23 +03004864/* Wimpy, slow approach to tp_new calls for subtypes of int:
4865 first create a regular int from whatever arguments we got,
Guido van Rossumbef14172001-08-29 15:47:46 +00004866 then allocate a subtype instance and initialize it from
Serhiy Storchaka95949422013-08-27 19:40:23 +03004867 the regular int. The regular int is then thrown away.
Guido van Rossumbef14172001-08-29 15:47:46 +00004868*/
4869static PyObject *
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004870long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
Guido van Rossumbef14172001-08-29 15:47:46 +00004871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004872 PyLongObject *tmp, *newobj;
4873 Py_ssize_t i, n;
Guido van Rossumbef14172001-08-29 15:47:46 +00004874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 assert(PyType_IsSubtype(type, &PyLong_Type));
Serhiy Storchaka18b250f2017-03-19 08:51:07 +02004876 tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004877 if (tmp == NULL)
4878 return NULL;
Serhiy Storchaka15095802015-11-25 15:47:01 +02004879 assert(PyLong_Check(tmp));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004880 n = Py_SIZE(tmp);
4881 if (n < 0)
4882 n = -n;
4883 newobj = (PyLongObject *)type->tp_alloc(type, n);
4884 if (newobj == NULL) {
4885 Py_DECREF(tmp);
4886 return NULL;
4887 }
4888 assert(PyLong_Check(newobj));
4889 Py_SIZE(newobj) = Py_SIZE(tmp);
4890 for (i = 0; i < n; i++)
4891 newobj->ob_digit[i] = tmp->ob_digit[i];
4892 Py_DECREF(tmp);
4893 return (PyObject *)newobj;
Guido van Rossumbef14172001-08-29 15:47:46 +00004894}
4895
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004896/*[clinic input]
4897int.__getnewargs__
4898[clinic start generated code]*/
4899
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004900static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004901int___getnewargs___impl(PyObject *self)
4902/*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004903{
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004904 return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
Guido van Rossum5d9113d2003-01-29 17:58:45 +00004905}
4906
Guido van Rossumb43daf72007-08-01 18:08:08 +00004907static PyObject *
Mark Dickinson6bf19002009-05-02 17:57:52 +00004908long_get0(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004909 return PyLong_FromLong(0L);
Mark Dickinson6bf19002009-05-02 17:57:52 +00004910}
4911
4912static PyObject *
4913long_get1(PyLongObject *v, void *context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004914 return PyLong_FromLong(1L);
Guido van Rossumb43daf72007-08-01 18:08:08 +00004915}
4916
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004917/*[clinic input]
4918int.__format__
4919
4920 format_spec: unicode
4921 /
4922[clinic start generated code]*/
4923
Guido van Rossum2fa33db2007-08-23 22:07:24 +00004924static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02004925int___format___impl(PyObject *self, PyObject *format_spec)
4926/*[clinic end generated code: output=b4929dee9ae18689 input=e31944a9b3e428b7]*/
Eric Smith8c663262007-08-25 02:26:07 +00004927{
Victor Stinnerd3f08822012-05-29 12:57:52 +02004928 _PyUnicodeWriter writer;
4929 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +00004930
Victor Stinner8f674cc2013-04-17 23:02:17 +02004931 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +02004932 ret = _PyLong_FormatAdvancedWriter(
4933 &writer,
4934 self,
4935 format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
4936 if (ret == -1) {
4937 _PyUnicodeWriter_Dealloc(&writer);
4938 return NULL;
4939 }
4940 return _PyUnicodeWriter_Finish(&writer);
Eric Smith8c663262007-08-25 02:26:07 +00004941}
4942
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004943/* Return a pair (q, r) such that a = b * q + r, and
4944 abs(r) <= abs(b)/2, with equality possible only if q is even.
4945 In other words, q == a / b, rounded to the nearest integer using
4946 round-half-to-even. */
4947
4948PyObject *
Mark Dickinsonfa68a612010-06-07 18:47:09 +00004949_PyLong_DivmodNear(PyObject *a, PyObject *b)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004950{
4951 PyLongObject *quo = NULL, *rem = NULL;
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004952 PyObject *twice_rem, *result, *temp;
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004953 int cmp, quo_is_odd, quo_is_neg;
4954
4955 /* Equivalent Python code:
4956
4957 def divmod_near(a, b):
4958 q, r = divmod(a, b)
4959 # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
4960 # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
4961 # positive, 2 * r < b if b negative.
4962 greater_than_half = 2*r > b if b > 0 else 2*r < b
4963 exactly_half = 2*r == b
4964 if greater_than_half or exactly_half and q % 2 == 1:
4965 q += 1
4966 r -= b
4967 return q, r
4968
4969 */
4970 if (!PyLong_Check(a) || !PyLong_Check(b)) {
4971 PyErr_SetString(PyExc_TypeError,
4972 "non-integer arguments in division");
4973 return NULL;
4974 }
4975
4976 /* Do a and b have different signs? If so, quotient is negative. */
4977 quo_is_neg = (Py_SIZE(a) < 0) != (Py_SIZE(b) < 0);
4978
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004979 if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
4980 goto error;
4981
4982 /* compare twice the remainder with the divisor, to see
4983 if we need to adjust the quotient and remainder */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03004984 twice_rem = long_lshift((PyObject *)rem, _PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00004985 if (twice_rem == NULL)
4986 goto error;
4987 if (quo_is_neg) {
4988 temp = long_neg((PyLongObject*)twice_rem);
4989 Py_DECREF(twice_rem);
4990 twice_rem = temp;
4991 if (twice_rem == NULL)
4992 goto error;
4993 }
4994 cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
4995 Py_DECREF(twice_rem);
4996
4997 quo_is_odd = Py_SIZE(quo) != 0 && ((quo->ob_digit[0] & 1) != 0);
4998 if ((Py_SIZE(b) < 0 ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
4999 /* fix up quotient */
5000 if (quo_is_neg)
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005001 temp = long_sub(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005002 else
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005003 temp = long_add(quo, (PyLongObject *)_PyLong_One);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005004 Py_DECREF(quo);
5005 quo = (PyLongObject *)temp;
5006 if (quo == NULL)
5007 goto error;
5008 /* and remainder */
5009 if (quo_is_neg)
5010 temp = long_add(rem, (PyLongObject *)b);
5011 else
5012 temp = long_sub(rem, (PyLongObject *)b);
5013 Py_DECREF(rem);
5014 rem = (PyLongObject *)temp;
5015 if (rem == NULL)
5016 goto error;
5017 }
5018
5019 result = PyTuple_New(2);
5020 if (result == NULL)
5021 goto error;
5022
5023 /* PyTuple_SET_ITEM steals references */
5024 PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
5025 PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005026 return result;
5027
5028 error:
5029 Py_XDECREF(quo);
5030 Py_XDECREF(rem);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005031 return NULL;
5032}
5033
Eric Smith8c663262007-08-25 02:26:07 +00005034static PyObject *
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005035long_round(PyObject *self, PyObject *args)
5036{
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005037 PyObject *o_ndigits=NULL, *temp, *result, *ndigits;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005038
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005039 /* To round an integer m to the nearest 10**n (n positive), we make use of
5040 * the divmod_near operation, defined by:
5041 *
5042 * divmod_near(a, b) = (q, r)
5043 *
5044 * where q is the nearest integer to the quotient a / b (the
5045 * nearest even integer in the case of a tie) and r == a - q * b.
5046 * Hence q * b = a - r is the nearest multiple of b to a,
5047 * preferring even multiples in the case of a tie.
5048 *
5049 * So the nearest multiple of 10**n to m is:
5050 *
5051 * m - divmod_near(m, 10**n)[1].
5052 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 if (!PyArg_ParseTuple(args, "|O", &o_ndigits))
5054 return NULL;
5055 if (o_ndigits == NULL)
5056 return long_long(self);
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005057
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005058 ndigits = PyNumber_Index(o_ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 if (ndigits == NULL)
5060 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005061
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005062 /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 if (Py_SIZE(ndigits) >= 0) {
5064 Py_DECREF(ndigits);
5065 return long_long(self);
5066 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005067
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005068 /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
5069 temp = long_neg((PyLongObject*)ndigits);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 Py_DECREF(ndigits);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005071 ndigits = temp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 if (ndigits == NULL)
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005073 return NULL;
Mark Dickinson1124e712009-01-28 21:25:58 +00005074
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005075 result = PyLong_FromLong(10L);
5076 if (result == NULL) {
5077 Py_DECREF(ndigits);
5078 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 }
Mark Dickinson1124e712009-01-28 21:25:58 +00005080
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005081 temp = long_pow(result, ndigits, Py_None);
5082 Py_DECREF(ndigits);
5083 Py_DECREF(result);
5084 result = temp;
5085 if (result == NULL)
5086 return NULL;
5087
Mark Dickinsonfa68a612010-06-07 18:47:09 +00005088 temp = _PyLong_DivmodNear(self, result);
Mark Dickinson7f1bf802010-05-26 16:02:59 +00005089 Py_DECREF(result);
5090 result = temp;
5091 if (result == NULL)
5092 return NULL;
5093
5094 temp = long_sub((PyLongObject *)self,
5095 (PyLongObject *)PyTuple_GET_ITEM(result, 1));
5096 Py_DECREF(result);
5097 result = temp;
5098
5099 return result;
Guido van Rossum2fa33db2007-08-23 22:07:24 +00005100}
5101
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005102/*[clinic input]
5103int.__sizeof__ -> Py_ssize_t
5104
5105Returns size in memory, in bytes.
5106[clinic start generated code]*/
5107
5108static Py_ssize_t
5109int___sizeof___impl(PyObject *self)
5110/*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005113
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005114 res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
5115 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00005116}
5117
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005118/*[clinic input]
5119int.bit_length
5120
5121Number of bits necessary to represent self in binary.
5122
5123>>> bin(37)
5124'0b100101'
5125>>> (37).bit_length()
51266
5127[clinic start generated code]*/
5128
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005129static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005130int_bit_length_impl(PyObject *self)
5131/*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005133 PyLongObject *result, *x, *y;
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005134 Py_ssize_t ndigits;
5135 int msd_bits;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 digit msd;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005137
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005138 assert(self != NULL);
5139 assert(PyLong_Check(self));
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005140
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005141 ndigits = Py_ABS(Py_SIZE(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005142 if (ndigits == 0)
5143 return PyLong_FromLong(0);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005144
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005145 msd = ((PyLongObject *)self)->ob_digit[ndigits-1];
Serhiy Storchakab2e64f92016-11-08 20:34:22 +02005146 msd_bits = bits_in_digit(msd);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
5149 return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 /* expression above may overflow; use Python integers instead */
5152 result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
5153 if (result == NULL)
5154 return NULL;
5155 x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
5156 if (x == NULL)
5157 goto error;
5158 y = (PyLongObject *)long_mul(result, x);
5159 Py_DECREF(x);
5160 if (y == NULL)
5161 goto error;
5162 Py_DECREF(result);
5163 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
5166 if (x == NULL)
5167 goto error;
5168 y = (PyLongObject *)long_add(result, x);
5169 Py_DECREF(x);
5170 if (y == NULL)
5171 goto error;
5172 Py_DECREF(result);
5173 result = y;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 return (PyObject *)result;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005176
Mark Dickinson22b20182010-05-10 21:27:53 +00005177 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005178 Py_DECREF(result);
5179 return NULL;
Mark Dickinson54bc1ec2008-12-17 16:19:07 +00005180}
5181
Christian Heimes53876d92008-04-19 00:31:39 +00005182#if 0
5183static PyObject *
5184long_is_finite(PyObject *v)
5185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 Py_RETURN_TRUE;
Christian Heimes53876d92008-04-19 00:31:39 +00005187}
5188#endif
5189
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005190/*[clinic input]
5191int.to_bytes
5192
5193 length: Py_ssize_t
5194 Length of bytes object to use. An OverflowError is raised if the
5195 integer is not representable with the given number of bytes.
5196 byteorder: unicode
5197 The byte order used to represent the integer. If byteorder is 'big',
5198 the most significant byte is at the beginning of the byte array. If
5199 byteorder is 'little', the most significant byte is at the end of the
5200 byte array. To request the native byte order of the host system, use
5201 `sys.byteorder' as the byte order value.
5202 *
5203 signed as is_signed: bool = False
5204 Determines whether two's complement is used to represent the integer.
5205 If signed is False and a negative integer is given, an OverflowError
5206 is raised.
5207
5208Return an array of bytes representing an integer.
5209[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005210
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005211static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005212int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
5213 int is_signed)
5214/*[clinic end generated code: output=89c801df114050a3 input=ddac63f4c7bf414c]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005216 int little_endian;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005217 PyObject *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005218
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005219 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005220 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005221 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005222 little_endian = 0;
5223 else {
5224 PyErr_SetString(PyExc_ValueError,
5225 "byteorder must be either 'little' or 'big'");
5226 return NULL;
5227 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005229 if (length < 0) {
5230 PyErr_SetString(PyExc_ValueError,
5231 "length argument must be non-negative");
5232 return NULL;
5233 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 bytes = PyBytes_FromStringAndSize(NULL, length);
5236 if (bytes == NULL)
5237 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005238
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005239 if (_PyLong_AsByteArray((PyLongObject *)self,
5240 (unsigned char *)PyBytes_AS_STRING(bytes),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005241 length, little_endian, is_signed) < 0) {
5242 Py_DECREF(bytes);
5243 return NULL;
5244 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005246 return bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005247}
5248
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005249/*[clinic input]
5250@classmethod
5251int.from_bytes
5252
5253 bytes as bytes_obj: object
5254 Holds the array of bytes to convert. The argument must either
5255 support the buffer protocol or be an iterable object producing bytes.
5256 Bytes and bytearray are examples of built-in objects that support the
5257 buffer protocol.
5258 byteorder: unicode
5259 The byte order used to represent the integer. If byteorder is 'big',
5260 the most significant byte is at the beginning of the byte array. If
5261 byteorder is 'little', the most significant byte is at the end of the
5262 byte array. To request the native byte order of the host system, use
5263 `sys.byteorder' as the byte order value.
5264 *
5265 signed as is_signed: bool = False
5266 Indicates whether two's complement is used to represent the integer.
5267
5268Return the integer represented by the given array of bytes.
5269[clinic start generated code]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005270
5271static PyObject *
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005272int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
5273 PyObject *byteorder, int is_signed)
5274/*[clinic end generated code: output=efc5d68e31f9314f input=cdf98332b6a821b0]*/
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 int little_endian;
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005277 PyObject *long_obj, *bytes;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005278
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005279 if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_little))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005280 little_endian = 1;
Serhiy Storchaka196a7bc2017-02-02 16:54:45 +02005281 else if (_PyUnicode_EqualToASCIIId(byteorder, &PyId_big))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 little_endian = 0;
5283 else {
5284 PyErr_SetString(PyExc_ValueError,
5285 "byteorder must be either 'little' or 'big'");
5286 return NULL;
5287 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005288
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005289 bytes = PyObject_Bytes(bytes_obj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005290 if (bytes == NULL)
5291 return NULL;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005293 long_obj = _PyLong_FromByteArray(
5294 (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
5295 little_endian, is_signed);
5296 Py_DECREF(bytes);
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005297
Serhiy Storchakaea36c942016-05-12 10:37:58 +03005298 if (type != &PyLong_Type) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01005299 Py_SETREF(long_obj, PyObject_CallFunctionObjArgs((PyObject *)type,
5300 long_obj, NULL));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 }
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005303 return long_obj;
Alexandre Vassalottic36c3782010-01-09 20:35:09 +00005304}
5305
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005306static PyMethodDef long_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 {"conjugate", (PyCFunction)long_long, METH_NOARGS,
5308 "Returns self, the complex conjugate of any int."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005309 INT_BIT_LENGTH_METHODDEF
Christian Heimes53876d92008-04-19 00:31:39 +00005310#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
5312 "Returns always True."},
Christian Heimes53876d92008-04-19 00:31:39 +00005313#endif
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005314 INT_TO_BYTES_METHODDEF
5315 INT_FROM_BYTES_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
5317 "Truncating an Integral returns itself."},
5318 {"__floor__", (PyCFunction)long_long, METH_NOARGS,
5319 "Flooring an Integral returns itself."},
5320 {"__ceil__", (PyCFunction)long_long, METH_NOARGS,
5321 "Ceiling of an Integral returns itself."},
5322 {"__round__", (PyCFunction)long_round, METH_VARARGS,
5323 "Rounding an Integral returns itself.\n"
5324 "Rounding with an ndigits argument also returns an integer."},
Serhiy Storchaka495e8802017-02-01 23:12:20 +02005325 INT___GETNEWARGS___METHODDEF
5326 INT___FORMAT___METHODDEF
5327 INT___SIZEOF___METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 {NULL, NULL} /* sentinel */
Guido van Rossum5d9113d2003-01-29 17:58:45 +00005329};
5330
Guido van Rossumb43daf72007-08-01 18:08:08 +00005331static PyGetSetDef long_getset[] = {
Mark Dickinson6bf19002009-05-02 17:57:52 +00005332 {"real",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005333 (getter)long_long, (setter)NULL,
5334 "the real part of a complex number",
5335 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005336 {"imag",
5337 (getter)long_get0, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005338 "the imaginary part of a complex number",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005339 NULL},
5340 {"numerator",
Guido van Rossumb43daf72007-08-01 18:08:08 +00005341 (getter)long_long, (setter)NULL,
5342 "the numerator of a rational number in lowest terms",
5343 NULL},
Mark Dickinson6bf19002009-05-02 17:57:52 +00005344 {"denominator",
5345 (getter)long_get1, (setter)NULL,
Guido van Rossumb43daf72007-08-01 18:08:08 +00005346 "the denominator of a rational number in lowest terms",
Mark Dickinson6bf19002009-05-02 17:57:52 +00005347 NULL},
Guido van Rossumb43daf72007-08-01 18:08:08 +00005348 {NULL} /* Sentinel */
5349};
5350
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005351PyDoc_STRVAR(long_doc,
svelankar390a0962017-03-08 19:29:01 -05005352"int([x]) -> integer\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005353int(x, base=10) -> integer\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +00005354\n\
Chris Jerdonek83fe2e12012-10-07 14:48:36 -07005355Convert a number or string to an integer, or return 0 if no arguments\n\
5356are given. If x is a number, return x.__int__(). For floating point\n\
5357numbers, this truncates towards zero.\n\
5358\n\
5359If x is not a number or if base is given, then x must be a string,\n\
5360bytes, or bytearray instance representing an integer literal in the\n\
5361given base. The literal can be preceded by '+' or '-' and be surrounded\n\
5362by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
5363Base 0 means to interpret the base from the string as an integer literal.\n\
5364>>> int('0b100', base=0)\n\
53654");
Tim Peters6d6c1a32001-08-02 04:15:00 +00005366
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005367static PyNumberMethods long_as_number = {
Mark Dickinson22b20182010-05-10 21:27:53 +00005368 (binaryfunc)long_add, /*nb_add*/
5369 (binaryfunc)long_sub, /*nb_subtract*/
5370 (binaryfunc)long_mul, /*nb_multiply*/
5371 long_mod, /*nb_remainder*/
5372 long_divmod, /*nb_divmod*/
5373 long_pow, /*nb_power*/
5374 (unaryfunc)long_neg, /*nb_negative*/
5375 (unaryfunc)long_long, /*tp_positive*/
5376 (unaryfunc)long_abs, /*tp_absolute*/
5377 (inquiry)long_bool, /*tp_bool*/
5378 (unaryfunc)long_invert, /*nb_invert*/
5379 long_lshift, /*nb_lshift*/
5380 (binaryfunc)long_rshift, /*nb_rshift*/
5381 long_and, /*nb_and*/
5382 long_xor, /*nb_xor*/
5383 long_or, /*nb_or*/
5384 long_long, /*nb_int*/
5385 0, /*nb_reserved*/
5386 long_float, /*nb_float*/
5387 0, /* nb_inplace_add */
5388 0, /* nb_inplace_subtract */
5389 0, /* nb_inplace_multiply */
5390 0, /* nb_inplace_remainder */
5391 0, /* nb_inplace_power */
5392 0, /* nb_inplace_lshift */
5393 0, /* nb_inplace_rshift */
5394 0, /* nb_inplace_and */
5395 0, /* nb_inplace_xor */
5396 0, /* nb_inplace_or */
5397 long_div, /* nb_floor_divide */
5398 long_true_divide, /* nb_true_divide */
5399 0, /* nb_inplace_floor_divide */
5400 0, /* nb_inplace_true_divide */
5401 long_long, /* nb_index */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005402};
5403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005404PyTypeObject PyLong_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 PyVarObject_HEAD_INIT(&PyType_Type, 0)
5406 "int", /* tp_name */
5407 offsetof(PyLongObject, ob_digit), /* tp_basicsize */
5408 sizeof(digit), /* tp_itemsize */
5409 long_dealloc, /* tp_dealloc */
5410 0, /* tp_print */
5411 0, /* tp_getattr */
5412 0, /* tp_setattr */
5413 0, /* tp_reserved */
5414 long_to_decimal_string, /* tp_repr */
5415 &long_as_number, /* tp_as_number */
5416 0, /* tp_as_sequence */
5417 0, /* tp_as_mapping */
5418 (hashfunc)long_hash, /* tp_hash */
5419 0, /* tp_call */
5420 long_to_decimal_string, /* tp_str */
5421 PyObject_GenericGetAttr, /* tp_getattro */
5422 0, /* tp_setattro */
5423 0, /* tp_as_buffer */
5424 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
5425 Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
5426 long_doc, /* tp_doc */
5427 0, /* tp_traverse */
5428 0, /* tp_clear */
5429 long_richcompare, /* tp_richcompare */
5430 0, /* tp_weaklistoffset */
5431 0, /* tp_iter */
5432 0, /* tp_iternext */
5433 long_methods, /* tp_methods */
5434 0, /* tp_members */
5435 long_getset, /* tp_getset */
5436 0, /* tp_base */
5437 0, /* tp_dict */
5438 0, /* tp_descr_get */
5439 0, /* tp_descr_set */
5440 0, /* tp_dictoffset */
5441 0, /* tp_init */
5442 0, /* tp_alloc */
5443 long_new, /* tp_new */
5444 PyObject_Del, /* tp_free */
Guido van Rossumedcc38a1991-05-05 20:09:44 +00005445};
Guido van Rossumddefaf32007-01-14 03:31:43 +00005446
Mark Dickinsonbd792642009-03-18 20:06:12 +00005447static PyTypeObject Int_InfoType;
5448
5449PyDoc_STRVAR(int_info__doc__,
5450"sys.int_info\n\
5451\n\
5452A struct sequence that holds information about Python's\n\
5453internal representation of integers. The attributes are read only.");
5454
5455static PyStructSequence_Field int_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005456 {"bits_per_digit", "size of a digit in bits"},
Mark Dickinson22b20182010-05-10 21:27:53 +00005457 {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 {NULL, NULL}
Mark Dickinsonbd792642009-03-18 20:06:12 +00005459};
5460
5461static PyStructSequence_Desc int_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 "sys.int_info", /* name */
5463 int_info__doc__, /* doc */
5464 int_info_fields, /* fields */
5465 2 /* number of fields */
Mark Dickinsonbd792642009-03-18 20:06:12 +00005466};
5467
5468PyObject *
5469PyLong_GetInfo(void)
5470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 PyObject* int_info;
5472 int field = 0;
5473 int_info = PyStructSequence_New(&Int_InfoType);
5474 if (int_info == NULL)
5475 return NULL;
5476 PyStructSequence_SET_ITEM(int_info, field++,
5477 PyLong_FromLong(PyLong_SHIFT));
5478 PyStructSequence_SET_ITEM(int_info, field++,
5479 PyLong_FromLong(sizeof(digit)));
5480 if (PyErr_Occurred()) {
5481 Py_CLEAR(int_info);
5482 return NULL;
5483 }
5484 return int_info;
Mark Dickinsonbd792642009-03-18 20:06:12 +00005485}
5486
Guido van Rossumddefaf32007-01-14 03:31:43 +00005487int
5488_PyLong_Init(void)
5489{
5490#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005491 int ival, size;
5492 PyLongObject *v = small_ints;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005494 for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++, v++) {
5495 size = (ival < 0) ? -1 : ((ival == 0) ? 0 : 1);
5496 if (Py_TYPE(v) == &PyLong_Type) {
5497 /* The element is already initialized, most likely
5498 * the Python interpreter was initialized before.
5499 */
5500 Py_ssize_t refcnt;
5501 PyObject* op = (PyObject*)v;
Christian Heimesdfc12ed2008-01-31 15:16:38 +00005502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005503 refcnt = Py_REFCNT(op) < 0 ? 0 : Py_REFCNT(op);
5504 _Py_NewReference(op);
5505 /* _Py_NewReference sets the ref count to 1 but
5506 * the ref count might be larger. Set the refcnt
5507 * to the original refcnt + 1 */
5508 Py_REFCNT(op) = refcnt + 1;
5509 assert(Py_SIZE(op) == size);
Victor Stinner12174a52014-08-15 23:17:38 +02005510 assert(v->ob_digit[0] == (digit)abs(ival));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 }
5512 else {
Christian Heimesd3afe782013-12-04 09:27:47 +01005513 (void)PyObject_INIT(v, &PyLong_Type);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 }
5515 Py_SIZE(v) = size;
Victor Stinner12174a52014-08-15 23:17:38 +02005516 v->ob_digit[0] = (digit)abs(ival);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005518#endif
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005519 _PyLong_Zero = PyLong_FromLong(0);
5520 if (_PyLong_Zero == NULL)
5521 return 0;
5522 _PyLong_One = PyLong_FromLong(1);
5523 if (_PyLong_One == NULL)
5524 return 0;
5525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 /* initialize int_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02005527 if (Int_InfoType.tp_name == NULL) {
5528 if (PyStructSequence_InitType2(&Int_InfoType, &int_info_desc) < 0)
5529 return 0;
5530 }
Mark Dickinsonbd792642009-03-18 20:06:12 +00005531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 return 1;
Guido van Rossumddefaf32007-01-14 03:31:43 +00005533}
5534
5535void
5536PyLong_Fini(void)
5537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005538 /* Integers are currently statically allocated. Py_DECREF is not
5539 needed, but Python must forget about the reference or multiple
5540 reinitializations will fail. */
Serhiy Storchakaba85d692017-03-30 09:09:41 +03005541 Py_CLEAR(_PyLong_One);
5542 Py_CLEAR(_PyLong_Zero);
Guido van Rossumddefaf32007-01-14 03:31:43 +00005543#if NSMALLNEGINTS + NSMALLPOSINTS > 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 int i;
5545 PyLongObject *v = small_ints;
5546 for (i = 0; i < NSMALLNEGINTS + NSMALLPOSINTS; i++, v++) {
5547 _Py_DEC_REFTOTAL;
5548 _Py_ForgetReference((PyObject*)v);
5549 }
Guido van Rossumddefaf32007-01-14 03:31:43 +00005550#endif
5551}